.classpath | 11 etc/agent-versioning/build.xml | 2 etc/apt/pom.xml | 2 etc/classloaders-test/plugin1/pom.xml | 2 etc/classloaders-test/plugin2/pom.xml | 2 etc/eclipse-tools/RHQ | 42 etc/samples/skeleton-plugin/pom.xml | 2 modules/common/drift/pom.xml | 2 modules/common/jboss-as-dmr-client/pom.xml | 2 modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/CoreJBossASClient.java | 79 modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java | 40 modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DeploymentJBossASClient.java | 32 modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/JBossASClient.java | 8 modules/core/arquillian-integration/container/src/test/resources/arquillian.xml | 9 modules/core/client-api/pom.xml | 2 modules/core/comm-api/pom.xml | 2 modules/core/dbutils/pom.xml | 2 modules/core/dbutils/src/main/scripts/dbsetup/2.3.1/db-data-combined-2.3.1.xml | 663 modules/core/dbutils/src/main/scripts/dbsetup/2.3.1/db-schema-combined-2.3.1.xml | 1916 -- modules/core/dbutils/src/main/scripts/dbsetup/2.4.0/db-data-combined-2.4.0.xml | 669 modules/core/dbutils/src/main/scripts/dbsetup/2.4.0/db-schema-combined-2.4.0.xml | 2494 ++ modules/core/domain/intentional-api-changes-since-4.5.1.xml | 21 modules/core/domain/pom.xml | 190 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AgentCriteria.java | 107 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ServerCriteria.java | 125 modules/core/domain/src/main/java/org/rhq/core/domain/resource/Agent.java | 3 modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceSyncResultsTest.java | 8 modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceTest.java | 13 modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDataAccessTest.java | 9 modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDefinitionTemplateTest.java | 13 modules/core/domain/src/test/java/org/rhq/core/domain/drift/JPADriftChangeSetTest.java | 23 modules/core/domain/src/test/java/org/rhq/core/domain/operation/OperationHistoryTest.java | 81 modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ProblemResourceTest.java | 1 modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java | 37 modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceGroupTest.java | 17 modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java | 44 modules/core/domain/src/test/resources/arquillian.xml | 5 modules/core/domain/src/test/resources/jbossas-oracle-ds.xml | 36 modules/core/domain/src/test/resources/jbossas-postgres-ds.xml | 40 modules/core/gui/pom.xml | 2 modules/core/plugin-container-itest/src/test/resources/arquillian.xml | 8 modules/core/util/pom.xml | 2 modules/enterprise/agent/ant-run.xml | 21 modules/enterprise/agent/src/etc/rhq-agent-env.sh | 4 modules/enterprise/agentupdate/pom.xml | 2 modules/enterprise/binding/pom.xml | 2 modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java | 17 modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java | 10 modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManager.java | 2 modules/enterprise/comm/pom.xml | 2 modules/enterprise/gui/content_http-war/pom.xml | 2 modules/enterprise/gui/coregui/pom.xml | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java | 265 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java | 55 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java | 127 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupTableView.java | 72 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupWithCountsDatasource.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java | 178 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java | 84 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java | 46 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasource.java | 188 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasourceField.java | 83 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java | 39 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java | 80 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java | 65 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventTableView.java | 259 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java | 66 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasourceField.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java | 58 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java | 145 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerWithAgentCountDatasource.java | 32 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java | 192 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/operation/schedule/GroupOperationScheduleDetailsView.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/operation/schedule/ResourceOperationScheduleDetailsView.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java | 94 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SystemGWTServiceImpl.java | 56 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties | 39 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties | 39 modules/enterprise/gui/installer/pom.xml | 413 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/client/Installer.java | 771 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/client/ServerPropertyRecordList.java | 62 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/client/gwt/InstallerGWTService.java | 132 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/client/shared/ServerDetails.java | 109 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/client/shared/ServerProperties.java | 174 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/server/service/ManagementService.java | 105 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/server/servlet/InstallerGWTServiceImpl.java | 782 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/server/servlet/LoggerAntBuildListener.java | 103 modules/enterprise/gui/installer/src/main/java/org/rhq/enterprise/gui/installer/server/servlet/ServerInstallUtil.java | 1303 - modules/enterprise/gui/installer/src/main/resources/org/rhq/enterprise/gui/installer/Installer.gwt.xml | 35 modules/enterprise/gui/installer/src/main/resources/org/rhq/enterprise/gui/installer/client/Messages.properties | 40 modules/enterprise/gui/installer/src/main/resources/org/rhq/enterprise/gui/installer/client/ServerPropertiesMessages.properties | 23 modules/enterprise/gui/installer/src/main/webapp/WEB-INF/classes/META-INF/services/org.jboss.msc.service.ServiceActivator | 1 modules/enterprise/gui/installer/src/main/webapp/WEB-INF/web.xml | 9 modules/enterprise/gui/installer/src/main/webapp/index.html | 45 modules/enterprise/gui/installer/src/test/java/org/rhq/enterprise/installer/DBInstallationTest.java | 225 modules/enterprise/gui/installer/src/test/java/org/rhq/enterprise/installer/client/controller/DatasourceJBossASClientTest.java | 118 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-data-combined-2.4.0.xml | 669 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-data-combined-3.0.0.xml | 690 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-data-combined-rhq-4.2.0.xml | 396 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-data-combined-rhq-4.3.0.xml | 398 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-data-combined-rhq-4.4.0.xml | 398 modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-schema-combined-2.4.0.xml | 2494 -- modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-schema-combined-3.0.0.xml | 2649 -- modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-schema-combined-rhq-4.2.0.xml | 2642 -- modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-schema-combined-rhq-4.3.0.xml | 2649 -- modules/enterprise/gui/installer/src/test/resources/org/rhq/enterprise/installer/db-schema-combined-rhq-4.4.0.xml | 2649 -- modules/enterprise/gui/pom.xml | 2 modules/enterprise/gui/portal-war/pom.xml | 2 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java | 21 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/client/RemoteClientServlet.java | 85 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/download/DownloadServlet.java | 122 modules/enterprise/gui/rest-examples-war/pom.xml | 133 modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/jboss-web.xml | 5 modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/web.xml | 27 modules/enterprise/gui/rest-examples-war/src/main/webapp/bars_simple.html | 131 modules/enterprise/gui/rest-examples-war/src/main/webapp/index.html | 40 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.behavior.js | 198 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.chart.js | 984 + modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.csv.js | 92 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geo.js | 938 + modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geom.js | 835 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.js | 4695 +++++ modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.layout.js | 1889 ++ modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.time.js | 687 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/jquery.js | 9266 ++++++++++ modules/enterprise/gui/rest-examples-war/src/main/webapp/js/resource_tree.js | 65 modules/enterprise/gui/rest-examples-war/src/main/webapp/js/rhq.js | 120 modules/enterprise/gui/rest-examples-war/src/main/webapp/raw_graph.html | 184 modules/enterprise/gui/rest-examples-war/src/main/webapp/raw_graph7.html | 225 modules/enterprise/gui/rest-examples-war/src/main/webapp/stacked1.html | 145 modules/enterprise/gui/rest-examples-war/src/main/webapp/stacked2.html | 139 modules/enterprise/gui/rest-examples-war/src/main/webapp/stacked3.html | 95 modules/enterprise/gui/rest-examples-war/src/main/webapp/tree.html | 44 modules/enterprise/gui/rest-examples-war/src/main/webapp/whisker.html | 53 modules/enterprise/gui/rest-examples-war/src/main/webapp/whisker2.html | 35 modules/enterprise/gui/rest-war/pom.xml | 7 modules/enterprise/gui/rest-war/src/main/java/org/rhq/enterprise/rest/RHQApplication.java | 41 modules/enterprise/gui/rest-war/src/main/webapp/WEB-INF/web.xml | 7 modules/enterprise/gui/rest-war/src/main/webapp/bars_simple.html | 131 modules/enterprise/gui/rest-war/src/main/webapp/index.html | 40 modules/enterprise/gui/rest-war/src/main/webapp/js/d3.behavior.js | 198 modules/enterprise/gui/rest-war/src/main/webapp/js/d3.chart.js | 984 - modules/enterprise/gui/rest-war/src/main/webapp/js/d3.csv.js | 92 modules/enterprise/gui/rest-war/src/main/webapp/js/d3.geo.js | 938 - modules/enterprise/gui/rest-war/src/main/webapp/js/d3.geom.js | 835 modules/enterprise/gui/rest-war/src/main/webapp/js/d3.js | 4695 ----- modules/enterprise/gui/rest-war/src/main/webapp/js/d3.layout.js | 1889 -- modules/enterprise/gui/rest-war/src/main/webapp/js/d3.time.js | 687 modules/enterprise/gui/rest-war/src/main/webapp/js/jquery.js | 9266 ---------- modules/enterprise/gui/rest-war/src/main/webapp/js/resource_tree.js | 65 modules/enterprise/gui/rest-war/src/main/webapp/js/rhq.js | 120 modules/enterprise/gui/rest-war/src/main/webapp/raw_graph.html | 184 modules/enterprise/gui/rest-war/src/main/webapp/raw_graph7.html | 225 modules/enterprise/gui/rest-war/src/main/webapp/stacked1.html | 145 modules/enterprise/gui/rest-war/src/main/webapp/stacked2.html | 139 modules/enterprise/gui/rest-war/src/main/webapp/stacked3.html | 95 modules/enterprise/gui/rest-war/src/main/webapp/tree.html | 44 modules/enterprise/gui/rest-war/src/main/webapp/whisker.html | 53 modules/enterprise/gui/rest-war/src/main/webapp/whisker2.html | 35 modules/enterprise/pom.xml | 4 modules/enterprise/remoting/cli/pom.xml | 2 modules/enterprise/remoting/cli/src/main/samples/measurement_utils.js | 4 modules/enterprise/scripting/api/pom.xml | 2 modules/enterprise/scripting/javascript/pom.xml | 2 modules/enterprise/scripting/python/pom.xml | 2 modules/enterprise/server/appserver/pom.xml | 12 modules/enterprise/server/appserver/src/main/bin-resources/bin/generate-db-password.bat | 115 modules/enterprise/server/appserver/src/main/bin-resources/bin/generate-db-password.sh | 159 modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.bat | 161 modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.sh | 243 modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.bat | 1 modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.sh | 106 modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat | 41 modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh | 29 modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml | 242 modules/enterprise/server/client-api/pom.xml | 9 modules/enterprise/server/client-api/src/main/java/org/rhq/enterprise/client/RhqDownloadsScriptSourceProvider.java | 32 modules/enterprise/server/client-api/src/test/java/org/rhq/enterprise/client/test/RhqDownloadsScriptSourceProviderTest.java | 20 modules/enterprise/server/container-lib/pom.xml | 107 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AccessCheckingInitialContextFactoryBuilder.java | 250 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AllowRhqServerInternalsAccessPermission.java | 36 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/DecoratingInitialContextFactory.java | 110 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecorator.java | 264 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecoratorSetContext.java | 75 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingDirContextDecorator.java | 187 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventContextDecorator.java | 69 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventDirContextDecorator.java | 96 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingLdapContextDecorator.java | 85 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/ContextDecorator.java | 33 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecorator.java | 222 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorHelper.java | 76 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorSetContext.java | 71 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringDirContextDecorator.java | 185 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventContextDecorator.java | 81 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventDirContextDecorator.java | 104 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringLdapContextDecorator.java | 94 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstaller.java | 45 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstallerMBean.java | 32 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratingInvocationHandler.java | 55 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorPicker.java | 195 modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorSetContext.java | 59 modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratingInvocationHandlerTest.java | 145 modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratorPickerTest.java | 180 modules/enterprise/server/ear/pom.xml | 77 modules/enterprise/server/ear/src/main/application/META-INF/jboss-deployment-structure.xml | 3 modules/enterprise/server/installer/pom.xml | 250 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/Installer.java | 252 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerConfiguration.java | 62 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerService.java | 196 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java | 989 + modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/LoggerAntBuildListener.java | 103 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ManagementService.java | 40 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerDetails.java | 105 modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java | 1259 + modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerProperties.java | 174 modules/enterprise/server/installer/src/main/resources/logging.properties | 27 modules/enterprise/server/installer/src/main/resources/module/main/module.xml | 35 modules/enterprise/server/installer/src/main/scripts/module-assembly.xml | 37 modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/DBInstallationTest.java | 213 modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/client/DatasourceJBossASClientTest.java | 119 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-data-combined-2.4.0.xml | 669 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-data-combined-3.0.0.xml | 690 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-data-combined-rhq-4.2.0.xml | 396 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-data-combined-rhq-4.3.0.xml | 398 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-data-combined-rhq-4.4.0.xml | 398 modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-schema-combined-2.4.0.xml | 2494 ++ modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-schema-combined-3.0.0.xml | 2649 ++ modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-schema-combined-rhq-4.2.0.xml | 2642 ++ modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-schema-combined-rhq-4.3.0.xml | 2649 ++ modules/enterprise/server/installer/src/test/resources/org/rhq/enterprise/server/installer/db-schema-combined-rhq-4.4.0.xml | 2649 ++ modules/enterprise/server/itests-2/pom.xml | 77 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java | 113 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/TestServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/bundle/TestBundleServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/content/test/ContentUIManagerBeanTest.java | 11 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/content/test/RepoSyncingTest.java | 71 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/core/CoreServerServiceImplTest.java | 15 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/core/plugin/DatabaseAndFilePluginDeploymentTest.java | 7 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/AbstractDriftServerTest.java | 36 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java | 7 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/DriftTemplateManagerBeanTest.java | 53 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java | 8 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/ManageDriftDefinitionsTest.java | 16 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/drift/ManageSnapshotsTest.java | 16 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java | 15 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java | 142 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/test/AvailabilityManagerTest.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/test/MeasurementBaselineManagerTest.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/plugin/pc/content/TestContentServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/plugin/pc/generic/TestGenericServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/resource/metadata/MetadataBeanTest.java | 36 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/resource/metadata/PluginManagerBeanTest.java | 10 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/resource/metadata/PluginScanningExtensionMetadataTest.java | 12 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java | 46 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/resource/metadata/test/UpdatePluginMetadataTestBase.java | 11 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java | 85 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/OldAbstractEJB3Test.java | 445 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StandardServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBean.java | 45 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBeanPreparation.java | 75 modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/TestServerPluginService.java | 2 modules/enterprise/server/itests-2/src/test/resources/arquillian.xml | 5 modules/enterprise/server/itests-2/src/test/resources/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest/dup_drift.xml | 2 modules/enterprise/server/itests-2/src/test/resources/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest/plugin_v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest/plugin_v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest/remove_bundle_drift_config_v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest/remove_bundle_drift_config_v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/security.policy | 10 modules/enterprise/server/itests-2/src/test/resources/test/metadata/alerts/type-with-metric.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/BZ_573034_v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/BZ_573034_v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/addDeleteTemplate1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/addDeleteTemplate2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/addDeleteTemplate3.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/constraint.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/constraintMinMax.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupDeleted-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupDeleted-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropDeleted-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropDeleted-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropDeleted-v3.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropMoved-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/groupPropMoved-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyChanging-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyChanging-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyList-simple.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyList-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyList-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyMap-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/propertyMap-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/update5-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/update5-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/updateDefaultTemplate1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/configuration/updateDefaultTemplate2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/events/event1-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/events/event1-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/measurementDeletion-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/measurementDeletion-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update6-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update6-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update7-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/measurement/update7-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/natives/update5-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/natives/update5-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/noTypes.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation1-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation1-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation2-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation2-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation3-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/operation3-2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/update3-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/operation/update3-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/duplicateResourceType.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/update2-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/update2-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/update4-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/update4-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/updateResourceTypeBundleTarget-v1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource-type/updateResourceTypeBundleTarget-v2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/illegal-subcat-1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-2children.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-grandchild.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-services-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-services-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-v1_1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/nested-subcat-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/no-subcat.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/one-subcat-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/one-subcat-v1_1.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/one-subcat-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/one-subcat-v3_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/services-v1_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/services-v2_0.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/test-subcategories.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/test-subcategories2.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/test-subcategories3.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/two-subcat.xml | 2 modules/enterprise/server/itests-2/src/test/resources/test/metadata/resource/undefined-child-subcat-1.xml | 2 modules/enterprise/server/jar/intentional-api-changes-since-4.5.1.xml | 24 modules/enterprise/server/jar/pom.xml | 128 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/AllowRhqServerInternalsAccessPermission.java | 36 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java | 6 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java | 12 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java | 10 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerRemote.java | 90 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java | 72 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerLocal.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java | 44 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java | 13 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java | 39 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServerMBean.java | 12 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/RemoteClientManagerBean.java | 149 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/RemoteClientManagerLocal.java | 67 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/ShutdownListener.java | 59 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/StartupBean.java | 76 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/plugin/PluginDeploymentScanner.java | 68 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/plugin/ProductPluginDeployer.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java | 320 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/DecoratingInitialContextFactory.java | 110 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java | 103 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecorator.java | 264 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecoratorSetContext.java | 75 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingDirContextDecorator.java | 187 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventContextDecorator.java | 69 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventDirContextDecorator.java | 96 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingLdapContextDecorator.java | 85 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/ContextDecorator.java | 33 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecorator.java | 222 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorHelper.java | 76 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorSetContext.java | 71 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringDirContextDecorator.java | 185 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventContextDecorator.java | 81 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventDirContextDecorator.java | 104 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringLdapContextDecorator.java | 94 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratingInvocationHandler.java | 55 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorPicker.java | 195 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorSetContext.java | 59 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginService.java | 6 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java | 117 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerLocal.java | 140 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/EventHandlerBean.java | 85 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/EventHandlerLocal.java | 121 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/GroupHandlerBean.java | 171 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/GroupHandlerLocal.java | 176 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/MetricHandlerBean.java | 167 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/MetricHandlerLocal.java | 254 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java | 100 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerLocal.java | 135 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RHQApplication.java | 44 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java | 173 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerLocal.java | 188 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java | 108 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java | 32 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerLocal.java | 58 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java | 50 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerLocal.java | 79 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/support/SupportManagerBean.java | 4 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java | 15 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/SystemManagerBean.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/system/SystemManagerLocal.java | 1 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java | 20 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/RemoteAPIValidator.java | 2 modules/enterprise/server/jar/src/main/resources/rest_templates/alert.ftl | 8 modules/enterprise/server/jar/src/main/resources/rest_templates/availability.ftl | 2 modules/enterprise/server/jar/src/main/resources/rest_templates/group.ftl | 6 modules/enterprise/server/jar/src/main/resources/rest_templates/groupDefinition.ftl | 2 modules/enterprise/server/jar/src/main/resources/rest_templates/index.ftl | 59 modules/enterprise/server/jar/src/main/resources/rest_templates/metricData.ftl | 2 modules/enterprise/server/jar/src/main/resources/rest_templates/resourceWithType.ftl | 16 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java | 144 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratorPickerTest.java | 180 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java | 260 modules/enterprise/server/plugins/alert-cli/pom.xml | 2 modules/enterprise/server/plugins/alert-email/pom.xml | 2 modules/enterprise/server/plugins/alert-irc/pom.xml | 2 modules/enterprise/server/plugins/alert-log4j/pom.xml | 2 modules/enterprise/server/plugins/alert-microblog/pom.xml | 2 modules/enterprise/server/plugins/alert-mobicents/pom.xml | 2 modules/enterprise/server/plugins/alert-operations/pom.xml | 2 modules/enterprise/server/plugins/alert-roles/pom.xml | 2 modules/enterprise/server/plugins/alert-scriptlang/pom.xml | 2 modules/enterprise/server/plugins/alert-sms/pom.xml | 2 modules/enterprise/server/plugins/alert-snmp/pom.xml | 2 modules/enterprise/server/plugins/alert-subject/pom.xml | 2 modules/enterprise/server/plugins/ant-bundle/pom.xml | 2 modules/enterprise/server/plugins/cloud/pom.xml | 2 modules/enterprise/server/plugins/cobbler/pom.xml | 2 modules/enterprise/server/plugins/disk/pom.xml | 2 modules/enterprise/server/plugins/drift-mongodb/pom.xml | 2 modules/enterprise/server/plugins/drift-rhq/pom.xml | 2 modules/enterprise/server/plugins/filetemplate-bundle/pom.xml | 2 modules/enterprise/server/plugins/groovy-script/pom.xml | 2 modules/enterprise/server/plugins/jboss-software/pom.xml | 2 modules/enterprise/server/plugins/packagetype-cli/pom.xml | 2 modules/enterprise/server/plugins/url/pom.xml | 2 modules/enterprise/server/plugins/yum/pom.xml | 2 modules/enterprise/server/pom.xml | 3 modules/enterprise/server/safe-invoker/pom.xml | 2 modules/enterprise/server/sars/agent-sar/src/main/resources/embedded-agent-configuration-overrides.properties | 2 modules/enterprise/server/sars/services-sar/pom.xml | 2 modules/enterprise/server/sars/services-sar/src/main/resources/META-INF/jboss-service.xml | 3 modules/enterprise/server/sars/services-sar/src/main/resources/server-comm-configuration-overrides.properties | 2 modules/enterprise/server/startup-subsystem/pom.xml | 61 modules/enterprise/server/startup-subsystem/src/main/java/org/rhq/enterprise/startup/StartupExtension.java | 24 modules/enterprise/server/startup-subsystem/src/main/java/org/rhq/enterprise/startup/StartupSubsystemAdd.java | 16 modules/enterprise/server/xml-schemas/pom.xml | 2 modules/helpers/rtfilter/pom.xml | 7 modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java | 7 modules/integration-tests/jndi-access/jndi-access-test/src/test/resources/arquillian.xml | 6 modules/integration-tests/mod_cluster-plugin-test/pom.xml | 2 modules/integration-tests/pom.xml | 2 modules/integration-tests/rest-api/pom.xml | 4 modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/GetStatusTest.java | 6 modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java | 4 modules/plugins/aliases/pom.xml | 2 modules/plugins/ant-bundle/pom.xml | 2 modules/plugins/apache/pom.xml | 2 modules/plugins/augeas/pom.xml | 2 modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/impl/DefaultAugeasTreeBuilder.java | 2 modules/plugins/byteman/pom.xml | 2 modules/plugins/cassandra/pom.xml | 307 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeComponent.java | 203 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/CassandraNodeDiscoveryComponent.java | 95 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/ColumnFamilyComponent.java | 266 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/ColumnFamilyDiscoveryComponent.java | 70 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/ComplexConfigurationResourceComponent.java | 125 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/KeyspaceComponent.java | 262 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/KeyspaceDiscoveryComponent.java | 114 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/MetricsDiscoveryComponent.java | 61 modules/plugins/cassandra/src/main/java/org/rhq/plugins/cassandra/StorageServiceComponent.java | 124 modules/plugins/cassandra/src/main/resources/META-INF/rhq-plugin.xml | 755 modules/plugins/cassandra/src/test/java/org/rhq/plugins/cassandra/itest/DiscoveryAndConfigurationTest.java | 268 modules/plugins/cobbler/pom.xml | 2 modules/plugins/cron/pom.xml | 2 modules/plugins/database/pom.xml | 2 modules/plugins/filetemplate-bundle/pom.xml | 2 modules/plugins/grub/pom.xml | 2 modules/plugins/hadoop/pom.xml | 2 modules/plugins/hardware/src/main/java/org/rhq/plugins/hardware/SmartDiskComponent.java | 4 modules/plugins/hibernate/pom.xml | 2 modules/plugins/hosts/pom.xml | 2 modules/plugins/iis/pom.xml | 2 modules/plugins/iptables/pom.xml | 2 modules/plugins/irc/pom.xml | 2 modules/plugins/jboss-as-5/pom.xml | 2 modules/plugins/jboss-as-5/src/test/resources/itest/arquillian.xml | 5 modules/plugins/jboss-as-7/pom.xml | 2 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java | 7 modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 4 modules/plugins/jboss-as-7/src/test/resources/itest/arquillian.xml | 5 modules/plugins/jboss-as/pom.xml | 2 modules/plugins/jboss-cache-v3/pom.xml | 2 modules/plugins/jboss-cache/pom.xml | 2 modules/plugins/jdbctrace/pom.xml | 2 modules/plugins/jira/pom.xml | 2 modules/plugins/jmx/pom.xml | 2 modules/plugins/jmx/src/main/java/org/rhq/plugins/jmx/JMXServerComponent.java | 46 modules/plugins/kickstart/pom.xml | 2 modules/plugins/lsof/pom.xml | 2 modules/plugins/mod-cluster/pom.xml | 4 modules/plugins/mysql/pom.xml | 2 modules/plugins/netservices/pom.xml | 2 modules/plugins/noop/pom.xml | 2 modules/plugins/nss/pom.xml | 2 modules/plugins/onewire/pom.xml | 2 modules/plugins/oracle/pom.xml | 2 modules/plugins/pattern-generator/pom.xml | 2 modules/plugins/perftest/pom.xml | 2 modules/plugins/platform/pom.xml | 2 modules/plugins/pom.xml | 1 modules/plugins/postfix/pom.xml | 2 modules/plugins/postgres/pom.xml | 2 modules/plugins/raw-config-test/pom.xml | 2 modules/plugins/rhq-agent/pom.xml | 2 modules/plugins/rhq-server/pom.xml | 2 modules/plugins/samba/pom.xml | 2 modules/plugins/script/pom.xml | 2 modules/plugins/script2/pom.xml | 2 modules/plugins/services/pom.xml | 2 modules/plugins/snmptrapd/pom.xml | 2 modules/plugins/sshd/pom.xml | 2 modules/plugins/sudoers/pom.xml | 2 modules/plugins/tomcat/pom.xml | 2 modules/plugins/twitter/pom.xml | 2 modules/plugins/virt/pom.xml | 2 modules/pom.xml | 1 pom.xml | 44 543 files changed, 55208 insertions(+), 50955 deletions(-)
New commits: commit 49c19bafe83b2b2f55f514c51d34eb88fe960304 Author: Jirka Kremser jkremser@redhat.com Date: Wed Dec 19 21:10:31 2012 +0100
the rest of l10n for error and other messages, some javadoc
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java index 5515e18..b1a1a6c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java @@ -22,7 +22,7 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_NAME;
import java.util.ArrayList; import java.util.List; @@ -31,7 +31,6 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.events.ClickEvent; @@ -47,6 +46,7 @@ import com.smartgwt.client.widgets.layout.VLayout; import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.IconEnum; import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; @@ -64,6 +64,7 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr
private static RPCDataSource<Agent, AgentCriteria> datasource = null;
+ private static final int MAX_AVAIL_AGENTS = 3000; private static Window modalWindow; private static boolean shouldBeClosed; private static VLayout layout; @@ -79,13 +80,13 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr this.affinityGroupId = affinityGroupId; prepareMembers(this); } - + @Override protected DynamicForm getAvailableFilterForm() { if (availableFilterForm == null) { - availableFilterForm = new LocatableDynamicForm(extendLocatorId("AgeSelectAvailFilterForm")); + availableFilterForm = new LocatableDynamicForm(extendLocatorId("AgentSelectAvailFilterForm")); availableFilterForm.setWidth("75%"); - final TextItem search = new TextItem(NAME.propertyName(), MSG.common_title_search()); + final TextItem search = new TextItem(FIELD_NAME.propertyName(), MSG.common_title_search()); availableFilterForm.setItems(search); } return availableFilterForm; @@ -95,21 +96,21 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr AgentCriteria criteria = new AgentCriteria(); criteria.addFilterAffinityGroupId(affinityGroupId); GWTServiceLookup.getCloudService().findAgentsByCriteria(criteria, new AsyncCallback<PageList<Agent>>() { - public void onSuccess(PageList<Agent> result) { - ListGridRecord[] records = getDataSource().buildRecords(result); - originallyAssignedIds = getIdList(records); - setAssigned(records); - modalWindow.addItem(layout); - modalWindow.show(); - selector.reset(); - } - - @Override - public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); - } - }); + public void onSuccess(PageList<Agent> result) { + ListGridRecord[] records = getDataSource().buildRecords(result); + originallyAssignedIds = getIdList(records); + setAssigned(records); + modalWindow.addItem(layout); + modalWindow.show(); + selector.reset(); + }
+ @Override + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchAgentsFail(String.valueOf(affinityGroupId)), t); + } + }); }
@Override @@ -122,15 +123,15 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr
@Override protected int getMaxAvailableRecords() { - return 3000; + return MAX_AVAIL_AGENTS; }
@Override protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { - String search = (String) availableFilterForm.getValue(NAME.propertyName()); + String search = (String) availableFilterForm.getValue(FIELD_NAME.propertyName()); Criteria criteria = new Criteria(); if (null != search) { - criteria.addCriteria(NAME.propertyName(), search); + criteria.addCriteria(FIELD_NAME.propertyName(), search); } return criteria; } @@ -145,15 +146,15 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr return IconEnum.AGENT.getIcon16x16Path(); }
- public static void show(Integer affinityGroupId, final TableSection parrent) { + public static void show(final Integer affinityGroupId, final TableSection<?> parrent) { modalWindow = new Window(); modalWindow.addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(CloseClickEvent event) { closeAndRefresh(parrent, false); } }); - modalWindow.setTitle(MSG.view_adminTopology_agents() + ": " - + MSG.view_adminTopology_affinityGroups_createNew()); + modalWindow + .setTitle(MSG.view_adminTopology_agents() + ": " + MSG.view_adminTopology_affinityGroups_createNew()); modalWindow.setOverflow(Overflow.VISIBLE); modalWindow.setWidth(800); modalWindow.setHeight(400); @@ -167,7 +168,7 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr layout.setPadding(10); layout.setLayoutMargin(10);
- final AffinityGroupAgentsSelector selector = new AffinityGroupAgentsSelector("foo", affinityGroupId); + final AffinityGroupAgentsSelector selector = new AffinityGroupAgentsSelector("assignAgents", affinityGroupId); layout.addMember(selector);
IButton cancel = new LocatableIButton(selector.extendLocatorId("Cancel"), MSG.common_button_cancel()); @@ -193,9 +194,10 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr closeAndRefresh(parrent, true); }
- public void onFailure(Throwable caught) { - //todo: error handling - SC.say("errX"); + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_agroupAssingAgentsFail(String + .valueOf(affinityGroupId)), t); } }); } @@ -208,17 +210,16 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr closeAndRefresh(parrent, true); }
- public void onFailure(Throwable caught) { - //todo: error handling - SC.say("errX"); + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_agroupRemovingAgentsFail(String + .valueOf(affinityGroupId)), t); } }); } if (shouldBeClosed) { closeAndRefresh(parrent, false); } - // SC.say("To del: " + originallySelected + "\n\nTo add: " + actuallySelected); - } });
@@ -231,7 +232,7 @@ public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCr layout.addMember(buttons); }
- private static void closeAndRefresh(TableSection parrent, boolean fullRefresh) { + private static void closeAndRefresh(TableSection<?> parrent, boolean fullRefresh) { if (modalWindow != null) { modalWindow.destroy(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java index 4355814..fbd832e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java @@ -25,7 +25,6 @@ import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -35,9 +34,11 @@ import com.smartgwt.client.widgets.layout.SectionStackSection;
import org.rhq.core.domain.cloud.AffinityGroup; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.Log; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; @@ -50,7 +51,6 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class AffinityGroupDetailView extends LocatableVLayout implements BookmarkableView {
- // private final CloudGWTServiceAsync cloudManager = GWTServiceLookup.getCloudService(); private final int affinityGroupId;
private static final int SECTION_COUNT = 3; @@ -79,28 +79,18 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar @Override protected void onInit() { super.onInit(); - GWTServiceLookup.getCloudService().getAffinityGroupById(this.affinityGroupId, - new AsyncCallback<AffinityGroup>() { - public void onSuccess(final AffinityGroup affinityGroup) { - prepareDetailsSection(sectionStack, affinityGroup); - - // GWTServiceLookup.getCloudService().getAgentsByServerName(server.getName(), - // new AsyncCallback<List<Agent>>() { - // public void onSuccess(List<Agent> agents) { - // prepareAgentSection(sectionStack, server, agents); - // }; - // - // public void onFailure(Throwable caught) { - // //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); - // } - // }); - } + GWTServiceLookup.getCloudService().getAffinityGroupById(affinityGroupId, new AsyncCallback<AffinityGroup>() { + public void onSuccess(final AffinityGroup affinityGroup) { + prepareDetailsSection(sectionStack, affinityGroup); + }
- public void onFailure(Throwable caught) { - SC.say("er1:" + caught); - //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); - } - }); + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchAgroupFail(String.valueOf(affinityGroupId)), caught); + initSectionCount = SECTION_COUNT; + return; + } + }); prepareAgentSection(sectionStack); prepareServerSection(sectionStack); } @@ -178,7 +168,7 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar
final TextItem nameItem = new TextItem(FIELD_NAME.propertyName(), FIELD_NAME.title()); nameItem.setValue(affinityGroup.getName()); - + LocatableToolStrip footer = new LocatableToolStrip(extendLocatorId("detailsFooter")); footer.setPadding(5); footer.setWidth100(); @@ -187,25 +177,27 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar IButton saveButton = new IButton(); saveButton.setOverflow(Overflow.VISIBLE); saveButton.setTitle(MSG.common_button_save()); -// saveButton.setWidth(70); saveButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { affinityGroup.setName(nameItem.getValueAsString()); GWTServiceLookup.getCloudService().updateAffinityGroup(affinityGroup, new AsyncCallback<Void>() { public void onSuccess(Void result) { - // todo: notify + Message msg = new Message(MSG.view_adminTopology_message_agroupRenamed( + String.valueOf(affinityGroupId), affinityGroup.getName(), nameItem.getValueAsString()), + Message.Severity.Info); + CoreGUI.getMessageCenter().notify(msg); }
public void onFailure(Throwable caught) { - // todo: handle + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_agroupRenamingFail(String.valueOf(affinityGroupId), + affinityGroup.getName()) + " " + caught.getMessage(), caught); } }); } }); footer.addMember(saveButton); - form.setItems(nameItem); - SectionStackSection section = new SectionStackSection(MSG.common_title_details()); section.setExpanded(true); section.setItems(form, footer); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java index 13b1559..803214c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java @@ -22,7 +22,7 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_NAME;
import java.util.ArrayList; import java.util.List; @@ -31,7 +31,6 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.events.ClickEvent; @@ -49,6 +48,7 @@ import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.Server.OperationMode; import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.IconEnum; import org.rhq.enterprise.gui.coregui.client.components.form.SortedSelectItem; import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; @@ -82,27 +82,24 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve this.affinityGroupId = affinityGroupId; prepareMembers(this); } - + @Override protected DynamicForm getAvailableFilterForm() { if (availableFilterForm == null) { availableFilterForm = new LocatableDynamicForm(extendLocatorId("SerSelectAvailFilterForm")); availableFilterForm.setNumCols(4); availableFilterForm.setWidth("75%"); - final TextItem search = new TextItem(NAME.propertyName(), MSG.common_title_search()); - final SelectItem operationModeSelect = new SortedSelectItem(ServerDatasource.FILTER_OPERATION_MODE, MSG.view_adminTopology_serverDetail_operationMode()); + final TextItem search = new TextItem(FIELD_NAME.propertyName(), MSG.common_title_search()); + final SelectItem operationModeSelect = new SortedSelectItem(ServerDatasource.FILTER_OPERATION_MODE, + MSG.view_adminTopology_serverDetail_operationMode()); operationModeSelect.setValueMap(buildOperationModeOptions()); operationModeSelect.setValue("ALL"); -// -// final EnumSelectItem operationModeFilter = new EnumSelectItem(ServerDatasource.FILTER_OPERATION_MODE, -// MSG.view_adminTopology_serverDetail_operationMode(), OperationMode.class, null, null); -
availableFilterForm.setItems(search, operationModeSelect); } return availableFilterForm; } - + private String[] buildOperationModeOptions() { OperationMode[] modes = OperationMode.values(); String[] options = new String[modes.length + 1]; @@ -117,27 +114,28 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve ServerCriteria criteria = new ServerCriteria(); criteria.addFilterAffinityGroupId(affinityGroupId); GWTServiceLookup.getCloudService().findServersByCriteria(criteria, new AsyncCallback<PageList<Server>>() { - public void onSuccess(PageList<Server> result) { - ListGridRecord[] records = getDataSource().buildRecords(result); - originallyAssignedIds = getIdList(records); - setAssigned(records); - modalWindow.addItem(layout); - modalWindow.show(); - selector.reset(); - } + public void onSuccess(PageList<Server> result) { + ListGridRecord[] records = getDataSource().buildRecords(result); + originallyAssignedIds = getIdList(records); + setAssigned(records); + modalWindow.addItem(layout); + modalWindow.show(); + selector.reset(); + }
- @Override - public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); - } - }); + @Override + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchServersFail(String.valueOf(affinityGroupId)), t); + } + });
}
@Override protected RPCDataSource<Server, ServerCriteria> getDataSource() { if (datasource == null) { - datasource = new ServerDatasource(affinityGroupId, false); + datasource = new ServerDatasource(null); } return datasource; } @@ -149,11 +147,11 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve
@Override protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { - String search = (String) availableFilterForm.getValue(NAME.propertyName()); + String search = (String) availableFilterForm.getValue(FIELD_NAME.propertyName()); String operationMode = (String) availableFilterForm.getValue(ServerDatasource.FILTER_OPERATION_MODE); Criteria criteria = new Criteria(); if (null != search) { - criteria.addCriteria(NAME.propertyName(), search); + criteria.addCriteria(FIELD_NAME.propertyName(), search); } if (operationMode != null && !"ALL".equals(operationMode)) { criteria.addCriteria(ServerDatasource.FILTER_OPERATION_MODE, operationMode); @@ -171,7 +169,7 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve return IconEnum.SERVERS.getIcon16x16Path(); }
- public static void show(Integer affinityGroupId, final TableSection parrent) { + public static void show(final Integer affinityGroupId, final TableSection<?> parrent) { modalWindow = new Window(); modalWindow.addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(CloseClickEvent event) { @@ -193,7 +191,7 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve layout.setPadding(10); layout.setLayoutMargin(10);
- final AffinityGroupServersSelector selector = new AffinityGroupServersSelector("foo", affinityGroupId); + final AffinityGroupServersSelector selector = new AffinityGroupServersSelector("assignServers", affinityGroupId); layout.addMember(selector);
IButton cancel = new LocatableIButton(selector.extendLocatorId("Cancel"), MSG.common_button_cancel()); @@ -214,14 +212,14 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve shouldBeClosed = false; GWTServiceLookup.getCloudService().removeServersFromGroup( originallySelected.toArray(new Integer[originallySelected.size()]), new AsyncCallback<Void>() { - public void onSuccess(Void result) { closeAndRefresh(parrent, true); }
- public void onFailure(Throwable caught) { - //todo: error handling - SC.say("errX"); + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_agroupAssingServersFail(String + .valueOf(affinityGroupId)), t); } }); } @@ -229,22 +227,20 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve shouldBeClosed = false; GWTServiceLookup.getCloudService().addServersToGroup(selector.getAffinityGroupId(), actuallySelected.toArray(new Integer[actuallySelected.size()]), new AsyncCallback<Void>() { - public void onSuccess(Void result) { closeAndRefresh(parrent, true); }
- public void onFailure(Throwable caught) { - //todo: error handling - SC.say("errX"); + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_agroupRemovingServersFail(String + .valueOf(affinityGroupId)), t); } }); } if (shouldBeClosed) { closeAndRefresh(parrent, false); } - // SC.say("To del: " + originallySelected + "\n\nTo add: " + actuallySelected); - } });
@@ -257,7 +253,7 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve layout.addMember(buttons); }
- private static void closeAndRefresh(TableSection parrent, boolean fullRefresh) { + private static void closeAndRefresh(TableSection<?> parrent, boolean fullRefresh) { if (modalWindow != null) { modalWindow.destroy(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupTableView.java index ac44d44..dbe8d0f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupTableView.java @@ -36,6 +36,8 @@ import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.TextItem; +import com.smartgwt.client.widgets.form.fields.events.KeyUpEvent; +import com.smartgwt.client.widgets.form.fields.events.KeyUpHandler; import com.smartgwt.client.widgets.form.validator.LengthRangeValidator; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; @@ -98,32 +100,29 @@ public class AffinityGroupTableView extends TableSection<AffinityGroupWithCounts } });
- addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), - MSG.common_msg_areYouSure(), new AuthorizedTableAction(this, TableActionEnablement.ANY, - Permission.MANAGE_SETTINGS) { + addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), null, + new AuthorizedTableAction(this, TableActionEnablement.ANY, Permission.MANAGE_SETTINGS) { public void executeAction(final ListGridRecord[] selections, Object actionValue) { - List<String> selectedNames = getSelectedNames(selections); - String message = "Really? Delete? For all I've done for you? " + selectedNames; + final List<String> selectedNames = getSelectedNames(selections); + String message = MSG.view_adminTopology_message_removeAGroupsConfirm(selectedNames.toString()); SC.ask(message, new BooleanCallback() { public void execute(Boolean confirmed) { if (confirmed) { int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); GWTServiceLookup.getCloudService().deleteAffinityGroups(selectedIds, new AsyncCallback<Integer>() { public void onSuccess(Integer count) { - // TODO: msg with count Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); + .view_adminTopology_message_removedAGroups(String.valueOf(count)), + Message.Severity.Info); CoreGUI.getMessageCenter().notify(msg); refresh(); }
public void onFailure(Throwable caught) { - // TODO: msg CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); + MSG.view_adminTopology_message_removeAGroupsFail(selectedNames + .toString()) + " " + caught.getMessage(), caught); refreshTableInfo(); }
@@ -190,9 +189,16 @@ public class AffinityGroupTableView extends TableSection<AffinityGroupWithCounts nameLengthValidator.setMin(3); nameLengthValidator.setMax(100); name.setValidators(nameLengthValidator); + name.addKeyUpHandler(new KeyUpHandler() { + public void onKeyUp(KeyUpEvent event) { + if ("Enter".equals(event.getKeyName())) { + createNewGroup(modalWindow, form); + } + } + }); + form.setFields(name); layout.addMember(form); - VLayout spacer = new VLayout(); spacer.setHeight(10); layout.addMember(spacer); @@ -203,32 +209,17 @@ public class AffinityGroupTableView extends TableSection<AffinityGroupWithCounts modalWindow.destroy(); } }); - IButton save = new LocatableIButton(this.extendLocatorId("Create"), + final IButton create = new LocatableIButton(this.extendLocatorId("Create"), MSG.view_adminTopology_affinityGroups_createNew()); - save.addClickHandler(new ClickHandler() { + create.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { - if (form.validate()) { - String name = form.getValueAsString(FIELD_NAME); - AffinityGroup affinityGroup = new AffinityGroup(name); - GWTServiceLookup.getCloudService().createAffinityGroup(affinityGroup, new AsyncCallback<Integer>() { - public void onSuccess(Integer affinityGroupId) { - modalWindow.destroy(); - CoreGUI.goToView(VIEW_PATH + "/" + affinityGroupId); - } - - public void onFailure(Throwable caught) { - Map<String, String> errors = new HashMap<String, String>(); - errors.put(FIELD_NAME, caught.getMessage()); - form.setErrors(errors, true); - } - }); - } + createNewGroup(modalWindow, form); } });
HLayout buttons = new HLayout(10); buttons.setLayoutAlign(Alignment.CENTER); - buttons.addMember(save); + buttons.addMember(create); buttons.addMember(cancel); layout.addMember(buttons); modalWindow.addItem(layout); @@ -236,6 +227,25 @@ public class AffinityGroupTableView extends TableSection<AffinityGroupWithCounts name.focusInItem(); }
+ private void createNewGroup(final Window modalWindow, final DynamicForm form) { + if (form.validate()) { + String name = form.getValueAsString(FIELD_NAME); + AffinityGroup affinityGroup = new AffinityGroup(name); + GWTServiceLookup.getCloudService().createAffinityGroup(affinityGroup, new AsyncCallback<Integer>() { + public void onSuccess(Integer affinityGroupId) { + modalWindow.destroy(); + CoreGUI.goToView(VIEW_PATH + "/" + affinityGroupId); + } + + public void onFailure(Throwable caught) { + Map<String, String> errors = new HashMap<String, String>(); + errors.put(FIELD_NAME, caught.getMessage()); + form.setErrors(errors, true); + } + }); + } + } + @Override public ViewName getViewName() { return VIEW_ID; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupWithCountsDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupWithCountsDatasource.java index e08a88e..bd8b6b3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupWithCountsDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupWithCountsDatasource.java @@ -55,14 +55,7 @@ public class AffinityGroupWithCountsDatasource extends RPCDataSource<AffinityGro
FIELD_SERVER_COUNT("serverCount", CoreGUI.getMessages().view_adminTopology_affinityGroups_serverCount());
- /** - * Corresponds to a property name of Server (e.g. operationMode). - */ private String propertyName; - - /** - * The table header for the field or property (e.g. Mode). - */ private String title;
private Fields(String propertyName, String title) { @@ -131,8 +124,8 @@ public class AffinityGroupWithCountsDatasource extends RPCDataSource<AffinityGro processResponse(request.getRequestId(), response); }
- public void onFailure(Throwable caught) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + public void onFailure(Throwable t) { + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchAgroupsFail(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java index ac1d26b..dd596e9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java @@ -42,9 +42,8 @@ import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.resource.Agent; -import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; -import org.rhq.core.domain.util.PageOrdering; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.Log; @@ -61,7 +60,6 @@ public class AgentDatasource extends RPCDataSource<Agent, AgentCriteria> { public static final String FILTER_PORT = FIELD_PORT.propertyName(); public static final String FILTER_SERVER_ID = "serverId"; public static final String FILTER_AFFINITY_GROUP_ID = "affinityGroupId"; -
private final Integer id; private final boolean isAffinityGroupId; @@ -115,31 +113,10 @@ public class AgentDatasource extends RPCDataSource<Agent, AgentCriteria> {
@Override protected void executeFetch(final DSRequest request, final DSResponse response, AgentCriteria criteria) { -// final PageControl pc = getPageControl(request); - -// AsyncCallback<PageList<Agent>> callback = new AsyncCallback<PageList<Agent>>() { -// public void onSuccess(PageList<Agent> result) { -// response.setData(buildRecords(result)); -// response.setTotalRows(result.size()); -// processResponse(request.getRequestId(), response); -// } -// -// @Override -// public void onFailure(Throwable t) { -// //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); -// response.setStatus(DSResponse.STATUS_FAILURE); -// processResponse(request.getRequestId(), response); -// } -// }; -// -// if (isAffinityGroupId) { -// GWTServiceLookup.getCloudService().getAgentMembersByAffinityGroupId(id, pc, callback); criteria.addFilterAffinityGroupId(id); - } else if (id != null) { - // if id == null all agent are returned + } else { criteria.addFilterServerId(id); -// GWTServiceLookup.getAgentService().getAgentsByServer(id, pc, callback); }
GWTServiceLookup.getCloudService().findAgentsByCriteria(criteria, new AsyncCallback<PageList<Agent>>() { @@ -151,38 +128,13 @@ public class AgentDatasource extends RPCDataSource<Agent, AgentCriteria> {
@Override public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchAgents2Fail(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } }); }
- /** - * Returns a prepopulated PageControl based on the provided DSRequest. This will set sort fields, - * pagination, but *not* filter fields. - * - * @param request the request to turn into a page control - * @return the page control for passing to criteria and other queries - */ - protected PageControl getPageControl(DSRequest request) { - // Initialize paging. - PageControl pageControl = new PageControl(0, getDataPageSize()); - - // Initialize sorting. - String sortBy = request.getAttribute("sortBy"); - if (sortBy != null) { - String[] sorts = sortBy.split(","); - for (String sort : sorts) { - PageOrdering ordering = (sort.startsWith("-")) ? PageOrdering.DESC : PageOrdering.ASC; - String columnName = (ordering == PageOrdering.DESC) ? sort.substring(1) : sort; - pageControl.addDefaultOrderingField(columnName, ordering); - } - } - - return pageControl; - } - @Override public Agent copyValues(Record from) { throw new UnsupportedOperationException("AgentNodeDatasource.copyValues(Record from)"); @@ -216,7 +168,6 @@ public class AgentDatasource extends RPCDataSource<Agent, AgentCriteria> { criteria.addFilterPort(getFilter(request, FILTER_PORT, Integer.class)); criteria.addFilterServerId(getFilter(request, FILTER_SERVER_ID, Integer.class)); criteria.addFilterAffinityGroupId(getFilter(request, FILTER_AFFINITY_GROUP_ID, Integer.class)); -
//@todo: Remove me when finished debugging search expression Log.debug(" *** AgentCriteria Search String: " + getFilter(request, "search", String.class)); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java index 26792d4..7935446 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java @@ -33,19 +33,20 @@ public enum AgentDatasourceField { FIELD_NAME("name", CoreGUI.getMessages().common_title_name()),
FIELD_SERVER("server", CoreGUI.getMessages().view_adminTopology_agent_connectedServer()), - + FIELD_SERVER_ID("serverId", "serverId"),
FIELD_ADDRESS("address", CoreGUI.getMessages().view_adminTopology_agent_agentBindAddress()),
FIELD_PORT("port", CoreGUI.getMessages().view_adminTopology_agent_agentBindPort()),
- FIELD_LAST_AVAILABILITY_REPORT("lastAvailabilityReport", CoreGUI.getMessages().view_adminTopology_agent_lastAvailabilityReport()), + FIELD_LAST_AVAILABILITY_REPORT("lastAvailabilityReport", CoreGUI.getMessages() + .view_adminTopology_agent_lastAvailabilityReport()),
FIELD_AGENT_TOKEN("agentToken", CoreGUI.getMessages().view_adminTopology_agentDetail_token()),
FIELD_AFFINITY_GROUP("affinityGroup", CoreGUI.getMessages().view_adminTopology_server_affinityGroup()), - + FIELD_AFFINITY_GROUP_ID("affinityGroupId", "affinityGroupId");
/** diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java index f48e7b7..7e5c3ac 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java @@ -31,7 +31,6 @@ import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java index dc34602..8c47813 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java @@ -55,7 +55,7 @@ public class AgentTableView extends TableSection<AgentDatasource> implements Has + AdministrationView.SECTION_TOPOLOGY_VIEW_ID + "/" + VIEW_ID;
private final boolean isAffinityGroupId; - + private final Integer id;
public AgentTableView(String locatorId, Integer id, boolean isAffinityGroupId) { @@ -91,7 +91,7 @@ public class AgentTableView extends TableSection<AgentDatasource> implements Has } }); } else if (field.getName() == FIELD_SERVER.propertyName()) { - // adding the cell formatter for server field (clickable link) + // adding the cell formatter for server field (clickable link) field.setCellFormatter(new CellFormatter() { @Override public String format(Object value, ListGridRecord record, int rowNum, int colNum) { @@ -105,7 +105,7 @@ public class AgentTableView extends TableSection<AgentDatasource> implements Has } }); } else if (field.getName() == FIELD_AFFINITY_GROUP.propertyName()) { - // adding the cell formatter for affinity group field (clickable link) + // adding the cell formatter for affinity group field (clickable link) field.setCellFormatter(new CellFormatter() { @Override public String format(Object value, ListGridRecord record, int rowNum, int colNum) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java index 6dd2430..6bfa378 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java @@ -43,6 +43,7 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.cloud.FailoverListDetails; import org.rhq.core.domain.criteria.Criteria; import org.rhq.core.domain.util.PageControl; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
@@ -53,14 +54,14 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; public class FailoverListItemDatasource extends AbstractServerNodeDatasource<FailoverListDetails, Criteria> {
private final int agentId; - + // this delegate is there to not repeat the copyValues code private final ServerDatasource serverDatasource;
public FailoverListItemDatasource(int agentId) { super(); this.agentId = agentId; - this.serverDatasource = new ServerDatasource(null, false); + this.serverDatasource = new ServerDatasource(null); List<DataSourceField> fields = addDataSourceFields(); addFields(fields); } @@ -111,13 +112,14 @@ public class FailoverListItemDatasource extends AbstractServerNodeDatasource<Fai
@Override public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchFailOverLists(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } }); }
+ @Override protected PageControl getPageControl(DSRequest request) { return serverDatasource.getPageControl(request); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java index f77a843..c3d103b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java @@ -27,7 +27,6 @@ import static org.rhq.enterprise.gui.coregui.client.admin.topology.PartitionEven
import java.util.ArrayList; import java.util.List; -import java.util.Map;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; @@ -42,11 +41,11 @@ import org.rhq.core.domain.cloud.PartitionEvent; import org.rhq.core.domain.cloud.PartitionEvent.ExecutionStatus; import org.rhq.core.domain.cloud.PartitionEventType; import org.rhq.core.domain.criteria.PartitionEventCriteria; -import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; -import org.rhq.core.domain.util.PageOrdering; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.Log; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
/** @@ -95,8 +94,6 @@ public class PartitionEventDatasource extends RPCDataSource<PartitionEvent, Part
@Override protected void executeFetch(final DSRequest request, final DSResponse response, PartitionEventCriteria criteria) { - // final PageControl pc = getPageControl(request); - GWTServiceLookup.getCloudService().findPartitionEventsByCriteria(criteria, new AsyncCallback<PageList<PartitionEvent>>() { public void onSuccess(PageList<PartitionEvent> result) { @@ -107,38 +104,13 @@ public class PartitionEventDatasource extends RPCDataSource<PartitionEvent, Part
@Override public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchPEventFail(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } }); }
- /** - * Returns a prepopulated PageControl based on the provided DSRequest. This will set sort fields, - * pagination, but *not* filter fields. - * - * @param request the request to turn into a page control - * @return the page control for passing to criteria and other queries - */ - protected PageControl getPageControl(DSRequest request) { - // Initialize paging. - PageControl pageControl = new PageControl(0, getDataPageSize()); - - // Initialize sorting. - String sortBy = request.getAttribute("sortBy"); - if (sortBy != null) { - String[] sorts = sortBy.split(","); - for (String sort : sorts) { - PageOrdering ordering = (sort.startsWith("-")) ? PageOrdering.DESC : PageOrdering.ASC; - String columnName = (ordering == PageOrdering.DESC) ? sort.substring(1) : sort; - pageControl.addDefaultOrderingField(columnName, ordering); - } - } - - return pageControl; - } - @Override public PartitionEvent copyValues(Record from) { throw new UnsupportedOperationException("PartitionEventDatasource.copyValues(Record from)"); @@ -150,46 +122,27 @@ public class PartitionEventDatasource extends RPCDataSource<PartitionEvent, Part record.setAttribute(FIELD_ID.propertyName(), from.getId()); record.setAttribute(FIELD_CTIME.propertyName(), from.getCtime()); record.setAttribute(FIELD_EVENT_TYPE.propertyName(), from.getEventType() == null ? "" : from.getEventType()); - record.setAttribute(FIELD_EVENT_DETAIL.propertyName(), from.getEventDetail() == null ? "" : from.getEventDetail()); - record.setAttribute(FIELD_SUBJECT_NAME.propertyName(), from.getSubjectName() == null ? "" : from.getSubjectName()); - record.setAttribute(FIELD_EXECUTION_STATUS.propertyName(), from.getExecutionStatus() == null ? "" : from.getExecutionStatus()); + record.setAttribute(FIELD_EVENT_DETAIL.propertyName(), + from.getEventDetail() == null ? "" : from.getEventDetail()); + record.setAttribute(FIELD_SUBJECT_NAME.propertyName(), + from.getSubjectName() == null ? "" : from.getSubjectName()); + record.setAttribute(FIELD_EXECUTION_STATUS.propertyName(), + from.getExecutionStatus() == null ? "" : from.getExecutionStatus()); return record; }
@Override protected PartitionEventCriteria getFetchCriteria(DSRequest request) { - //todo: do it like in ResourceDatasource.class - - - ExecutionStatus[] statuses = getArrayFilter(request, FILTER_EXECUTION_STATUS, ExecutionStatus.class); - PartitionEventType[] types = getArrayFilter(request, FILTER_EVENT_TYPE, PartitionEventType.class); - if (types == null || types.length == 0 || statuses == null || statuses.length == 0) { - return null; // user didn't select any type or status - return null to indicate no data should be displayed - } - PartitionEventCriteria criteria = new PartitionEventCriteria(); - // This code is unlikely to be necessary as the encompassing view should be using an initial - // sort specifier. But just in case, make sure we set the initial sort. Note that we have to - // manipulate the PageControl directly as per the restrictions on getFetchCriteria() (see jdoc). - PageControl pageControl = getPageControl(request); - if (pageControl.getOrderingFields().isEmpty()) { - pageControl.initDefaultOrderingField(FIELD_CTIME.propertyName(), PageOrdering.DESC); - } - - // TODO: This call is broken in 2.2, http://code.google.com/p/smartgwt/issues/detail?id=490 - // when using AdvancedCriteria - Map<String, Object> criteriaMap = request.getCriteria().getValues(); - criteria.addFilterEventDetail((String) criteriaMap.get(FILTER_EVENT_DETAIL)); - - // There's no need to add a exec. status filter to the criteria if the user specified all exec. statuses. - if (statuses.length != ExecutionStatus.values().length) { - criteria.addFilterExecutionStatus(statuses); - } - - // There's no need to add a event type filter to the criteria if the user specified all event types. - if (types.length != PartitionEventType.values().length) { - criteria.addFilterEventType(types); - } + // printRequestCriteria(request); + criteria.addFilterId(getFilter(request, FIELD_ID.propertyName(), Integer.class)); + criteria.addFilterEventDetail(getFilter(request, FIELD_EVENT_DETAIL.propertyName(), String.class)); + criteria.addFilterExecutionStatus(getArrayFilter(request, FILTER_EXECUTION_STATUS, ExecutionStatus.class)); + criteria.addFilterEventType(getArrayFilter(request, FILTER_EVENT_TYPE, PartitionEventType.class)); + + //@todo: Remove me when finished debugging search expression + Log.debug(" *** PartitionEventCriteria Search String: " + getFilter(request, "search", String.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class));
return criteria; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java index dc96374..4210202 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java @@ -29,7 +29,6 @@ import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.grid.ListGrid; @@ -44,6 +43,7 @@ import org.rhq.core.domain.criteria.PartitionEventCriteria; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.CloudGWTServiceAsync; @@ -90,32 +90,39 @@ public class PartitionEventDetailView extends LocatableVLayout implements Bookma PartitionEventCriteria criteria = new PartitionEventCriteria(); criteria.addFilterId(partitionEventId); final CloudGWTServiceAsync service = GWTServiceLookup.getCloudService(); - service.findPartitionEventsByCriteria(criteria, - new AsyncCallback<PageList<PartitionEvent>>() { - public void onSuccess(final PageList<PartitionEvent> events) { - if (events == null || events.size() != 1) { - //TODO: notify user in msg center - return; - } - prepareDetailsSection(sectionStack, events.get(0)); - service.getPartitionEventDetails(partitionEventId, - PageControl.getUnlimitedInstance(), new AsyncCallback<PageList<PartitionEventDetails>>() { - public void onSuccess(PageList<PartitionEventDetails> result) { - prepareAssignmentsSection(sectionStack, result); - } - public void onFailure(Throwable caught) { - SC.say("er2:" + caught); - //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); - } - }); - + service.findPartitionEventsByCriteria(criteria, new AsyncCallback<PageList<PartitionEvent>>() { + public void onSuccess(final PageList<PartitionEvent> events) { + if (events == null || events.size() != 1) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchPEventDetailsFail(String.valueOf(partitionEventId))); + initSectionCount = SECTION_COUNT; + return; } + prepareDetailsSection(sectionStack, events.get(0)); + service.getPartitionEventDetails(partitionEventId, PageControl.getUnlimitedInstance(), + new AsyncCallback<PageList<PartitionEventDetails>>() { + public void onSuccess(PageList<PartitionEventDetails> result) { + prepareAssignmentsSection(sectionStack, result); + } + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler() + .handleError( + MSG.view_adminTopology_message_fetchPEventDetailsFail(String + .valueOf(partitionEventId))); + initSectionCount = SECTION_COUNT; + return; + } + });
- public void onFailure(Throwable caught) { - SC.say("er1:" + caught); - //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); - } - }); + } + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchPEventDetailsFail(String.valueOf(partitionEventId))); + initSectionCount = SECTION_COUNT; + } + }); }
public boolean isInitialized() { @@ -165,7 +172,8 @@ public class PartitionEventDetailView extends LocatableVLayout implements Bookma // there is no need for datasource, it is a simple table with two columns ListGrid assignments = new ListGrid(); ListGridField agentName = new ListGridField("agentName", MSG.view_adminTopology_agent_agentName()); - ListGridField serverName = new ListGridField("serverName", MSG.view_admin_systemSettings_serverDetails_serverName()); + ListGridField serverName = new ListGridField("serverName", + MSG.view_admin_systemSettings_serverDetails_serverName()); assignments.setFields(agentName, serverName); ListGridRecord[] records = new ListGridRecord[eventDetails.size()]; for (int i = 0; i < eventDetails.size(); i++) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventTableView.java index b25a4d3..7fa9a7c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventTableView.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
+import java.util.ArrayList; import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback; @@ -63,18 +64,29 @@ public class PartitionEventTableView extends TableSection<PartitionEventDatasour public static final String VIEW_PATH = AdministrationView.VIEW_ID + "/" + AdministrationView.SECTION_TOPOLOGY_VIEW_ID + "/" + VIEW_ID;
- private static final Criteria INITIAL_CRITERIA = new Criteria();
- private static SortSpecifier DEFAULT_SORT_SPECIFIER = new SortSpecifier(PartitionEventCriteria.SORT_FIELD_CTIME, - SortDirection.DESCENDING); + private static final SortSpecifier DEFAULT_SORT_SPECIFIER = new SortSpecifier( + PartitionEventCriteria.SORT_FIELD_CTIME, SortDirection.DESCENDING); + + private enum TableAction { + REMOVE_SELECTED(MSG.view_adminTopology_server_removeSelected(), TableActionEnablement.ANY), PURGE_ALL(MSG + .view_adminTopology_partitionEvents_purgeAll(), TableActionEnablement.ALWAYS), FORCE_REPARTITION(MSG + .view_adminTopology_partitionEvents_forceRepartition(), TableActionEnablement.ALWAYS); + + private String title; + private TableActionEnablement enablement; + + private TableAction(String title, TableActionEnablement enablement) { + this.title = title; + this.enablement = enablement; + } + }
public PartitionEventTableView(String locatorId, String tableTitle) { super(locatorId, tableTitle, INITIAL_CRITERIA, new SortSpecifier[] { DEFAULT_SORT_SPECIFIER }); - setHeight100(); setWidth100(); - setInitialCriteriaFixed(false); setDataSource(new PartitionEventDatasource()); } @@ -89,22 +101,6 @@ public class PartitionEventTableView extends TableSection<PartitionEventDatasour
final TextItem detail = new TextItem(PartitionEventDatasource.FILTER_EVENT_DETAIL, MSG.view_adminTopology_partitionEvents_detailsFilter()); - // detail.setValue(""); - - // startDateFilter = new DateFilterItem(DateFilterItem.START_DATE_FILTER, MSG.filter_from_date()); - // endDateFilter = new DateFilterItem(DateFilterItem.END_DATE_FILTER, MSG.filter_to_date()); - -// SpacerItem spacerItem = new SpacerItem(); -// spacerItem.setColSpan(1); -// final ButtonItem showAll = new ButtonItem("showAll", "Show All"); -// showAll.addClickHandler(new ClickHandler() { -// public void onClick(ClickEvent event) { -// statusFilter.init(ExecutionStatus.class, null, null); -// typeFilter.init(PartitionEventType.class, null, null); -// detail.setValue(""); -// refresh(); -// } -// });
if (isShowFilterForm()) { setFilterFormItems(statusFilter, detail, typeFilter); @@ -118,7 +114,7 @@ public class PartitionEventTableView extends TableSection<PartitionEventDatasour ListGrid listGrid = getListGrid(); listGrid.setFields(fields.toArray(new ListGridField[fields.size()])); showActions(); - + for (ListGridField field : fields) { // adding the cell formatter for name field (clickable link) if (field.getName() == PartitionEventDatasourceField.FIELD_EVENT_TYPE.propertyName()) { @@ -137,140 +133,97 @@ public class PartitionEventTableView extends TableSection<PartitionEventDatasour } }
- // @Override - // protected String getDetailsLinkColumnName() { - // return PartitionEventDatasourceField.FIELD_EVENT_TYPE.propertyName(); - // } - // - // @Override - // protected CellFormatter getDetailsLinkColumnCellFormatter() { - // return new CellFormatter() { - // public String format(Object value, ListGridRecord record, int rowNum, int colNum) { - // Integer recordId = getId(record); - // String detailsUrl = "#" + VIEW_PATH + "/" + recordId; - // return SeleniumUtility.getLocatableHref(detailsUrl, detailsUrl, null); - // } - // }; - // } - @Override public Canvas getDetailsView(Integer id) { return new PartitionEventDetailView(extendLocatorId("detailsView"), id); }
private void showActions() { - addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), - MSG.common_msg_areYouSure(), new AuthorizedTableAction(this, TableActionEnablement.ANY, - Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - String message = "Really? Delete? For all I've done for you? "; - SC.ask(message, new BooleanCallback() { - public void execute(Boolean confirmed) { - if (confirmed) { - int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); - GWTServiceLookup.getCloudService().deletePartitionEvents(selectedIds, - new AsyncCallback<Void>() { - public void onSuccess(Void arg0) { - // TODO: msg - Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); - CoreGUI.getMessageCenter().notify(msg); - refresh(); - } - - public void onFailure(Throwable caught) { - // TODO: msg - CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); - refreshTableInfo(); - } + addTableAction(TableAction.REMOVE_SELECTED); + addTableAction(TableAction.PURGE_ALL); + addTableAction(TableAction.FORCE_REPARTITION); + }
- }); - } else { - refreshTableInfo(); - } - } - }); + private void addTableAction(final TableAction action) { + addTableAction(extendLocatorId(action.toString()), action.title, null, new AuthorizedTableAction(this, + action.enablement, Permission.MANAGE_SETTINGS) { + public void executeAction(final ListGridRecord[] selections, Object actionValue) { + String eventTypes = getSelectedEventTypes(selections).toString(); + String message = null; + switch (action) { + case REMOVE_SELECTED: + message = MSG.view_adminTopology_message_removePEventConfirm(eventTypes); + break; + case PURGE_ALL: + message = MSG.view_adminTopology_message_removeAllPEventConfirm(); + break; + case FORCE_REPARTITION: + message = MSG.view_adminTopology_message_forceRepartition(); + break; + default: + throw new IllegalArgumentException("unknown table action type"); } - }); - - addTableAction(extendLocatorId("purgeAll"), MSG.view_adminTopology_partitionEvents_purgeAll(), - MSG.common_msg_areYouSure(), new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, - Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - // TODO: msg - // String message = MSG.view_admin_plugins_serverDisableConfirm(selectedNames.toString()); - String message = "Really? Normal? For all I've done for you? "; - SC.ask(message, new BooleanCallback() { - public void execute(Boolean confirmed) { - if (confirmed) { - int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); - GWTServiceLookup.getCloudService().purgeAllEvents(new AsyncCallback<Void>() { - public void onSuccess(Void arg0) { - // TODO: msg - Message msg = new Message(MSG.view_admin_plugins_disabledServerPlugins("sdf"), - Message.Severity.Info); - CoreGUI.getMessageCenter().notify(msg); - refresh(); + SC.ask(message, new BooleanCallback() { + public void execute(Boolean confirmed) { + if (confirmed) { + int[] selectedIds = getSelectedIds(selections); + + AsyncCallback<Void> callback = new AsyncCallback<Void>() { + public void onSuccess(Void arg0) { + String msgString = null; + switch (action) { + case REMOVE_SELECTED: + msgString = MSG.view_adminTopology_message_removedPEvent(String + .valueOf(selections.length)); + break; + case PURGE_ALL: + msgString = MSG.view_adminTopology_message_removedAllPEvent(); + break; + case FORCE_REPARTITION: + msgString = MSG.view_adminTopology_message_repartitioned(); } - - public void onFailure(Throwable caught) { - // TODO: msg - CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); - refreshTableInfo(); + Message msg = new Message(msgString, Message.Severity.Info); + CoreGUI.getMessageCenter().notify(msg); + refresh(); + } + + public void onFailure(Throwable caught) { + String msgString = null; + switch (action) { + case REMOVE_SELECTED: + msgString = MSG.view_adminTopology_message_removePEventFail(String + .valueOf(selections.length)); + break; + case PURGE_ALL: + msgString = MSG.view_adminTopology_message_removedAllPEventFail(); + break; + case FORCE_REPARTITION: + msgString = MSG.view_adminTopology_message_forceRepartitionFail(); } - - }); - } else { - refreshTableInfo(); + CoreGUI.getErrorHandler() + .handleError(msgString + " " + caught.getMessage(), caught); + refreshTableInfo(); + } + + }; + switch (action) { + case REMOVE_SELECTED: + GWTServiceLookup.getCloudService().deletePartitionEvents(selectedIds, callback); + break; + case PURGE_ALL: + GWTServiceLookup.getCloudService().purgeAllEvents(callback); + break; + case FORCE_REPARTITION: + GWTServiceLookup.getCloudService().cloudPartitionEventRequest(callback); } - } - }); - } - }); - - addTableAction(extendLocatorId("forceRepartition"), MSG.view_adminTopology_partitionEvents_forceRepartition(), - new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - // List<String> selectedNames = getSelectedNames(selections); - // TODO: msg - // String message = MSG.view_admin_plugins_serverDisableConfirm(selectedNames.toString()); - String message = "Really? Repartition? For all I've done for you? ";// + selectedNames; - SC.ask(message, new BooleanCallback() { - public void execute(Boolean confirmed) { - if (confirmed) { - SC.say("repartition is now forced"); - GWTServiceLookup.getCloudService().cloudPartitionEventRequest( - new AsyncCallback<Void>() { - public void onSuccess(Void arg0) { - // TODO: msg - Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); - CoreGUI.getMessageCenter().notify(msg); - refresh(); - }
- public void onFailure(Throwable caught) { - // TODO: msg - CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); - refreshTableInfo(); - } - - }); - } else { - refreshTableInfo(); - } + } else { + refreshTableInfo(); } - }); - } - }); + } + }); + } + }); }
private int[] getSelectedIds(ListGridRecord[] selections) { @@ -285,16 +238,16 @@ public class PartitionEventTableView extends TableSection<PartitionEventDatasour return ids; }
- // private List<String> getSelectedNames(ListGridRecord[] selections) { - // if (selections == null) { - // return new ArrayList<String>(0); - // } - // List<String> ids = new ArrayList<String>(selections.length); - // for (ListGridRecord selection : selections) { - // ids.add(selection.getAttributeAsString(FIELD_NAME)); - // } - // return ids; - // } + private List<String> getSelectedEventTypes(ListGridRecord[] selections) { + if (selections == null) { + return new ArrayList<String>(0); + } + List<String> ids = new ArrayList<String>(selections.length); + for (ListGridRecord selection : selections) { + ids.add(selection.getAttributeAsString(PartitionEventDatasourceField.FIELD_EVENT_TYPE.propertyName())); + } + return ids; + }
@Override public ViewName getViewName() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java index 2d1a75e..0e7fd48 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.admin.topology; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_ADDRESS; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_AFFINITY_GROUP; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_AFFINITY_GROUP_ID; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_AGENT_COUNT; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_ID; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_MTIME; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_NAME; @@ -47,6 +46,7 @@ import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.Log; @@ -56,7 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.util.Log; * */ public class ServerDatasource extends AbstractServerNodeDatasource<Server, ServerCriteria> { - + // filters public static final String FILTER_ADDRESS = FIELD_ADDRESS.propertyName(); public static final String FILTER_PORT = FIELD_PORT.propertyName(); @@ -66,13 +66,10 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve public static final String FILTER_AFFINITY_GROUP_ID = "affinityGroupId";
private final Integer affinityGroupId; - - private final boolean fetchMembers;
- public ServerDatasource(Integer affinityGroupId, boolean fetchMembers) { + public ServerDatasource(Integer affinityGroupId) { super(); this.affinityGroupId = affinityGroupId; - this.fetchMembers = fetchMembers; List<DataSourceField> fields = addDataSourceFields(); addFields(fields); } @@ -107,36 +104,28 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve ListGridField affinityGroupIdField = FIELD_AFFINITY_GROUP_ID.getListGridField(); affinityGroupIdField.setHidden(true); fields.add(affinityGroupIdField); - fields.add(FIELD_AGENT_COUNT.getListGridField("75"));
return fields; }
@Override protected void executeFetch(final DSRequest request, final DSResponse response, ServerCriteria criteria) { - if (affinityGroupId == null) { - return; + if (affinityGroupId != null) { + criteria.addFilterAffinityGroupId(affinityGroupId); } - final PageControl pc = getPageControl(request); - AsyncCallback<PageList<Server>> callback = new AsyncCallback<PageList<Server>>() { + GWTServiceLookup.getCloudService().findServersByCriteria(criteria, new AsyncCallback<PageList<Server>>() { public void onSuccess(PageList<Server> result) { response.setData(buildRecords(result)); response.setTotalRows(result.size()); processResponse(request.getRequestId(), response); }
- @Override public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchServers2Fail(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } - }; - - if(fetchMembers) { - criteria.addFilterAffinityGroupId(affinityGroupId); - } - GWTServiceLookup.getCloudService().findServersByCriteria(criteria, callback); + }); }
/** @@ -146,6 +135,7 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve * @param request the request to turn into a page control * @return the page control for passing to criteria and other queries */ + @Override protected PageControl getPageControl(DSRequest request) { // Initialize paging. PageControl pageControl = new PageControl(0, getDataPageSize()); @@ -167,10 +157,6 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve @Override public Server copyValues(Record from) { throw new UnsupportedOperationException("ServerDatasource.copyValues(Record from)"); -// Server server = new Server(); -// server.setId(from.getAttributeAsInt(FIELD_ID.propertyName())); -// server.setName(from.getAttributeAsString(FIELD_NAME.propertyName())); -// return server; }
@Override @@ -193,7 +179,7 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve @Override protected ServerCriteria getFetchCriteria(DSRequest request) { ServerCriteria criteria = new ServerCriteria(); -// printRequestCriteria(request); + // printRequestCriteria(request); criteria.addFilterId(getFilter(request, FIELD_ID.propertyName(), Integer.class)); criteria.addFilterName(getFilter(request, FIELD_NAME.propertyName(), String.class)); criteria.addFilterAddress(getFilter(request, FILTER_ADDRESS, String.class)); @@ -202,7 +188,7 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve criteria.addFilterOperationMode(getFilter(request, FILTER_OPERATION_MODE, OperationMode.class)); criteria.addFilterComputePower(getFilter(request, FILTER_COMPUTE_POWER, Integer.class)); criteria.addFilterAffinityGroupId(getFilter(request, FILTER_AFFINITY_GROUP_ID, Integer.class)); - + //@todo: Remove me when finished debugging search expression Log.debug(" *** ServerCriteria Search String: " + getFilter(request, "search", String.class)); criteria.setSearchExpression(getFilter(request, "search", String.class)); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasourceField.java index 09577d8..6dbcee3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasourceField.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasourceField.java @@ -29,9 +29,8 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; public enum ServerDatasourceField {
FIELD_ID("id", CoreGUI.getMessages().common_title_id()), - - // todo: i18n - FIELD_ORDINAL("ordinal", "Order"), + + FIELD_ORDINAL("ordinal", CoreGUI.getMessages().view_adminTopology_message_order()),
FIELD_NAME("name", CoreGUI.getMessages().common_title_name()),
@@ -42,13 +41,13 @@ public enum ServerDatasourceField { FIELD_PORT("port", CoreGUI.getMessages().view_adminTopology_server_nonSecurePort()),
FIELD_SECURE_PORT("securePort", CoreGUI.getMessages().view_adminTopology_server_securePort()), - + FIELD_CTIME("ctime", CoreGUI.getMessages().view_adminTopology_serverDetail_installationDate()),
FIELD_MTIME("mtime", CoreGUI.getMessages().view_adminTopology_server_lastUpdateTime()),
FIELD_AFFINITY_GROUP("affinityGroup", CoreGUI.getMessages().view_adminTopology_server_affinityGroup()), - + FIELD_AFFINITY_GROUP_ID("affinityGroupId", "affinityGroupId"),
FIELD_AGENT_COUNT("agentCount", CoreGUI.getMessages().view_adminTopology_server_agentCount()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java index b50e18c..d38d95d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java @@ -79,7 +79,7 @@ public class ServerTableView extends setHeight100(); setWidth100(); if (isAffinityGroupId) { - setDataSource(new ServerDatasource(id, true)); + setDataSource(new ServerDatasource(id)); } else { setDataSource(showActions ? new ServerWithAgentCountDatasource() : new FailoverListItemDatasource(id)); } @@ -96,6 +96,7 @@ public class ServerTableView extends listGrid.sort(FIELD_NAME, SortDirection.ASCENDING); showCommonActions(); } else if (isAffinityGroupId) { + listGrid.sort(FIELD_NAME, SortDirection.ASCENDING); // displayed from AffinityGroupDetailView showUpdateMembersAction(); } else { @@ -141,7 +142,7 @@ public class ServerTableView extends }
private void showCommonActions() { - addChangeOperationModeAction(OperationMode.NORMAL, MSG.view_adminTopology_server_setMaintenance()); + addChangeOperationModeAction(OperationMode.NORMAL, MSG.view_adminTopology_server_setNormal()); addChangeOperationModeAction(OperationMode.MAINTENANCE, MSG.view_adminTopology_server_setMaintenance());
addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), null, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerWithAgentCountDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerWithAgentCountDatasource.java index af52e7a..1b6609b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerWithAgentCountDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerWithAgentCountDatasource.java @@ -27,25 +27,28 @@ import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; +import com.smartgwt.client.widgets.grid.HoverCustomizer; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; import org.rhq.core.domain.criteria.Criteria; import org.rhq.core.domain.util.PageControl; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
/** * @author Jirka Kremser * */ -public class ServerWithAgentCountDatasource extends AbstractServerNodeDatasource<ServerWithAgentCountComposite, Criteria> { - +public class ServerWithAgentCountDatasource extends + AbstractServerNodeDatasource<ServerWithAgentCountComposite, Criteria> { + private final ServerDatasource serverDatasource;
public ServerWithAgentCountDatasource() { super(); - serverDatasource = new ServerDatasource(null, false); + serverDatasource = new ServerDatasource(null); List<DataSourceField> fields = addDataSourceFields(); addFields(fields); } @@ -56,7 +59,18 @@ public class ServerWithAgentCountDatasource extends AbstractServerNodeDatasource }
public List<ListGridField> getListGridFields() { - return serverDatasource.getListGridFields(); + List<ListGridField> fields = serverDatasource.getListGridFields(); + ListGridField agentCountField = FIELD_AGENT_COUNT.getListGridField("75"); + agentCountField.setHoverCustomizer(new HoverCustomizer() { + public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) { + return MSG.view_adminTopology_message_agentsCount(FIELD_AGENT_COUNT.propertyName()); + // "There are " + record.getAttributeAsInt(FIELD_AGENT_COUNT.propertyName()) + // + " agents registered to this server."; + } + }); + agentCountField.setShowHover(true); + fields.add(agentCountField); + return fields; }
@Override @@ -72,20 +86,14 @@ public class ServerWithAgentCountDatasource extends AbstractServerNodeDatasource
@Override public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + CoreGUI.getErrorHandler().handleError(MSG.view_adminTopology_message_fetchServers2Fail(), t); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } }); }
- /** - * Returns a prepopulated PageControl based on the provided DSRequest. This will set sort fields, - * pagination, but *not* filter fields. - * - * @param request the request to turn into a page control - * @return the page control for passing to criteria and other queries - */ + @Override protected PageControl getPageControl(DSRequest request) { return serverDatasource.getPageControl(request); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java index df83ba8..4b92d6f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java @@ -41,72 +41,197 @@ import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList;
/** + * API for HAAC console, mostly CRUD operations for entities <code>Server</code>, <code>Agent</code>, + * <code>PartitionEvent</code> and <code>AffinityGroup</code>. + * * @author Jiri Kremser */ public interface CloudGWTService extends RemoteService {
/** + * Returns all the servers with agent count. * - * @return a list of all available servers (the servers in MAINTENANCE mode are included as well) + * @param pageControl the page control instance + * @return a list of all available servers (the servers in <code>MAINTENANCE</code> or <code>DOWN</code> mode are included as well) * @throws RuntimeException */ - List<ServerWithAgentCountComposite> getServers(PageControl pc) throws RuntimeException; - - Server getServerById(int serverId) throws RuntimeException; - - List<Agent> getAgentsByServerName(String serverName) throws RuntimeException; + List<ServerWithAgentCountComposite> getServers(PageControl pageControl) throws RuntimeException;
+ /** + * Deletes the servers with provided ids. + * + * @param serverIds array of server ids + * @throws RuntimeException + */ void deleteServers(int[] serverIds) throws RuntimeException;
+ /** + * Updates the server mode to particular servers. + * + * @param serverIds the array of ids of the servers whose modes are object of update + * @param mode the new operation mode + * @throws RuntimeException + */ void updateServerMode(int[] serverIds, Server.OperationMode mode) throws RuntimeException;
+ /** + * Updates the server. + * + * @param server instance of Server + * @throws RuntimeException + */ void updateServer(Server server) throws RuntimeException;
- List<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc) throws RuntimeException;; + /** + * Returns the list of <code>FailoverListDetails</code> for a particular agent. + * + * @param agentId the id the agent + * @param pageControl the page control instance + * @return a list of <code>FailoverListDetails</code> instances + * @throws RuntimeException + */ + List<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pageControl) throws RuntimeException;;
+ /** + * Finder for <code>PartitionEvent</code> instances + * + * @param criteria the criteria for finding partition events + * @return a list of <code>codePartitionEvent</code> instances + * @throws RuntimeException + */ PageList<PartitionEvent> findPartitionEventsByCriteria(PartitionEventCriteria criteria) throws RuntimeException;
+ /** + * Finder for <code>Server</code> instances + * + * @param criteria the criteria for finding servers + * @return a list of <code>Server</code> instances + * @throws RuntimeException + */ PageList<Server> findServersByCriteria(ServerCriteria criteria) throws RuntimeException;
+ /** + * Finder for <code>Agent</code> instances + * + * @param criteria the criteria for finding agents + * @return a list of <code>Agent</code> instances + * @throws RuntimeException + */ PageList<Agent> findAgentsByCriteria(AgentCriteria criteria) throws RuntimeException;
+ /** + * Request forcing the repartition of the cluster. All agents should eventually reconnects to its most preferred server + * (The first one in their failover list.) + * + * @throws RuntimeException + */ void cloudPartitionEventRequest() throws RuntimeException;
+ /** + * Deletes all the partition events. + * + * @throws RuntimeException + */ void purgeAllEvents() throws RuntimeException;
+ /** + * Deletes some partition events. + * + * @param eventIds the list of ids of partition events to delete + * @throws RuntimeException + */ void deletePartitionEvents(int[] eventIds) throws RuntimeException;
+ /** + * Returns the list of <code>PartitionEventDetails</code> instances. + * + * @param partitionEventId + * @param pageControl the page control instance + * @return list of <code>PartitionEventDetails</code> instances + * @throws RuntimeException + */ PageList<PartitionEventDetails> getPartitionEventDetails(int partitionEventId, PageControl pageControl) throws RuntimeException;
+ /** + * Returns the list with <code>AffinityGroupCountComposite</code> instances, i.e. affinity groups with agent and server + * counts. + * + * @param pageControl the page control instance + * @return list with <code>AffinityGroupCountComposite</code> instances + * @throws RuntimeException + */ PageList<AffinityGroupCountComposite> getAffinityGroupCountComposites(PageControl pageControl) throws RuntimeException;
+ /** + * Deletes some affinity groups. + * + * @param affinityGroupIds array of ids of affinity group to delete + * @return the number of deleted affinity groups + * @throws RuntimeException + */ int deleteAffinityGroups(int[] affinityGroupIds) throws RuntimeException;
+ /** + * Creates new affinity group. + * + * @param affinityGroup instance of <code>AffinityGroup</code> to create + * @return the new id of the affinity group + * @throws RuntimeException + */ int createAffinityGroup(AffinityGroup affinityGroup) throws RuntimeException;
+ /** + * Updates existing affinity group. + * + * @param affinityGroup instance of <code>AffinityGroup</code> + * @throws RuntimeException + */ void updateAffinityGroup(AffinityGroup affinityGroup) throws RuntimeException;
- PageList<Server> getServerMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException; - - PageList<Server> getServerNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException; - - PageList<Agent> getAgentMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException; - - PageList<Agent> getAgentNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException; - + /** + * Returns the affinity group based on the provided id. + * + * @param affinityGroupId the id of an affinity group + * @return the instance of <code>AffinityGroup</code> + * @throws RuntimeException + */ AffinityGroup getAffinityGroupById(int affinityGroupId) throws RuntimeException;
+ /** + * Add servers to an existing affinity group. + * + * @param affinityGroupId id of the affinity group into which the servers should be added + * @param serverIds array of ids of servers to be added + * @throws RuntimeException + */ void addServersToGroup(int affinityGroupId, Integer[] serverIds) throws RuntimeException;
+ /** + * Removes the servers from the affinity group. There is no need to provide the id of affinity group, + * because it is part of the server data. + * + * @param serverIds array of ids of servers to be removed + * @throws RuntimeException + */ void removeServersFromGroup(Integer[] serverIds) throws RuntimeException;
+ /** + * Add agents to an existing affinity group. + * + * @param affinityGroupId id of the affinity group into which the agents should be added + * @param agentIds array of ids of agents to be added + * @throws RuntimeException + */ void addAgentsToGroup(int affinityGroupId, Integer[] agentIds) throws RuntimeException;
+ /** + * Removes the agents from the affinity group. There is no need to provide the id of affinity group, + * because it is part of the agent data. + * + * @param agentIds array of ids of agents to be removed + * @throws RuntimeException + */ void removeAgentsFromGroup(Integer[] agentIds) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java index db7ec3c..dd63fa0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java @@ -22,7 +22,6 @@ */ package org.rhq.enterprise.gui.coregui.server.gwt;
-import java.util.ArrayList; import java.util.List;
import org.apache.commons.lang.ArrayUtils; @@ -58,7 +57,7 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud private static final long serialVersionUID = 1L;
private CloudManagerLocal cloudManager = LookupUtil.getCloudManager(); - + private AgentManagerLocal agentManager = LookupUtil.getAgentManager();
private PartitionEventManagerLocal partitionEventManager = LookupUtil.getPartitionEventManager(); @@ -76,26 +75,6 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud }
@Override - public Server getServerById(int serverId) throws RuntimeException { - try { - return SerialUtility.prepare(cloudManager.getServerById(serverId), "CloudGWTServiceImpl.getServerById"); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public List<Agent> getAgentsByServerName(String serverName) throws RuntimeException { - try { - List<Agent> persistentBag = SerialUtility.prepare(cloudManager.getAgentsByServerName(serverName), - "CloudGWTServiceImpl.getAgentsByServerName"); - return new ArrayList<Agent>(persistentBag); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override public void deleteServers(int[] serverIds) throws RuntimeException { try { cloudManager.deleteServers(ArrayUtils.toObject(serverIds)); @@ -135,24 +114,21 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud throw getExceptionToThrowToClient(t); } } - + @Override - public PageList<Server> findServersByCriteria(ServerCriteria criteria) - throws RuntimeException { + public PageList<Server> findServersByCriteria(ServerCriteria criteria) throws RuntimeException { try { - return SerialUtility.prepare( - cloudManager.findServersByCriteria(getSessionSubject(), criteria), + return SerialUtility.prepare(cloudManager.findServersByCriteria(getSessionSubject(), criteria), "CloudGWTServiceImpl.findServersByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); } } - + @Override public PageList<Agent> findAgentsByCriteria(AgentCriteria criteria) throws RuntimeException { try { - return SerialUtility.prepare( - agentManager.findAgentsByCriteria(getSessionSubject(), criteria), + return SerialUtility.prepare(agentManager.findAgentsByCriteria(getSessionSubject(), criteria), "CloudGWTServiceImpl.findAgentsByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); @@ -229,54 +205,6 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud }
@Override - public PageList<Server> getServerMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException { - try { - return SerialUtility.prepare( - affinityGroupManager.getServerMembers(getSessionSubject(), affinityGroupId, pageControl), - "CloudGWTServiceImpl.getServerMembersByAffinityGroupId"); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public PageList<Server> getServerNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException { - try { - return SerialUtility.prepare( - affinityGroupManager.getServerNonMembers(getSessionSubject(), affinityGroupId, pageControl), - "CloudGWTServiceImpl.getServerNonMembersByAffinityGroupId"); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public PageList<Agent> getAgentMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException { - try { - return SerialUtility.prepare( - affinityGroupManager.getAgentMembers(getSessionSubject(), affinityGroupId, pageControl), - "CloudGWTServiceImpl.getAgentMembersByAffinityGroupId"); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public PageList<Agent> getAgentNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) - throws RuntimeException { - try { - return SerialUtility.prepare( - affinityGroupManager.getAgentNonMembers(getSessionSubject(), affinityGroupId, pageControl), - "CloudGWTServiceImpl.getAgentNonMembersByAffinityGroupId"); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override public AffinityGroup getAffinityGroupById(int affinityGroupId) throws RuntimeException { try { return SerialUtility.prepare(affinityGroupManager.getById(getSessionSubject(), affinityGroupId), @@ -322,7 +250,6 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud } }
- @Override public void updateServer(Server server) throws RuntimeException { try { @@ -332,7 +259,6 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud } }
- @Override public void updateAffinityGroup(AffinityGroup affinityGroup) throws RuntimeException { try { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index ceaad0d..56ed2ac 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -552,16 +552,45 @@ view_adminTopology_agentDetail_address = Address view_adminTopology_agentDetail_agentFailoverList = Agent Failover List view_adminTopology_agentDetail_currentServer = Current Server view_adminTopology_agentDetail_token = Token -view_adminTopology_message_fetchServerFail=Unable to fetch server details for server with id {0}. -view_adminTopology_message_fetchAgentFail=Unable to fetch agent details for agent with id {0}. -view_adminTopology_message_removeServerConfirm=Do you really want to remove servers [{0}]? -view_adminTopology_message_removeServerFail=Unable to remove {0} server(s). -view_adminTopology_message_removedServer=Removed {0} server(s). -view_adminTopology_message_serverUpdated=The server {0} was successfully updated. -view_adminTopology_message_serverUpdateFail=Unable to update server {0}. -view_adminTopology_message_setMode=Set {0} server(s) to {1} mode. -view_adminTopology_message_setModeConfirm=Do you really want to set servers [{0}] to {1} mode? -view_adminTopology_message_setModeFail=Unable to set {0} server(s) to {1} mode. +view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number does not correspond to the number of currently connected agents. +view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +view_adminTopology_message_order = Order +view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +view_adminTopology_message_removedAllPEvent = All partition events have been purged. +view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +view_adminTopology_message_removedServer = Removed {0} server(s). +view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = Partition Events view_adminTopology_partitionEvents_details = Details view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties index 35b7b46..0775491 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_cs.properties @@ -571,6 +571,45 @@ view_adminTopology_agentDetail_address = Adresa view_adminTopology_agentDetail_agentFailoverList = Agentův failover list view_adminTopology_agentDetail_currentServer = Současný server view_adminTopology_agentDetail_token = Token +view_adminTopology_message_agentsCount = K serveru je zaregistrováno {0} agentů. Toto číslo neznamená počet aktuálně připojených agentů. +view_adminTopology_message_agroupAssingAgentsFail = Nepodařilo se přiřadit agenty do afinitní skupiny s id {0}. +view_adminTopology_message_agroupAssingServersFail = Nepodařilo se přiřadit servery do afinitní skupiny s id {0}. +view_adminTopology_message_agroupRemovingAgentsFail = Nepodařilo se odstranit agenty z afinitní skupiny s id {0}. +view_adminTopology_message_agroupRemovingServersFail = Nepodařilo se odstranit servery z afinitní skupiny s id {0}. +view_adminTopology_message_agroupRenamed = Afinitní skupina s id {0} a jménem {1} byla přejmenována na {2}. +view_adminTopology_message_agroupRenamingFail = Nepodařilo se přejmenovat afinitní skupinu s id {0} a jménem {1}. +view_adminTopology_message_fetchAgentFail = Nepodařilo se získat detaily o agentovi s id {0}. +view_adminTopology_message_fetchAgentsFail = Nepodařilo se agenty pro afinitní skupinu s id {0}. +view_adminTopology_message_fetchAgents2Fail = Nepodařilo se získat agenty. +view_adminTopology_message_fetchAgroupFail = Nepodařilo se získat detaily o afinitní skupině s id {0}. +view_adminTopology_message_fetchAgroupsFail = Nepodařilo se získat afinitní skupiny. +view_adminTopology_message_fetchFailOverLists = Nepodařilo se získat dataily failover listu. +view_adminTopology_message_fetchPEventDetailsFail = Nepodařilo se získat detaily události clusteru s id {0}. +view_adminTopology_message_fetchPEventFail = Nepodařilo se získat události clusteru. +view_adminTopology_message_fetchServerFail = Nepodařilo se získat detaily o serveru s id {0}. +view_adminTopology_message_fetchServersFail = Nepodařilo se získat servery pro afinitní skupinu s id {0}. +view_adminTopology_message_fetchServers2Fail = Nepodařilo se získat servery. +view_adminTopology_message_forceRepartition = Přejete si opravdu vynutit přerozdělení celého clusteru? Přiměje to každého z agentů připojit se na svůj preferovaný server tzn. první ve failover listu. +view_adminTopology_message_forceRepartitionFail = Nepodařilo se spustit přerozdělení. +view_adminTopology_message_order = Pořadí +view_adminTopology_message_removeAGroupsFail = Nepodařilo se odstranit následující afinitní skupiny {0}. +view_adminTopology_message_removeAGroupsConfirm = Přejete si opravdu odstanit následující afinitní skupiny {0}? +view_adminTopology_message_removeAllPEventConfirm = Přejete si opravdu odstranit všechny události clusteru? +view_adminTopology_message_removePEventConfirm = Chcete opravdu odstranit následující události clusteru {0}? +view_adminTopology_message_removePEventFail = Nepodařilo se odstranit {0} události clusteru. +view_adminTopology_message_removeServerConfirm = Chcete opravdu odstranit následující servery {0}? +view_adminTopology_message_removeServerFail = Nepodařilo se odstranit {0} serverů. +view_adminTopology_message_removedAGroups = Odstraněno {0} afinitních skupin. +view_adminTopology_message_removedAllPEvent = Všechnz události clusteru byly smazány. +view_adminTopology_message_removedAllPEventFail = Nepodařilo se odstranit všechny události clusteru. +view_adminTopology_message_removedPEvent = Odstraněno {0} událostí clusteru. +view_adminTopology_message_removedServer =Odstraněno {0} serverů. +view_adminTopology_message_repartitioned = Operace přerozdělení clusteru byla úspěšně spuštěna. +view_adminTopology_message_serverUpdated = Server {0} byl úspěšně změněn. +view_adminTopology_message_serverUpdateFail = Nepodařilo se změnit server {0}. +view_adminTopology_message_setMode =Nastaveno {0} serverů do {1} módu. +view_adminTopology_message_setModeConfirm = Přejete si opravdu nastavit servery {0} do {1} módu? +view_adminTopology_message_setModeFail = Nepodařilo se nastavit {0} serverů do {1} módu. view_adminTopology_partitionEvents = Události o clusteru view_adminTopology_partitionEvents_details = Detaily view_adminTopology_partitionEvents_detailsFilter = Filtrovat podle detailu diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties index 6c2cc91..f9876c3 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties @@ -519,6 +519,45 @@ view_adminTopology_agents = Agenten ##view_adminTopology_agentDetail_agentFailoverList = Agent Failover List ##view_adminTopology_agentDetail_currentServer = Current Server ##view_adminTopology_agentDetail_token = Token +##view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number doesn't correspond to the number of currently connected agents. +##view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +##view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +##view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +##view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +##view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +##view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +##view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +##view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +##view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +##view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +##view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +##view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +##view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +##view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +##view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +##view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +##view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +##view_adminTopology_message_order = Order +##view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +##view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +##view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +##view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +##view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +##view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +##view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +##view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +##view_adminTopology_message_removedAllPEvent = All partition events have been purged. +##view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +##view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +##view_adminTopology_message_removedServer = Removed {0} server(s). +##view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +##view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +##view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +##view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +##view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +##view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = Partitionierungs-Ereignisse ##view_adminTopology_partitionEvents_details = Details ##view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties index 2b74e1b..83b705b 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties @@ -550,6 +550,45 @@ view_adminTopology_agents = エージェント ##view_adminTopology_agentDetail_agentFailoverList = Agent Failover List ##view_adminTopology_agentDetail_currentServer = Current Server ##view_adminTopology_agentDetail_token = Token +##view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number doesn't correspond to the number of currently connected agents. +##view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +##view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +##view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +##view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +##view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +##view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +##view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +##view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +##view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +##view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +##view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +##view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +##view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +##view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +##view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +##view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +##view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +##view_adminTopology_message_order = Order +##view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +##view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +##view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +##view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +##view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +##view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +##view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +##view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +##view_adminTopology_message_removedAllPEvent = All partition events have been purged. +##view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +##view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +##view_adminTopology_message_removedServer = Removed {0} server(s). +##view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +##view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +##view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +##view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +##view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +##view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = イベントの分類 ##view_adminTopology_partitionEvents_details = Details ##view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties index ceb89bd..9f545fb 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties @@ -555,6 +555,45 @@ view_adminTopology_agents = Agentes ##view_adminTopology_agentDetail_agentFailoverList = Agent Failover List ##view_adminTopology_agentDetail_currentServer = Current Server ##view_adminTopology_agentDetail_token = Token +##view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number doesn't correspond to the number of currently connected agents. +##view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +##view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +##view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +##view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +##view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +##view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +##view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +##view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +##view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +##view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +##view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +##view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +##view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +##view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +##view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +##view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +##view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +##view_adminTopology_message_order = Order +##view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +##view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +##view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +##view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +##view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +##view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +##view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +##view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +##view_adminTopology_message_removedAllPEvent = All partition events have been purged. +##view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +##view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +##view_adminTopology_message_removedServer = Removed {0} server(s). +##view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +##view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +##view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +##view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +##view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +##view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = Eventos na Parti\u00E7\u00E3o ##view_adminTopology_partitionEvents_details = Details ##view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties index 86c16cb..47025b7 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ru.properties @@ -542,6 +542,45 @@ #view_adminTopology_agentDetail_agentFailoverList = Agent Failover List #view_adminTopology_agentDetail_currentServer = Current Server #view_adminTopology_agentDetail_token = Token +##view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number doesn't correspond to the number of currently connected agents. +##view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +##view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +##view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +##view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +##view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +##view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +##view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +##view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +##view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +##view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +##view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +##view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +##view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +##view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +##view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +##view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +##view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +##view_adminTopology_message_order = Order +##view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +##view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +##view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +##view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +##view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +##view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +##view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +##view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +##view_adminTopology_message_removedAllPEvent = All partition events have been purged. +##view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +##view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +##view_adminTopology_message_removedServer = Removed {0} server(s). +##view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +##view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +##view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +##view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +##view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +##view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. #view_adminTopology_partitionEvents = Partition Events ##view_adminTopology_partitionEvents_details = Details ##view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties index 2c649de..b9941fc 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties @@ -542,6 +542,45 @@ view_adminTopology_agents = \u4ee3\u7406 ##view_adminTopology_agentDetail_agentFailoverList = Agent Failover List ##view_adminTopology_agentDetail_currentServer = Current Server ##view_adminTopology_agentDetail_token = Token +##view_adminTopology_message_agentsCount = There are {0} agents registered to this server. This number doesn't correspond to the number of currently connected agents. +##view_adminTopology_message_agroupAssingAgentsFail = Unable to assign agents to the affinity group with id {0}. +##view_adminTopology_message_agroupAssingServersFail = Unable to assign servers to the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingAgentsFail = Unable to remove agents from the affinity group with id {0}. +##view_adminTopology_message_agroupRemovingServersFail = Unable to remove servers from the affinity group with id {0}. +##view_adminTopology_message_agroupRenamed = Affinity group with id {0} and name {1} was renamed to {2}. +##view_adminTopology_message_agroupRenamingFail = Unable to rename affinity group with id {0} and name {1}. +##view_adminTopology_message_fetchAgentFail = Unable to fetch agent details for agent with id {0}. +##view_adminTopology_message_fetchAgentsFail = Unable to fetch agent(s) for affinity group with id {0}. +##view_adminTopology_message_fetchAgents2Fail = Unable to fetch agents. +##view_adminTopology_message_fetchAgroupFail = Unable to fetch affinity group details for group with id {0}. +##view_adminTopology_message_fetchAgroupsFail = Unable to fetch affinity group(s). +##view_adminTopology_message_fetchFailOverLists = Unable to fetch fail over list details. +##view_adminTopology_message_fetchPEventDetailsFail = Unable to fetch partition event details for event with id {0}. +##view_adminTopology_message_fetchPEventFail = Unable to fetch partition events. +##view_adminTopology_message_fetchServerFail = Unable to fetch server details for server with id {0}. +##view_adminTopology_message_fetchServersFail = Unable to fetch server(s) for affinity group with id {0}. +##view_adminTopology_message_fetchServers2Fail = Unable to fetch servers. +##view_adminTopology_message_forceRepartition = Do you really want to force a repartition of whole cluster? It will force all the agents to connect to its most preferred server. +##view_adminTopology_message_forceRepartitionFail = Unable to run repartition. +##view_adminTopology_message_order = Order +##view_adminTopology_message_removeAGroupsFail = Unable to remove following affinity groups(s) {0}. +##view_adminTopology_message_removeAGroupsConfirm = Do you really want to remove following affinity groups {0}? +##view_adminTopology_message_removeAllPEventConfirm = Do you really want to purge all partition events? +##view_adminTopology_message_removePEventConfirm = Do you really want to remove following partition events {0}? +##view_adminTopology_message_removePEventFail = Unable to remove {0} partition events(s). +##view_adminTopology_message_removeServerConfirm = Do you really want to remove servers {0}? +##view_adminTopology_message_removeServerFail = Unable to remove {0} server(s). +##view_adminTopology_message_removedAGroups = Removed {0} affinity group(s). +##view_adminTopology_message_removedAllPEvent = All partition events have been purged. +##view_adminTopology_message_removedAllPEventFail = Unable to purge all partition events. +##view_adminTopology_message_removedPEvent = Removed {0} partition events(s). +##view_adminTopology_message_removedServer = Removed {0} server(s). +##view_adminTopology_message_repartitioned = The cluster repartitioning was successfully invoked. +##view_adminTopology_message_serverUpdated = The server {0} was successfully updated. +##view_adminTopology_message_serverUpdateFail = Unable to update server {0}. +##view_adminTopology_message_setMode = Set {0} server(s) to {1} mode. +##view_adminTopology_message_setModeConfirm = Do you really want to set servers {0} to {1} mode? +##view_adminTopology_message_setModeFail = Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = Partition\u4e8b\u4ef6 ##view_adminTopology_partitionEvents_details = Details ##view_adminTopology_partitionEvents_detailsFilter = Details Filter diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java index 92b59d3..595ca8f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java @@ -90,6 +90,13 @@ public interface CloudManagerLocal { PageList<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc);
void markStaleServersDown(Subject subject); - + + /** + * Fetches the server based on provided criteria. + * + * @param subject caller + * @param criteria the criteria + * @return + */ PageList<Server> findServersByCriteria(Subject subject, ServerCriteria criteria); }
commit caa81f6bf0a2e126896b8d40e5f066f39e88e013 Author: Jirka Kremser jkremser@redhat.com Date: Wed Dec 19 13:01:23 2012 +0100
i18n for error messages, exception handling for agent and server views
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java index 3005f7d..4355814 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupDetailView.java @@ -53,6 +53,7 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar // private final CloudGWTServiceAsync cloudManager = GWTServiceLookup.getCloudService(); private final int affinityGroupId;
+ private static final int SECTION_COUNT = 3; private final LocatableSectionStack sectionStack; private SectionStackSection detailsSection = null; private SectionStackSection agentSection = null; @@ -105,7 +106,7 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar }
public boolean isInitialized() { - return initSectionCount >= 3; + return initSectionCount >= SECTION_COUNT; }
@Override @@ -136,7 +137,7 @@ public class AffinityGroupDetailView extends LocatableVLayout implements Bookmar // don't wait forever, give up after 20s and show what we have long elapsedMillis = System.currentTimeMillis() - startTime; if (elapsedMillis > 20000) { - initSectionCount = 3; + initSectionCount = SECTION_COUNT; } schedule(100); // Reschedule the timer. } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java index 026a846..f48e7b7 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java @@ -37,7 +37,10 @@ import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection;
import org.rhq.core.domain.cloud.AffinityGroup; +import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.resource.Agent; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.StringUtility; @@ -53,9 +56,9 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; */ public class AgentDetailView extends LocatableVLayout {
- // private final CloudGWTServiceAsync cloudManager = GWTServiceLookup.getCloudService(); private final int agentId;
+ private static final int SECTION_COUNT = 2; private final LocatableSectionStack sectionStack; private SectionStackSection detailsSection = null; private SectionStackSection failoverListSection = null; @@ -80,21 +83,31 @@ public class AgentDetailView extends LocatableVLayout { @Override protected void onInit() { super.onInit(); - GWTServiceLookup.getAgentService().getAgentByID(this.agentId, new AsyncCallback<Agent>() { - public void onSuccess(final Agent agent) { - prepareDetailsSection(sectionStack, agent); - prepareFailoverListSection(sectionStack, agent); + AgentCriteria criteria = new AgentCriteria(); + criteria.addFilterId(agentId); + GWTServiceLookup.getCloudService().findAgentsByCriteria(criteria, new AsyncCallback<PageList<Agent>>() { + public void onSuccess(final PageList<Agent> agents) { + if (agents == null || agents.isEmpty() || agents.size() != 1) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchAgentFail(String.valueOf(agentId))); + initSectionCount = SECTION_COUNT; + return; + } + prepareDetailsSection(sectionStack, agents.get(0)); + prepareFailoverListSection(sectionStack, agents.get(0)); }
public void onFailure(Throwable caught) { - SC.say("er1:" + caught); - //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchAgentFail(String.valueOf(agentId)) + " " + caught.getMessage(), + caught); + initSectionCount = SECTION_COUNT; } }); }
public boolean isInitialized() { - return initSectionCount >= 2; + return initSectionCount >= SECTION_COUNT; }
@Override @@ -122,7 +135,7 @@ public class AgentDetailView extends LocatableVLayout { // don't wait forever, give up after 20s and show what we have long elapsedMillis = System.currentTimeMillis() - startTime; if (elapsedMillis > 20000) { - initSectionCount = 2; + initSectionCount = SECTION_COUNT; } schedule(100); // Reschedule the timer. } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java index b50d852..dc34602 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java @@ -124,7 +124,7 @@ public class AgentTableView extends TableSection<AgentDatasource> implements Has showUpdateMembersAction(); } } - + private void showUpdateMembersAction() { addTableAction(extendLocatorId("editGroupAgents"), MSG.view_groupInventoryMembers_button_updateMembership(), new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, Permission.MANAGE_SETTINGS) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java index f09a707..dc96374 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDetailView.java @@ -62,6 +62,7 @@ public class PartitionEventDetailView extends LocatableVLayout implements Bookma
private final int partitionEventId;
+ private static final int SECTION_COUNT = 2; private final LocatableSectionStack sectionStack; private SectionStackSection detailsSection = null; private SectionStackSection agentSection = null; @@ -118,7 +119,7 @@ public class PartitionEventDetailView extends LocatableVLayout implements Bookma }
public boolean isInitialized() { - return initSectionCount >= 2; + return initSectionCount >= SECTION_COUNT; }
@Override @@ -146,7 +147,7 @@ public class PartitionEventDetailView extends LocatableVLayout implements Bookma // don't wait forever, give up after 20s and show what we have long elapsedMillis = System.currentTimeMillis() - startTime; if (elapsedMillis > 20000) { - initSectionCount = 2; + initSectionCount = SECTION_COUNT; } schedule(100); // Reschedule the timer. } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java index f3dbd4d..ccc11aa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java @@ -32,7 +32,6 @@ import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -46,12 +45,16 @@ import com.smartgwt.client.widgets.layout.SectionStackSection; import org.rhq.core.domain.cloud.AffinityGroup; import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.Server.OperationMode; +import org.rhq.core.domain.criteria.ServerCriteria; +import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.Log; import org.rhq.enterprise.gui.coregui.client.util.StringUtility; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; @@ -65,9 +68,9 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; */ public class ServerDetailView extends LocatableVLayout implements BookmarkableView {
- // private final CloudGWTServiceAsync cloudManager = GWTServiceLookup.getCloudService(); private final int serverId;
+ private static final int SECTION_COUNT = 2; private final LocatableSectionStack sectionStack; private SectionStackSection detailsSection = null; private SectionStackSection agentSection = null; @@ -92,31 +95,31 @@ public class ServerDetailView extends LocatableVLayout implements BookmarkableVi @Override protected void onInit() { super.onInit(); - GWTServiceLookup.getCloudService().getServerById(this.serverId, new AsyncCallback<Server>() { - public void onSuccess(final Server server) { - prepareDetailsSection(sectionStack, server); - prepareAgentSection(sectionStack, server); - // GWTServiceLookup.getCloudService().getAgentsByServerName(server.getName(), - // new AsyncCallback<List<Agent>>() { - // public void onSuccess(List<Agent> agents) { - // prepareAgentSection(sectionStack, server, agents); - // }; - // - // public void onFailure(Throwable caught) { - // //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); - // } - // }); + ServerCriteria criteria = new ServerCriteria(); + criteria.addFilterId(serverId); + GWTServiceLookup.getCloudService().findServersByCriteria(criteria, new AsyncCallback<PageList<Server>>() { + public void onSuccess(final PageList<Server> servers) { + if (servers == null || servers.isEmpty() || servers.size() != 1) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchServerFail(String.valueOf(serverId))); + initSectionCount = SECTION_COUNT; + return; + } + prepareDetailsSection(sectionStack, servers.get(0)); + prepareAgentSection(sectionStack, servers.get(0)); }
public void onFailure(Throwable caught) { - SC.say("er1:" + caught); - //TODO: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught); + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_fetchServerFail(String.valueOf(serverId)) + " " + + caught.getMessage(), caught); + initSectionCount = SECTION_COUNT; } }); }
public boolean isInitialized() { - return initSectionCount >= 2; + return initSectionCount >= SECTION_COUNT; }
@Override @@ -144,7 +147,7 @@ public class ServerDetailView extends LocatableVLayout implements BookmarkableVi // don't wait forever, give up after 20s and show what we have long elapsedMillis = System.currentTimeMillis() - startTime; if (elapsedMillis > 20000) { - initSectionCount = 2; + initSectionCount = SECTION_COUNT; } schedule(100); // Reschedule the timer. } @@ -228,20 +231,25 @@ public class ServerDetailView extends LocatableVLayout implements BookmarkableVi server.setOperationMode(OperationMode.valueOf(operationModeItem.getValueAsString())); GWTServiceLookup.getCloudService().updateServer(server, new AsyncCallback<Void>() { public void onSuccess(Void result) { - // todo: notify + Message msg = new Message(MSG.view_adminTopology_message_serverUpdated(server.getName()), + Message.Severity.Info); + CoreGUI.getMessageCenter().notify(msg); + }
public void onFailure(Throwable caught) { - // todo: handle + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_serverUpdateFail(server.getName()) + " " + + caught.getMessage(), caught); } }); } } }); - + form.setItems(nameItem, addressItem, portItem, securePortItem, operationModeItem, affinityGroupItem, installationDateItem, lastUpdatetem); - + LocatableToolStrip footer = new LocatableToolStrip(extendLocatorId("detailsFooter")); footer.setPadding(5); footer.setWidth100(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java index 3c08618..b50e18c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java @@ -37,7 +37,7 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.authz.Permission; -import org.rhq.core.domain.cloud.Server; +import org.rhq.core.domain.cloud.Server.OperationMode; import org.rhq.core.domain.criteria.BaseCriteria; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.IconEnum; @@ -56,8 +56,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Jirka Kremser * */ -public class ServerTableView extends TableSection<AbstractServerNodeDatasource<? extends Serializable, ? extends BaseCriteria>> - implements HasViewName { +public class ServerTableView extends + TableSection<AbstractServerNodeDatasource<? extends Serializable, ? extends BaseCriteria>> implements HasViewName {
public static final ViewName VIEW_ID = new ViewName("Servers(GWT)", MSG.view_adminTopology_servers() + "(GWT)", IconEnum.SERVERS); @@ -141,117 +141,36 @@ public class ServerTableView extends TableSection<AbstractServerNodeDatasource<? }
private void showCommonActions() { - addTableAction(extendLocatorId("setNormal"), MSG.view_adminTopology_server_setNormal(), - MSG.common_msg_areYouSure(), new AuthorizedTableAction(this, TableActionEnablement.ANY, - Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - List<String> selectedNames = getSelectedNames(selections); - // TODO: msg - // String message = MSG.view_admin_plugins_serverDisableConfirm(selectedNames.toString()); - String message = "Really? Normal? For all I've done for you? " + selectedNames; - SC.ask(message, new BooleanCallback() { - public void execute(Boolean confirmed) { - if (confirmed) { - int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); - GWTServiceLookup.getCloudService().updateServerMode(selectedIds, - Server.OperationMode.NORMAL, new AsyncCallback<Void>() { - public void onSuccess(Void arg0) { - // TODO: msg - Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); - CoreGUI.getMessageCenter().notify(msg); - refresh(); - } + addChangeOperationModeAction(OperationMode.NORMAL, MSG.view_adminTopology_server_setMaintenance()); + addChangeOperationModeAction(OperationMode.MAINTENANCE, MSG.view_adminTopology_server_setMaintenance());
- public void onFailure(Throwable caught) { - // TODO: msg - CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); - refreshTableInfo(); - } - - }); - } else { - refreshTableInfo(); - } - } - }); - } - }); - - addTableAction(extendLocatorId("setMaintenance"), MSG.view_adminTopology_server_setMaintenance(), + addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), null, new AuthorizedTableAction(this, TableActionEnablement.ANY, Permission.MANAGE_SETTINGS) { public void executeAction(final ListGridRecord[] selections, Object actionValue) { List<String> selectedNames = getSelectedNames(selections); - // TODO: msg - // String message = MSG.view_admin_plugins_serverDisableConfirm(selectedNames.toString()); - String message = "Really? Maitenance? For all I've done for you? " + selectedNames; + String message = MSG.view_adminTopology_message_removeServerConfirm(selectedNames.toString()); SC.ask(message, new BooleanCallback() { public void execute(Boolean confirmed) { if (confirmed) { int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); - GWTServiceLookup.getCloudService().updateServerMode(selectedIds, - Server.OperationMode.MAINTENANCE, new AsyncCallback<Void>() { - public void onSuccess(Void arg0) { - // TODO: msg - Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); - CoreGUI.getMessageCenter().notify(msg); - refresh(); - } - - public void onFailure(Throwable caught) { - // TODO: msg - CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); - refreshTableInfo(); - } - - }); - } else { - refreshTableInfo(); - } - } - }); - } - }); - - addTableAction(extendLocatorId("removeSelected"), MSG.view_adminTopology_server_removeSelected(), - MSG.common_msg_areYouSure(), new AuthorizedTableAction(this, TableActionEnablement.ANY, - Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - List<String> selectedNames = getSelectedNames(selections); - String message = "Really? Delete? For all I've done for you? " + selectedNames; - SC.ask(message, new BooleanCallback() { - public void execute(Boolean confirmed) { - if (confirmed) { - int[] selectedIds = getSelectedIds(selections); - SC.say("setting servers to maintenance mode, ids: " + selectedIds); GWTServiceLookup.getCloudService().deleteServers(selectedIds, new AsyncCallback<Void>() { public void onSuccess(Void arg0) { - // TODO: msg Message msg = new Message(MSG - .view_admin_plugins_disabledServerPlugins("sdf"), Message.Severity.Info); + .view_adminTopology_message_removedServer(String + .valueOf(selections.length)), Message.Severity.Info); CoreGUI.getMessageCenter().notify(msg); refresh(); }
public void onFailure(Throwable caught) { - // TODO: msg CoreGUI.getErrorHandler().handleError( - MSG.view_admin_plugins_disabledServerPluginsFailure() + " " - + caught.getMessage(), caught); + MSG.view_adminTopology_message_removeServerFail(String + .valueOf(selections.length)) + " " + caught.getMessage(), caught); refreshTableInfo(); }
}); - } else { - refreshTableInfo(); } } }); @@ -259,6 +178,43 @@ public class ServerTableView extends TableSection<AbstractServerNodeDatasource<? }); }
+ private void addChangeOperationModeAction(final OperationMode mode, String label) { + addTableAction(extendLocatorId("set" + mode), label, null, new AuthorizedTableAction(this, + TableActionEnablement.ANY, Permission.MANAGE_SETTINGS) { + public void executeAction(final ListGridRecord[] selections, Object actionValue) { + List<String> selectedNames = getSelectedNames(selections); + String message = MSG.view_adminTopology_message_setModeConfirm(selectedNames.toString(), mode.name()); + SC.ask(message, new BooleanCallback() { + public void execute(Boolean confirmed) { + if (confirmed) { + int[] selectedIds = getSelectedIds(selections); + GWTServiceLookup.getCloudService().updateServerMode(selectedIds, mode, + new AsyncCallback<Void>() { + public void onSuccess(Void result) { + Message msg = new Message(MSG.view_adminTopology_message_setMode( + String.valueOf(selections.length), mode.name()), Message.Severity.Info); + CoreGUI.getMessageCenter().notify(msg); + refresh(); + } + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + MSG.view_adminTopology_message_setModeFail( + String.valueOf(selections.length), mode.name()) + + " " + caught.getMessage(), caught); + refreshTableInfo(); + } + + }); + } else { + refreshTableInfo(); + } + } + }); + } + }); + } + private void showUpdateMembersAction() { addTableAction(extendLocatorId("editGroupServers"), MSG.view_groupInventoryMembers_button_updateMembership(), new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, Permission.MANAGE_SETTINGS) { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 47611e8..ceaad0d 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties @@ -552,6 +552,16 @@ view_adminTopology_agentDetail_address = Address view_adminTopology_agentDetail_agentFailoverList = Agent Failover List view_adminTopology_agentDetail_currentServer = Current Server view_adminTopology_agentDetail_token = Token +view_adminTopology_message_fetchServerFail=Unable to fetch server details for server with id {0}. +view_adminTopology_message_fetchAgentFail=Unable to fetch agent details for agent with id {0}. +view_adminTopology_message_removeServerConfirm=Do you really want to remove servers [{0}]? +view_adminTopology_message_removeServerFail=Unable to remove {0} server(s). +view_adminTopology_message_removedServer=Removed {0} server(s). +view_adminTopology_message_serverUpdated=The server {0} was successfully updated. +view_adminTopology_message_serverUpdateFail=Unable to update server {0}. +view_adminTopology_message_setMode=Set {0} server(s) to {1} mode. +view_adminTopology_message_setModeConfirm=Do you really want to set servers [{0}] to {1} mode? +view_adminTopology_message_setModeFail=Unable to set {0} server(s) to {1} mode. view_adminTopology_partitionEvents = Partition Events view_adminTopology_partitionEvents_details = Details view_adminTopology_partitionEvents_detailsFilter = Details Filter
commit e3c531c1f52ef4298b0e5d29a044765cc97c8ac7 Author: Jirka Kremser jkremser@redhat.com Date: Tue Dec 18 17:12:46 2012 +0100
Assigning the agent to the affinity group; some refactoring (renaming AgentNodeDatasource -> AgentDatasource, AgentNodeDatasourceField -> AgentDatasourceField)
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Agent.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Agent.java index 870cc8f..5948a7e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Agent.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Agent.java @@ -172,6 +172,9 @@ public class Agent implements Serializable { public static final String QUERY_UPDATE_STATUS_BY_MEASUREMENT_BASELINE = "Agent.updateStatusByMeasurementBasleine"; public static final String QUERY_UPDATE_STATUS_BY_AGENT = "Agent.updateStatusByAgent"; public static final String QUERY_UPDATE_STATUS_FOR_ALL = "Agent.updateStatusForAll"; + + // this value is set, when authorized user wants to reset the token + public static final String SECURITY_TOKEN_RESET = "@#$reset$#@";
@Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "id") diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java new file mode 100644 index 0000000..5515e18 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupAgentsSelector.java @@ -0,0 +1,264 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.enterprise.gui.coregui.client.admin.topology; + +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.util.SC; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.events.CloseClickEvent; +import com.smartgwt.client.widgets.events.CloseClickHandler; +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.TextItem; +import com.smartgwt.client.widgets.grid.ListGridRecord; +import com.smartgwt.client.widgets.layout.HLayout; +import com.smartgwt.client.widgets.layout.VLayout; + +import org.rhq.core.domain.criteria.AgentCriteria; +import org.rhq.core.domain.resource.Agent; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.IconEnum; +import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; +import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; + +/** + * @author Jirka Kremser + */ +public class AffinityGroupAgentsSelector extends AbstractSelector<Agent, AgentCriteria> { + + private final Integer affinityGroupId; + + private static RPCDataSource<Agent, AgentCriteria> datasource = null; + + private static Window modalWindow; + private static boolean shouldBeClosed; + private static VLayout layout; + private List<Integer> originallyAssignedIds; + + private AffinityGroupAgentsSelector() { + super(""); + affinityGroupId = -1; + } + + private AffinityGroupAgentsSelector(String id, Integer affinityGroupId) { + super(id, false); + this.affinityGroupId = affinityGroupId; + prepareMembers(this); + } + + @Override + protected DynamicForm getAvailableFilterForm() { + if (availableFilterForm == null) { + availableFilterForm = new LocatableDynamicForm(extendLocatorId("AgeSelectAvailFilterForm")); + availableFilterForm.setWidth("75%"); + final TextItem search = new TextItem(NAME.propertyName(), MSG.common_title_search()); + availableFilterForm.setItems(search); + } + return availableFilterForm; + } + + private void prepareMembers(final AffinityGroupAgentsSelector selector) { + AgentCriteria criteria = new AgentCriteria(); + criteria.addFilterAffinityGroupId(affinityGroupId); + GWTServiceLookup.getCloudService().findAgentsByCriteria(criteria, new AsyncCallback<PageList<Agent>>() { + public void onSuccess(PageList<Agent> result) { + ListGridRecord[] records = getDataSource().buildRecords(result); + originallyAssignedIds = getIdList(records); + setAssigned(records); + modalWindow.addItem(layout); + modalWindow.show(); + selector.reset(); + } + + @Override + public void onFailure(Throwable t) { + //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + } + }); + + } + + @Override + protected RPCDataSource<Agent, AgentCriteria> getDataSource() { + if (datasource == null) { + datasource = new AgentDatasource(affinityGroupId, false); + } + return datasource; + } + + @Override + protected int getMaxAvailableRecords() { + return 3000; + } + + @Override + protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { + String search = (String) availableFilterForm.getValue(NAME.propertyName()); + Criteria criteria = new Criteria(); + if (null != search) { + criteria.addCriteria(NAME.propertyName(), search); + } + return criteria; + } + + @Override + protected String getItemTitle() { + return MSG.view_adminTopology_agents(); + } + + @Override + protected String getItemIcon() { + return IconEnum.AGENT.getIcon16x16Path(); + } + + public static void show(Integer affinityGroupId, final TableSection parrent) { + modalWindow = new Window(); + modalWindow.addCloseClickHandler(new CloseClickHandler() { + public void onCloseClick(CloseClickEvent event) { + closeAndRefresh(parrent, false); + } + }); + modalWindow.setTitle(MSG.view_adminTopology_agents() + ": " + + MSG.view_adminTopology_affinityGroups_createNew()); + modalWindow.setOverflow(Overflow.VISIBLE); + modalWindow.setWidth(800); + modalWindow.setHeight(400); + modalWindow.setAutoCenter(true); + modalWindow.setCanDragResize(true); + modalWindow.setCanDragReposition(true); + + layout = new VLayout(); + layout.setWidth100(); + layout.setHeight100(); + layout.setPadding(10); + layout.setLayoutMargin(10); + + final AffinityGroupAgentsSelector selector = new AffinityGroupAgentsSelector("foo", affinityGroupId); + layout.addMember(selector); + + IButton cancel = new LocatableIButton(selector.extendLocatorId("Cancel"), MSG.common_button_cancel()); + cancel.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + closeAndRefresh(parrent, false); + } + }); + IButton save = new LocatableIButton(selector.extendLocatorId("Save"), MSG.common_button_save()); + save.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + List<Integer> actuallySelected = getIdList(selector.getSelectedRecords()); + List<Integer> originallySelected = selector.getOriginallyAssignedIds(); + originallySelected.removeAll(actuallySelected); + actuallySelected.removeAll(selector.getOriginallyAssignedIds()); + shouldBeClosed = true; + if (!originallySelected.isEmpty()) { + shouldBeClosed = false; + GWTServiceLookup.getCloudService().removeAgentsFromGroup( + originallySelected.toArray(new Integer[originallySelected.size()]), new AsyncCallback<Void>() { + + public void onSuccess(Void result) { + closeAndRefresh(parrent, true); + } + + public void onFailure(Throwable caught) { + //todo: error handling + SC.say("errX"); + } + }); + } + if (!actuallySelected.isEmpty()) { + shouldBeClosed = false; + GWTServiceLookup.getCloudService().addAgentsToGroup(selector.getAffinityGroupId(), + actuallySelected.toArray(new Integer[actuallySelected.size()]), new AsyncCallback<Void>() { + + public void onSuccess(Void result) { + closeAndRefresh(parrent, true); + } + + public void onFailure(Throwable caught) { + //todo: error handling + SC.say("errX"); + } + }); + } + if (shouldBeClosed) { + closeAndRefresh(parrent, false); + } + // SC.say("To del: " + originallySelected + "\n\nTo add: " + actuallySelected); + + } + }); + + HLayout buttons = new HLayout(10); + buttons.setHeight(20); + buttons.setLayoutAlign(Alignment.CENTER); + buttons.setLayoutBottomMargin(0); + buttons.addMember(save); + buttons.addMember(cancel); + layout.addMember(buttons); + } + + private static void closeAndRefresh(TableSection parrent, boolean fullRefresh) { + if (modalWindow != null) { + modalWindow.destroy(); + } + if (fullRefresh) { + parrent.refresh(); + } else { + parrent.refreshTableInfo(); + } + } + + private static List<Integer> getIdList(ListGridRecord[] records) { + if (records == null) { + return null; + } + List<Integer> ids = new ArrayList<Integer>(records.length); + for (ListGridRecord record : records) { + ids.add(record.getAttributeAsInt(AgentDatasourceField.FIELD_ID.propertyName())); + } + return ids; + } + + public List<Integer> getOriginallyAssignedIds() { + return new ArrayList<Integer>(originallyAssignedIds); + } + + public Integer getAffinityGroupId() { + return affinityGroupId; + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java index f104d6c..13b1559 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java @@ -22,6 +22,8 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
+import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; + import java.util.ArrayList; import java.util.List;
@@ -37,18 +39,23 @@ import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.events.CloseClickEvent; import com.smartgwt.client.widgets.events.CloseClickHandler; import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.cloud.Server; +import org.rhq.core.domain.cloud.Server.OperationMode; import org.rhq.core.domain.criteria.ServerCriteria; -import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.IconEnum; +import org.rhq.enterprise.gui.coregui.client.components.form.SortedSelectItem; import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; import org.rhq.enterprise.gui.coregui.client.components.table.TableSection; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
/** @@ -56,8 +63,6 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; */ public class AffinityGroupServersSelector extends AbstractSelector<Server, ServerCriteria> {
- private static final String ITEM_ICON = "types/Server_up_16.png"; - private final Integer affinityGroupId;
private static RPCDataSource<Server, ServerCriteria> datasource = null; @@ -77,10 +82,41 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve this.affinityGroupId = affinityGroupId; prepareMembers(this); } + + @Override + protected DynamicForm getAvailableFilterForm() { + if (availableFilterForm == null) { + availableFilterForm = new LocatableDynamicForm(extendLocatorId("SerSelectAvailFilterForm")); + availableFilterForm.setNumCols(4); + availableFilterForm.setWidth("75%"); + final TextItem search = new TextItem(NAME.propertyName(), MSG.common_title_search()); + final SelectItem operationModeSelect = new SortedSelectItem(ServerDatasource.FILTER_OPERATION_MODE, MSG.view_adminTopology_serverDetail_operationMode()); + operationModeSelect.setValueMap(buildOperationModeOptions()); + operationModeSelect.setValue("ALL"); +// +// final EnumSelectItem operationModeFilter = new EnumSelectItem(ServerDatasource.FILTER_OPERATION_MODE, +// MSG.view_adminTopology_serverDetail_operationMode(), OperationMode.class, null, null); + + + availableFilterForm.setItems(search, operationModeSelect); + } + return availableFilterForm; + } + + private String[] buildOperationModeOptions() { + OperationMode[] modes = OperationMode.values(); + String[] options = new String[modes.length + 1]; + for (int i = 0; i < modes.length; i++) { + options[i] = modes[i].toString(); + } + options[modes.length] = "ALL"; + return options; + }
private void prepareMembers(final AffinityGroupServersSelector selector) { - GWTServiceLookup.getCloudService().getServerMembersByAffinityGroupId(affinityGroupId, - PageControl.getUnlimitedInstance(), new AsyncCallback<PageList<Server>>() { + ServerCriteria criteria = new ServerCriteria(); + criteria.addFilterAffinityGroupId(affinityGroupId); + GWTServiceLookup.getCloudService().findServersByCriteria(criteria, new AsyncCallback<PageList<Server>>() { public void onSuccess(PageList<Server> result) { ListGridRecord[] records = getDataSource().buildRecords(result); originallyAssignedIds = getIdList(records); @@ -107,28 +143,32 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve }
@Override - protected DynamicForm getAvailableFilterForm() { - return null; // No Filters Currently - } - - @Override protected int getMaxAvailableRecords() { return 500; }
@Override protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { - return null; // No Filters Currently + String search = (String) availableFilterForm.getValue(NAME.propertyName()); + String operationMode = (String) availableFilterForm.getValue(ServerDatasource.FILTER_OPERATION_MODE); + Criteria criteria = new Criteria(); + if (null != search) { + criteria.addCriteria(NAME.propertyName(), search); + } + if (operationMode != null && !"ALL".equals(operationMode)) { + criteria.addCriteria(ServerDatasource.FILTER_OPERATION_MODE, operationMode); + } + return criteria; }
@Override protected String getItemTitle() { - return MSG.view_adminTopology_affinityGroups(); + return MSG.view_adminTopology_servers(); }
@Override protected String getItemIcon() { - return ITEM_ICON; + return IconEnum.SERVERS.getIcon16x16Path(); }
public static void show(Integer affinityGroupId, final TableSection parrent) { @@ -138,7 +178,7 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, Serve closeAndRefresh(parrent, false); } }); - modalWindow.setTitle(MSG.view_adminTopology_affinityGroups() + ": " + modalWindow.setTitle(MSG.view_adminTopology_servers() + ": " + MSG.view_adminTopology_affinityGroups_createNew()); modalWindow.setOverflow(Overflow.VISIBLE); modalWindow.setWidth(800); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java new file mode 100644 index 0000000..ac1d26b --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasource.java @@ -0,0 +1,227 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.gui.coregui.client.admin.topology; + +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_ADDRESS; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP_ID; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_ID; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_LAST_AVAILABILITY_REPORT; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_NAME; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_PORT; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_SERVER; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_SERVER_ID; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.DataSourceField; +import com.smartgwt.client.data.Record; +import com.smartgwt.client.data.fields.DataSourceIntegerField; +import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.criteria.AgentCriteria; +import org.rhq.core.domain.resource.Agent; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageList; +import org.rhq.core.domain.util.PageOrdering; +import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.Log; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * @author Jirka Kremser + * + */ +public class AgentDatasource extends RPCDataSource<Agent, AgentCriteria> { + + // filters + public static final String FILTER_ADDRESS = FIELD_ADDRESS.propertyName(); + public static final String FILTER_PORT = FIELD_PORT.propertyName(); + public static final String FILTER_SERVER_ID = "serverId"; + public static final String FILTER_AFFINITY_GROUP_ID = "affinityGroupId"; + + + private final Integer id; + private final boolean isAffinityGroupId; + + public AgentDatasource(Integer id, boolean isAffinityGroupId) { + super(); + this.id = id; + this.isAffinityGroupId = isAffinityGroupId; + List<DataSourceField> fields = addDataSourceFields(); + addFields(fields); + } + + @Override + protected List<DataSourceField> addDataSourceFields() { + List<DataSourceField> fields = super.addDataSourceFields(); + DataSourceField idField = new DataSourceIntegerField(FIELD_ID.propertyName(), FIELD_ID.title(), 50); + idField.setPrimaryKey(true); + idField.setHidden(true); + fields.add(idField); + return fields; + } + + public List<ListGridField> getListGridFields() { + List<ListGridField> fields = new ArrayList<ListGridField>(); + + ListGridField idField = FIELD_ID.getListGridField(); + idField.setHidden(true); + fields.add(idField); + fields.add(FIELD_NAME.getListGridField("*")); + fields.add(FIELD_SERVER.getListGridField("120")); + fields.add(FIELD_ADDRESS.getListGridField("110")); + + ListGridField serverIdField = FIELD_SERVER_ID.getListGridField(); + serverIdField.setHidden(true); + fields.add(serverIdField); + + fields.add(FIELD_PORT.getListGridField("90")); + ListGridField lastAvailabilityReportField = FIELD_LAST_AVAILABILITY_REPORT.getListGridField("120"); + TimestampCellFormatter.prepareDateField(lastAvailabilityReportField); + fields.add(lastAvailabilityReportField); + + if (!isAffinityGroupId) { + fields.add(FIELD_AFFINITY_GROUP.getListGridField("100")); + ListGridField affinityGroupIdField = FIELD_AFFINITY_GROUP_ID.getListGridField(); + affinityGroupIdField.setHidden(true); + fields.add(affinityGroupIdField); + } + + return fields; + } + + @Override + protected void executeFetch(final DSRequest request, final DSResponse response, AgentCriteria criteria) { +// final PageControl pc = getPageControl(request); + +// AsyncCallback<PageList<Agent>> callback = new AsyncCallback<PageList<Agent>>() { +// public void onSuccess(PageList<Agent> result) { +// response.setData(buildRecords(result)); +// response.setTotalRows(result.size()); +// processResponse(request.getRequestId(), response); +// } +// +// @Override +// public void onFailure(Throwable t) { +// //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); +// response.setStatus(DSResponse.STATUS_FAILURE); +// processResponse(request.getRequestId(), response); +// } +// }; +// +// + if (isAffinityGroupId) { +// GWTServiceLookup.getCloudService().getAgentMembersByAffinityGroupId(id, pc, callback); + criteria.addFilterAffinityGroupId(id); + } else if (id != null) { + // if id == null all agent are returned + criteria.addFilterServerId(id); +// GWTServiceLookup.getAgentService().getAgentsByServer(id, pc, callback); + } + + GWTServiceLookup.getCloudService().findAgentsByCriteria(criteria, new AsyncCallback<PageList<Agent>>() { + public void onSuccess(PageList<Agent> result) { + response.setData(buildRecords(result)); + response.setTotalRows(result.size()); + processResponse(request.getRequestId(), response); + } + + @Override + public void onFailure(Throwable t) { + //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); + response.setStatus(DSResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + }); + } + + /** + * Returns a prepopulated PageControl based on the provided DSRequest. This will set sort fields, + * pagination, but *not* filter fields. + * + * @param request the request to turn into a page control + * @return the page control for passing to criteria and other queries + */ + protected PageControl getPageControl(DSRequest request) { + // Initialize paging. + PageControl pageControl = new PageControl(0, getDataPageSize()); + + // Initialize sorting. + String sortBy = request.getAttribute("sortBy"); + if (sortBy != null) { + String[] sorts = sortBy.split(","); + for (String sort : sorts) { + PageOrdering ordering = (sort.startsWith("-")) ? PageOrdering.DESC : PageOrdering.ASC; + String columnName = (ordering == PageOrdering.DESC) ? sort.substring(1) : sort; + pageControl.addDefaultOrderingField(columnName, ordering); + } + } + + return pageControl; + } + + @Override + public Agent copyValues(Record from) { + throw new UnsupportedOperationException("AgentNodeDatasource.copyValues(Record from)"); + } + + @Override + public ListGridRecord copyValues(Agent from) { + ListGridRecord record = new ListGridRecord(); + record.setAttribute(FIELD_ID.propertyName(), from.getId()); + record.setAttribute(FIELD_NAME.propertyName(), from.getName()); + record.setAttribute(FIELD_ADDRESS.propertyName(), from.getAddress()); + record.setAttribute(FIELD_PORT.propertyName(), from.getPort()); + record.setAttribute(FIELD_SERVER.propertyName(), from.getServer() == null ? "" : from.getServer().getName()); + record.setAttribute(FIELD_SERVER_ID.propertyName(), from.getServer() == null ? "" : from.getServer().getId()); + record.setAttribute(FIELD_LAST_AVAILABILITY_REPORT.propertyName(), from.getLastAvailabilityReport()); + record.setAttribute(FIELD_AFFINITY_GROUP.propertyName(), from.getAffinityGroup() == null ? "" : from + .getAffinityGroup().getName()); + record.setAttribute(FIELD_AFFINITY_GROUP_ID.propertyName(), from.getAffinityGroup() == null ? "" : from + .getAffinityGroup().getId()); + + return record; + } + + @Override + protected AgentCriteria getFetchCriteria(DSRequest request) { + AgentCriteria criteria = new AgentCriteria(); + // printRequestCriteria(request); + criteria.addFilterId(getFilter(request, FIELD_ID.propertyName(), Integer.class)); + criteria.addFilterName(getFilter(request, FIELD_NAME.propertyName(), String.class)); + criteria.addFilterAddress(getFilter(request, FILTER_ADDRESS, String.class)); + criteria.addFilterPort(getFilter(request, FILTER_PORT, Integer.class)); + criteria.addFilterServerId(getFilter(request, FILTER_SERVER_ID, Integer.class)); + criteria.addFilterAffinityGroupId(getFilter(request, FILTER_AFFINITY_GROUP_ID, Integer.class)); + + + //@todo: Remove me when finished debugging search expression + Log.debug(" *** AgentCriteria Search String: " + getFilter(request, "search", String.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class)); + + return criteria; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java new file mode 100644 index 0000000..26792d4 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDatasourceField.java @@ -0,0 +1,83 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.gui.coregui.client.admin.topology; + +import com.smartgwt.client.widgets.grid.ListGridField; + +import org.rhq.enterprise.gui.coregui.client.CoreGUI; + +/** + * @author Jirka Kremser + * + */ +public enum AgentDatasourceField { + + FIELD_ID("id", CoreGUI.getMessages().common_title_id()), + + FIELD_NAME("name", CoreGUI.getMessages().common_title_name()), + + FIELD_SERVER("server", CoreGUI.getMessages().view_adminTopology_agent_connectedServer()), + + FIELD_SERVER_ID("serverId", "serverId"), + + FIELD_ADDRESS("address", CoreGUI.getMessages().view_adminTopology_agent_agentBindAddress()), + + FIELD_PORT("port", CoreGUI.getMessages().view_adminTopology_agent_agentBindPort()), + + FIELD_LAST_AVAILABILITY_REPORT("lastAvailabilityReport", CoreGUI.getMessages().view_adminTopology_agent_lastAvailabilityReport()), + + FIELD_AGENT_TOKEN("agentToken", CoreGUI.getMessages().view_adminTopology_agentDetail_token()), + + FIELD_AFFINITY_GROUP("affinityGroup", CoreGUI.getMessages().view_adminTopology_server_affinityGroup()), + + FIELD_AFFINITY_GROUP_ID("affinityGroupId", "affinityGroupId"); + + /** + * Corresponds to a property name of Server (e.g. operationMode). + */ + private String propertyName; + + /** + * The table header for the field or property (e.g. Mode). + */ + private String title; + + private AgentDatasourceField(String propertyName, String title) { + this.propertyName = propertyName; + this.title = title; + } + + public String propertyName() { + return propertyName; + } + + public String title() { + return title; + } + + public ListGridField getListGridField() { + return new ListGridField(propertyName, title); + } + + public ListGridField getListGridField(String width) { + ListGridField field = new ListGridField(propertyName, title); + field.setWidth(width); + return field; + } +} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java index b91f71d..026a846 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentDetailView.java @@ -19,13 +19,13 @@
package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_ADDRESS; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AGENT_TOKEN; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_LAST_AVAILABILITY_REPORT; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_NAME; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_PORT; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_SERVER; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_ADDRESS; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AGENT_TOKEN; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_LAST_AVAILABILITY_REPORT; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_NAME; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_PORT; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_SERVER;
import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasource.java deleted file mode 100644 index 8a9da96..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasource.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.gui.coregui.client.admin.topology; - -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_ADDRESS; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP_ID; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_ID; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_LAST_AVAILABILITY_REPORT; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_NAME; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_PORT; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_SERVER; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_SERVER_ID; - -import java.util.ArrayList; -import java.util.List; - -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.data.DSRequest; -import com.smartgwt.client.data.DSResponse; -import com.smartgwt.client.data.DataSourceField; -import com.smartgwt.client.data.Record; -import com.smartgwt.client.data.fields.DataSourceIntegerField; -import com.smartgwt.client.widgets.grid.ListGridField; -import com.smartgwt.client.widgets.grid.ListGridRecord; - -import org.rhq.core.domain.criteria.Criteria; -import org.rhq.core.domain.resource.Agent; -import org.rhq.core.domain.util.PageControl; -import org.rhq.core.domain.util.PageList; -import org.rhq.core.domain.util.PageOrdering; -import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; - -/** - * @author Jirka Kremser - * - */ -public class AgentNodeDatasource extends RPCDataSource<Agent, Criteria> { - - private final Integer id; - private final boolean isAffinityGroupId; - - public AgentNodeDatasource(Integer id, boolean isAffinityGroupId) { - super(); - this.id = id; - this.isAffinityGroupId = isAffinityGroupId; - List<DataSourceField> fields = addDataSourceFields(); - addFields(fields); - } - - @Override - protected List<DataSourceField> addDataSourceFields() { - List<DataSourceField> fields = super.addDataSourceFields(); - DataSourceField idField = new DataSourceIntegerField(FIELD_ID.propertyName(), FIELD_ID.title(), 50); - idField.setPrimaryKey(true); - idField.setHidden(true); - fields.add(idField); - return fields; - } - - public List<ListGridField> getListGridFields() { - List<ListGridField> fields = new ArrayList<ListGridField>(); - - ListGridField idField = FIELD_ID.getListGridField(); - idField.setHidden(true); - fields.add(idField); - fields.add(FIELD_NAME.getListGridField("*")); - fields.add(FIELD_SERVER.getListGridField("120")); - fields.add(FIELD_ADDRESS.getListGridField("110")); - - ListGridField serverIdField = FIELD_SERVER_ID.getListGridField(); - serverIdField.setHidden(true); - fields.add(serverIdField); - - fields.add(FIELD_PORT.getListGridField("90")); - ListGridField lastAvailabilityReportField = FIELD_LAST_AVAILABILITY_REPORT.getListGridField("120"); - TimestampCellFormatter.prepareDateField(lastAvailabilityReportField); - fields.add(lastAvailabilityReportField); - - if (!isAffinityGroupId) { - fields.add(FIELD_AFFINITY_GROUP.getListGridField("100")); - ListGridField affinityGroupIdField = FIELD_AFFINITY_GROUP_ID.getListGridField(); - affinityGroupIdField.setHidden(true); - fields.add(affinityGroupIdField); - } - - return fields; - } - - @Override - protected void executeFetch(final DSRequest request, final DSResponse response, Criteria criteria) { - final PageControl pc = getPageControl(request); - - AsyncCallback<PageList<Agent>> callback = new AsyncCallback<PageList<Agent>>() { - public void onSuccess(PageList<Agent> result) { - response.setData(buildRecords(result)); - response.setTotalRows(result.size()); - processResponse(request.getRequestId(), response); - } - - @Override - public void onFailure(Throwable t) { - //todo: CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), t); - response.setStatus(DSResponse.STATUS_FAILURE); - processResponse(request.getRequestId(), response); - } - }; - - if (isAffinityGroupId) { - GWTServiceLookup.getCloudService().getAgentMembersByAffinityGroupId(id, pc, callback); - } else { - // if id == null all agent are returned - GWTServiceLookup.getAgentService().getAgentsByServer(id, pc, callback); - } - } - - /** - * Returns a prepopulated PageControl based on the provided DSRequest. This will set sort fields, - * pagination, but *not* filter fields. - * - * @param request the request to turn into a page control - * @return the page control for passing to criteria and other queries - */ - protected PageControl getPageControl(DSRequest request) { - // Initialize paging. - PageControl pageControl = new PageControl(0, getDataPageSize()); - - // Initialize sorting. - String sortBy = request.getAttribute("sortBy"); - if (sortBy != null) { - String[] sorts = sortBy.split(","); - for (String sort : sorts) { - PageOrdering ordering = (sort.startsWith("-")) ? PageOrdering.DESC : PageOrdering.ASC; - String columnName = (ordering == PageOrdering.DESC) ? sort.substring(1) : sort; - pageControl.addDefaultOrderingField(columnName, ordering); - } - } - - return pageControl; - } - - @Override - public Agent copyValues(Record from) { - throw new UnsupportedOperationException("AgentNodeDatasource.copyValues(Record from)"); - } - - @Override - public ListGridRecord copyValues(Agent from) { - ListGridRecord record = new ListGridRecord(); - record.setAttribute(FIELD_ID.propertyName(), from.getId()); - record.setAttribute(FIELD_NAME.propertyName(), from.getName()); - record.setAttribute(FIELD_ADDRESS.propertyName(), from.getAddress()); - record.setAttribute(FIELD_PORT.propertyName(), from.getPort()); - record.setAttribute(FIELD_SERVER.propertyName(), from.getServer() == null ? "" : from.getServer().getName()); - record.setAttribute(FIELD_SERVER_ID.propertyName(), from.getServer() == null ? "" : from.getServer().getId()); - record.setAttribute(FIELD_LAST_AVAILABILITY_REPORT.propertyName(), from.getLastAvailabilityReport()); - record.setAttribute(FIELD_AFFINITY_GROUP.propertyName(), from.getAffinityGroup() == null ? "" : from - .getAffinityGroup().getName()); - record.setAttribute(FIELD_AFFINITY_GROUP_ID.propertyName(), from.getAffinityGroup() == null ? "" : from - .getAffinityGroup().getId()); - - return record; - } - - @Override - protected Criteria getFetchCriteria(DSRequest request) { - // we don't use criteria for this datasource, just return null - return null; - } -} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasourceField.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasourceField.java deleted file mode 100644 index dc82130..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentNodeDatasourceField.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.gui.coregui.client.admin.topology; - -import com.smartgwt.client.widgets.grid.ListGridField; - -import org.rhq.enterprise.gui.coregui.client.CoreGUI; - -/** - * @author Jirka Kremser - * - */ -public enum AgentNodeDatasourceField { - - FIELD_ID("id", CoreGUI.getMessages().common_title_id()), - - FIELD_NAME("name", CoreGUI.getMessages().common_title_name()), - - FIELD_SERVER("server", CoreGUI.getMessages().view_adminTopology_agent_connectedServer()), - - FIELD_SERVER_ID("serverId", "serverId"), - - FIELD_ADDRESS("address", CoreGUI.getMessages().view_adminTopology_agent_agentBindAddress()), - - FIELD_PORT("port", CoreGUI.getMessages().view_adminTopology_agent_agentBindPort()), - - FIELD_LAST_AVAILABILITY_REPORT("lastAvailabilityReport", CoreGUI.getMessages().view_adminTopology_agent_lastAvailabilityReport()), - - FIELD_AGENT_TOKEN("agentToken", CoreGUI.getMessages().view_adminTopology_agentDetail_token()), - - FIELD_AFFINITY_GROUP("affinityGroup", CoreGUI.getMessages().view_adminTopology_server_affinityGroup()), - - FIELD_AFFINITY_GROUP_ID("affinityGroupId", "affinityGroupId"); - - /** - * Corresponds to a property name of Server (e.g. operationMode). - */ - private String propertyName; - - /** - * The table header for the field or property (e.g. Mode). - */ - private String title; - - private AgentNodeDatasourceField(String propertyName, String title) { - this.propertyName = propertyName; - this.title = title; - } - - public String propertyName() { - return propertyName; - } - - public String title() { - return title; - } - - public ListGridField getListGridField() { - return new ListGridField(propertyName, title); - } - - public ListGridField getListGridField(String width) { - ListGridField field = new ListGridField(propertyName, title); - field.setWidth(width); - return field; - } -} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java index d3b8761..b50d852 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AgentTableView.java @@ -18,15 +18,14 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP_ID; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_SERVER; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_SERVER_ID; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP_ID; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_SERVER; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_SERVER_ID;
import java.util.List;
import com.smartgwt.client.types.SortDirection; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; @@ -47,7 +46,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; /** * @author Jirka Kremser */ -public class AgentTableView extends TableSection<AgentNodeDatasource> implements HasViewName { +public class AgentTableView extends TableSection<AgentDatasource> implements HasViewName {
public static final ViewName VIEW_ID = new ViewName("Agents(GWT)", MSG.view_adminTopology_agents() + "(GWT)", IconEnum.AGENT); @@ -56,13 +55,16 @@ public class AgentTableView extends TableSection<AgentNodeDatasource> implements + AdministrationView.SECTION_TOPOLOGY_VIEW_ID + "/" + VIEW_ID;
private final boolean isAffinityGroupId; + + private final Integer id;
public AgentTableView(String locatorId, Integer id, boolean isAffinityGroupId) { super(locatorId, null); this.isAffinityGroupId = isAffinityGroupId; + this.id = id; setHeight100(); setWidth100(); - setDataSource(new AgentNodeDatasource(id, isAffinityGroupId)); + setDataSource(new AgentDatasource(id, isAffinityGroupId)); }
@Override @@ -118,15 +120,18 @@ public class AgentTableView extends TableSection<AgentNodeDatasource> implements }); } } - - if (isAffinityGroupId) - addTableAction(extendLocatorId("editGroupAgents"), MSG.view_groupInventoryMembers_button_updateMembership(), - new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, Permission.MANAGE_SETTINGS) { - public void executeAction(final ListGridRecord[] selections, Object actionValue) { - SC.say("working.."); - // todo: open editor for agent members - } - }); + if (isAffinityGroupId) { + showUpdateMembersAction(); + } + } + + private void showUpdateMembersAction() { + addTableAction(extendLocatorId("editGroupAgents"), MSG.view_groupInventoryMembers_button_updateMembership(), + new AuthorizedTableAction(this, TableActionEnablement.ALWAYS, Permission.MANAGE_SETTINGS) { + public void executeAction(final ListGridRecord[] selections, Object actionValue) { + AffinityGroupAgentsSelector.show(id, AgentTableView.this); + } + }); }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java index 0f76f74..2d1a75e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java @@ -135,10 +135,8 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve
if(fetchMembers) { criteria.addFilterAffinityGroupId(affinityGroupId); - GWTServiceLookup.getCloudService().findServersByCriteria(criteria, callback); - } else { - GWTServiceLookup.getCloudService().getServerNonMembersByAffinityGroupId(affinityGroupId, pc, callback); } + GWTServiceLookup.getCloudService().findServersByCriteria(criteria, callback); }
/** @@ -195,7 +193,7 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Serve @Override protected ServerCriteria getFetchCriteria(DSRequest request) { ServerCriteria criteria = new ServerCriteria(); - printRequestCriteria(request); +// printRequestCriteria(request); criteria.addFilterId(getFilter(request, FIELD_ID.propertyName(), Integer.class)); criteria.addFilterName(getFilter(request, FIELD_NAME.propertyName(), String.class)); criteria.addFilterAddress(getFilter(request, FILTER_ADDRESS, String.class)); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java index 7165390..f3dbd4d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDetailView.java @@ -19,7 +19,7 @@
package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_ADDRESS; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_CTIME; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_MTIME; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java index 79be297..3c08618 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java @@ -18,8 +18,8 @@ */ package org.rhq.enterprise.gui.coregui.client.admin.topology;
-import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP; -import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentNodeDatasourceField.FIELD_AFFINITY_GROUP_ID; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP; +import static org.rhq.enterprise.gui.coregui.client.admin.topology.AgentDatasourceField.FIELD_AFFINITY_GROUP_ID; import static org.rhq.enterprise.gui.coregui.client.admin.topology.ServerDatasourceField.FIELD_ORDINAL;
import java.io.Serializable; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java index bd9e88b..f51b246 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java @@ -296,7 +296,7 @@ public class CloudManagerBean implements CloudManagerLocal { partitionEventManager.processRequestedPartitionEvents(); }
- @RequiredPermission(Permission.MANAGE_INVENTORY) + @RequiredPermission(Permission.MANAGE_SETTINGS) public PageList<Server> findServersByCriteria(Subject subject, ServerCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); CriteriaQueryRunner<Server> runner = new CriteriaQueryRunner<Server>(criteria, generator, entityManager);
commit 9c52b1e5e5e75f65acad0fcd250da92914d7435c Author: Jirka Kremser jkremser@redhat.com Date: Tue Dec 18 17:10:43 2012 +0100
AgentCriteria and Agent finder have been added
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AgentCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AgentCriteria.java new file mode 100644 index 0000000..b18b5d6 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/AgentCriteria.java @@ -0,0 +1,107 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.core.domain.criteria; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +import org.rhq.core.domain.cloud.Server; +import org.rhq.core.domain.resource.Agent; +import org.rhq.core.domain.util.PageOrdering; + +/** + * Criteria object for querying {@link Server}s. + * + * @author Jiri Kremser + */ +@XmlAccessorType(XmlAccessType.FIELD) +@SuppressWarnings("unused") +public class AgentCriteria extends Criteria { + + private static final long serialVersionUID = 1L; + + public static final String SORT_FIELD_CTIME = "ctime"; + + public static final String SORT_FIELD_NAME = "name"; + + private Integer filterId; + private String filterName; + private String filterAddress; + private Integer filterPort; + private Integer filterServerId; // requires override + private Integer filterAffinityGroupId; // requires override + + private boolean fetchServer; + private boolean fetchAffinityGroup; + + private PageOrdering sortCtime; + private PageOrdering sortName; + + public AgentCriteria() { + filterOverrides.put("serverId", "server.id = ?"); + filterOverrides.put("affinityGroupId", "affinityGroup.id = ?"); + } + + public Class<?> getPersistentClass() { + return Agent.class; + } + + public void addFilterId(Integer filterId) { + this.filterId = filterId; + } + + public void addFilterName(String filterName) { + this.filterName = filterName; + } + + public void addFilterAffinityGroupId(Integer filterAffinityGroupId) { + this.filterAffinityGroupId = filterAffinityGroupId; + } + + public void addFilterAddress(String filterAddress) { + this.filterAddress = filterAddress; + } + + public void addFilterPort(Integer filterPort) { + this.filterPort = filterPort; + } + + public void addFilterServerId(Integer filterServerId) { + this.filterServerId = filterServerId; + } + + public void fetchAffinityGroup(boolean fetchAffinityGroup) { + this.fetchAffinityGroup = fetchAffinityGroup; + } + + public void fetchServer(boolean fetchServer) { + this.fetchServer = fetchServer; + } + + public void addSortCtime(PageOrdering sort) { + addSortField(SORT_FIELD_CTIME); + this.sortCtime = sort; + } + + public void addSortName(PageOrdering sort) { + addSortField(SORT_FIELD_NAME); + this.sortName = sort; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java index 3e64318..df83ba8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java @@ -33,6 +33,7 @@ import org.rhq.core.domain.cloud.PartitionEventDetails; import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.composite.AffinityGroupCountComposite; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; +import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.criteria.PartitionEventCriteria; import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; @@ -58,47 +59,54 @@ public interface CloudGWTService extends RemoteService { void deleteServers(int[] serverIds) throws RuntimeException;
void updateServerMode(int[] serverIds, Server.OperationMode mode) throws RuntimeException; - + void updateServer(Server server) throws RuntimeException;
List<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc) throws RuntimeException;;
PageList<PartitionEvent> findPartitionEventsByCriteria(PartitionEventCriteria criteria) throws RuntimeException; - + PageList<Server> findServersByCriteria(ServerCriteria criteria) throws RuntimeException;
+ PageList<Agent> findAgentsByCriteria(AgentCriteria criteria) throws RuntimeException; + void cloudPartitionEventRequest() throws RuntimeException;
void purgeAllEvents() throws RuntimeException;
void deletePartitionEvents(int[] eventIds) throws RuntimeException;
- PageList<PartitionEventDetails> getPartitionEventDetails(int partitionEventId, - PageControl pageControl) throws RuntimeException; - - PageList<AffinityGroupCountComposite> getAffinityGroupCountComposites(PageControl pageControl) throws RuntimeException; - + PageList<PartitionEventDetails> getPartitionEventDetails(int partitionEventId, PageControl pageControl) + throws RuntimeException; + + PageList<AffinityGroupCountComposite> getAffinityGroupCountComposites(PageControl pageControl) + throws RuntimeException; + int deleteAffinityGroups(int[] affinityGroupIds) throws RuntimeException; - + int createAffinityGroup(AffinityGroup affinityGroup) throws RuntimeException; - + void updateAffinityGroup(AffinityGroup affinityGroup) throws RuntimeException; - - PageList<Server> getServerMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) throws RuntimeException; - - PageList<Server> getServerNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) throws RuntimeException; - - PageList<Agent> getAgentMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) throws RuntimeException; - - PageList<Agent> getAgentNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) throws RuntimeException; - + + PageList<Server> getServerMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) + throws RuntimeException; + + PageList<Server> getServerNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) + throws RuntimeException; + + PageList<Agent> getAgentMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) + throws RuntimeException; + + PageList<Agent> getAgentNonMembersByAffinityGroupId(int affinityGroupId, PageControl pageControl) + throws RuntimeException; + AffinityGroup getAffinityGroupById(int affinityGroupId) throws RuntimeException; - + void addServersToGroup(int affinityGroupId, Integer[] serverIds) throws RuntimeException; - + void removeServersFromGroup(Integer[] serverIds) throws RuntimeException; - + void addAgentsToGroup(int affinityGroupId, Integer[] agentIds) throws RuntimeException; - + void removeAgentsFromGroup(Integer[] agentIds) throws RuntimeException; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java index 1daa1df..db7ec3c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java @@ -36,6 +36,7 @@ import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.Server.OperationMode; import org.rhq.core.domain.cloud.composite.AffinityGroupCountComposite; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; +import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.criteria.PartitionEventCriteria; import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; @@ -46,6 +47,7 @@ import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.cloud.AffinityGroupManagerLocal; import org.rhq.enterprise.server.cloud.CloudManagerLocal; import org.rhq.enterprise.server.cloud.PartitionEventManagerLocal; +import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -56,6 +58,8 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud private static final long serialVersionUID = 1L;
private CloudManagerLocal cloudManager = LookupUtil.getCloudManager(); + + private AgentManagerLocal agentManager = LookupUtil.getAgentManager();
private PartitionEventManagerLocal partitionEventManager = LookupUtil.getPartitionEventManager();
@@ -143,6 +147,17 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud throw getExceptionToThrowToClient(t); } } + + @Override + public PageList<Agent> findAgentsByCriteria(AgentCriteria criteria) throws RuntimeException { + try { + return SerialUtility.prepare( + agentManager.findAgentsByCriteria(getSessionSubject(), criteria), + "CloudGWTServiceImpl.findAgentsByCriteria"); + } catch (Throwable t) { + throw getExceptionToThrowToClient(t); + } + }
@Override public void cloudPartitionEventRequest() throws RuntimeException { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java index 9cced72..42adb10 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java @@ -48,6 +48,7 @@ import org.rhq.core.clientapi.server.core.PingRequest; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.common.composite.SystemSetting; +import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.composite.AgentLastAvailabilityPingComposite; @@ -67,6 +68,8 @@ import org.rhq.enterprise.server.core.comm.ServerCommunicationsServiceMBean; import org.rhq.enterprise.server.core.comm.ServerCommunicationsServiceUtil; import org.rhq.enterprise.server.measurement.AvailabilityManagerLocal; import org.rhq.enterprise.server.system.SystemManagerLocal; +import org.rhq.enterprise.server.util.CriteriaQueryGenerator; +import org.rhq.enterprise.server.util.CriteriaQueryRunner; import org.rhq.enterprise.server.util.LookupUtil; import org.rhq.enterprise.server.util.concurrent.AvailabilityReportSerializer;
@@ -654,5 +657,12 @@ public class AgentManagerBean implements AgentManagerLocal {
return pingResults; } + + @RequiredPermission(Permission.MANAGE_SETTINGS) + public PageList<Agent> findAgentsByCriteria(Subject subject, AgentCriteria criteria) { + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); + CriteriaQueryRunner<Agent> runner = new CriteriaQueryRunner<Agent>(criteria, generator, entityManager); + return runner.execute(); + }
} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java index e09cfaa..5494e4d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerLocal.java @@ -30,6 +30,7 @@ import org.rhq.core.clientapi.server.core.AgentVersion; import org.rhq.core.clientapi.server.core.CoreServerService; import org.rhq.core.clientapi.server.core.PingRequest; import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.criteria.AgentCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; @@ -308,4 +309,6 @@ public interface AgentManagerLocal { * @return The updated request object. */ public PingRequest handlePingRequest(PingRequest request); + + PageList<Agent> findAgentsByCriteria(Subject subject, AgentCriteria criteria); } \ No newline at end of file
commit 6ad56994db007039324ad2d6462636546e4e1ce1 Author: Jirka Kremser jkremser@redhat.com Date: Fri Dec 14 19:35:46 2012 +0100
ServerCriteria and Server finder have been added
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ServerCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ServerCriteria.java new file mode 100644 index 0000000..b00b3d7 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ServerCriteria.java @@ -0,0 +1,125 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.core.domain.criteria; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +import org.rhq.core.domain.cloud.Server; +import org.rhq.core.domain.cloud.Server.OperationMode; +import org.rhq.core.domain.util.PageOrdering; + +/** + * Criteria object for querying {@link Server}s. + * + * @author Jiri Kremser + */ +@XmlAccessorType(XmlAccessType.FIELD) +@SuppressWarnings("unused") +public class ServerCriteria extends Criteria { + + private static final long serialVersionUID = 1L; + + public static final String SORT_FIELD_CTIME = "ctime"; + + public static final String SORT_FIELD_NAME = "name"; + + public static final String SORT_FIELD_COMPUTE_POWER = "computePower"; + + private Integer filterId; + private String filterName; + private String filterAddress; + private Integer filterPort; + private Integer filterSecurePort; + private OperationMode filterOperationMode; // requires override + private Integer filterComputePower; + private Integer filterAffinityGroupId; // requires override + + private boolean fetchAgents; + private boolean fetchAffinityGroup; + + private PageOrdering sortCtime; + private PageOrdering sortName; + private PageOrdering sortComputePower; + + public ServerCriteria() { + // filterOverrides.put("operationMode", "operationMode IN ( ? )"); + filterOverrides.put("affinityGroupId", "affinityGroup.id = ?"); + } + + public Class<?> getPersistentClass() { + return Server.class; + } + + public void addFilterId(Integer filterId) { + this.filterId = filterId; + } + + public void addFilterName(String filterName) { + this.filterName = filterName; + } + + public void addFilterAddress(String filterAddress) { + this.filterAddress = filterAddress; + } + + public void addFilterPort(Integer filterPort) { + this.filterPort = filterPort; + } + + public void addFilterSecurePort(Integer filterSecurePort) { + this.filterSecurePort = filterSecurePort; + } + + public void addFilterOperationMode(OperationMode operationMode) { + this.filterOperationMode = operationMode; + } + + public void addFilterComputePower(Integer filterComputePower) { + this.filterComputePower = filterComputePower; + } + + public void addFilterAffinityGroupId(Integer filterAffinityGroupId) { + this.filterAffinityGroupId = filterAffinityGroupId; + } + + public void fetchAgents(boolean fetchAgents) { + this.fetchAgents = fetchAgents; + } + + public void fetchAffinityGroup(boolean fetchAffinityGroup) { + this.fetchAffinityGroup = fetchAffinityGroup; + } + + public void addSortCtime(PageOrdering sort) { + addSortField(SORT_FIELD_CTIME); + this.sortCtime = sort; + } + + public void addSortName(PageOrdering sort) { + addSortField(SORT_FIELD_NAME); + this.sortName = sort; + } + + public void addSortComputePower(PageOrdering sortComputePower) { + addSortField(SORT_FIELD_COMPUTE_POWER); + this.sortComputePower = sortComputePower; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java index a1f5507..f104d6c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/AffinityGroupServersSelector.java @@ -42,6 +42,7 @@ import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.cloud.Server; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; @@ -53,13 +54,13 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; /** * @author Jirka Kremser */ -public class AffinityGroupServersSelector extends AbstractSelector<Server, org.rhq.core.domain.criteria.Criteria> { +public class AffinityGroupServersSelector extends AbstractSelector<Server, ServerCriteria> {
private static final String ITEM_ICON = "types/Server_up_16.png";
private final Integer affinityGroupId;
- private static RPCDataSource<Server, org.rhq.core.domain.criteria.Criteria> datasource = null; + private static RPCDataSource<Server, ServerCriteria> datasource = null;
private static Window modalWindow; private static boolean shouldBeClosed; @@ -98,7 +99,7 @@ public class AffinityGroupServersSelector extends AbstractSelector<Server, org.r }
@Override - protected RPCDataSource<Server, org.rhq.core.domain.criteria.Criteria> getDataSource() { + protected RPCDataSource<Server, ServerCriteria> getDataSource() { if (datasource == null) { datasource = new ServerDatasource(affinityGroupId, false); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java index 4a07853..f77a843 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/PartitionEventDatasource.java @@ -158,6 +158,9 @@ public class PartitionEventDatasource extends RPCDataSource<PartitionEvent, Part
@Override protected PartitionEventCriteria getFetchCriteria(DSRequest request) { + //todo: do it like in ResourceDatasource.class + + ExecutionStatus[] statuses = getArrayFilter(request, FILTER_EXECUTION_STATUS, ExecutionStatus.class); PartitionEventType[] types = getArrayFilter(request, FILTER_EVENT_TYPE, PartitionEventType.class); if (types == null || types.length == 0 || statuses == null || statuses.length == 0) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java index d942c44..0f76f74 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerDatasource.java @@ -42,18 +42,28 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.cloud.Server; -import org.rhq.core.domain.criteria.Criteria; +import org.rhq.core.domain.cloud.Server.OperationMode; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.Log;
/** * @author Jirka Kremser * */ -public class ServerDatasource extends AbstractServerNodeDatasource<Server, Criteria> { +public class ServerDatasource extends AbstractServerNodeDatasource<Server, ServerCriteria> { + + // filters + public static final String FILTER_ADDRESS = FIELD_ADDRESS.propertyName(); + public static final String FILTER_PORT = FIELD_PORT.propertyName(); + public static final String FILTER_SECURE_PORT = FIELD_SECURE_PORT.propertyName(); + public static final String FILTER_OPERATION_MODE = FIELD_OPERATION_MODE.propertyName(); + public static final String FILTER_COMPUTE_POWER = "computePower"; + public static final String FILTER_AFFINITY_GROUP_ID = "affinityGroupId";
private final Integer affinityGroupId;
@@ -103,7 +113,7 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Crite }
@Override - protected void executeFetch(final DSRequest request, final DSResponse response, Criteria criteria) { + protected void executeFetch(final DSRequest request, final DSResponse response, ServerCriteria criteria) { if (affinityGroupId == null) { return; } @@ -122,8 +132,10 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Crite processResponse(request.getRequestId(), response); } }; + if(fetchMembers) { - GWTServiceLookup.getCloudService().getServerMembersByAffinityGroupId(affinityGroupId, pc, callback); + criteria.addFilterAffinityGroupId(affinityGroupId); + GWTServiceLookup.getCloudService().findServersByCriteria(criteria, callback); } else { GWTServiceLookup.getCloudService().getServerNonMembersByAffinityGroupId(affinityGroupId, pc, callback); } @@ -181,8 +193,22 @@ public class ServerDatasource extends AbstractServerNodeDatasource<Server, Crite }
@Override - protected Criteria getFetchCriteria(DSRequest request) { - // we don't use criteria for this datasource, just return null - return null; + protected ServerCriteria getFetchCriteria(DSRequest request) { + ServerCriteria criteria = new ServerCriteria(); + printRequestCriteria(request); + criteria.addFilterId(getFilter(request, FIELD_ID.propertyName(), Integer.class)); + criteria.addFilterName(getFilter(request, FIELD_NAME.propertyName(), String.class)); + criteria.addFilterAddress(getFilter(request, FILTER_ADDRESS, String.class)); + criteria.addFilterPort(getFilter(request, FILTER_PORT, Integer.class)); + criteria.addFilterSecurePort(getFilter(request, FILTER_SECURE_PORT, Integer.class)); + criteria.addFilterOperationMode(getFilter(request, FILTER_OPERATION_MODE, OperationMode.class)); + criteria.addFilterComputePower(getFilter(request, FILTER_COMPUTE_POWER, Integer.class)); + criteria.addFilterAffinityGroupId(getFilter(request, FILTER_AFFINITY_GROUP_ID, Integer.class)); + + //@todo: Remove me when finished debugging search expression + Log.debug(" *** ServerCriteria Search String: " + getFilter(request, "search", String.class)); + criteria.setSearchExpression(getFilter(request, "search", String.class)); + + return criteria; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java index 24e2d9c..79be297 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/ServerTableView.java @@ -38,7 +38,7 @@ import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.cloud.Server; -import org.rhq.core.domain.criteria.Criteria; +import org.rhq.core.domain.criteria.BaseCriteria; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.IconEnum; import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; @@ -56,7 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Jirka Kremser * */ -public class ServerTableView extends TableSection<AbstractServerNodeDatasource<? extends Serializable, Criteria>> +public class ServerTableView extends TableSection<AbstractServerNodeDatasource<? extends Serializable, ? extends BaseCriteria>> implements HasViewName {
public static final ViewName VIEW_ID = new ViewName("Servers(GWT)", MSG.view_adminTopology_servers() + "(GWT)", diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java index afaacb8..3e64318 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/CloudGWTService.java @@ -34,6 +34,7 @@ import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.composite.AffinityGroupCountComposite; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; import org.rhq.core.domain.criteria.PartitionEventCriteria; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; @@ -63,6 +64,8 @@ public interface CloudGWTService extends RemoteService { List<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc) throws RuntimeException;;
PageList<PartitionEvent> findPartitionEventsByCriteria(PartitionEventCriteria criteria) throws RuntimeException; + + PageList<Server> findServersByCriteria(ServerCriteria criteria) throws RuntimeException;
void cloudPartitionEventRequest() throws RuntimeException;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java index 32fadde..1daa1df 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/CloudGWTServiceImpl.java @@ -37,6 +37,7 @@ import org.rhq.core.domain.cloud.Server.OperationMode; import org.rhq.core.domain.cloud.composite.AffinityGroupCountComposite; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; import org.rhq.core.domain.criteria.PartitionEventCriteria; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; @@ -130,6 +131,18 @@ public class CloudGWTServiceImpl extends AbstractGWTServiceImpl implements Cloud throw getExceptionToThrowToClient(t); } } + + @Override + public PageList<Server> findServersByCriteria(ServerCriteria criteria) + throws RuntimeException { + try { + return SerialUtility.prepare( + cloudManager.findServersByCriteria(getSessionSubject(), criteria), + "CloudGWTServiceImpl.findServersByCriteria"); + } catch (Throwable t) { + throw getExceptionToThrowToClient(t); + } + }
@Override public void cloudPartitionEventRequest() throws RuntimeException { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java index 4bfc1af..bd9e88b 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java @@ -36,6 +36,7 @@ import org.rhq.core.domain.cloud.FailoverListDetails; import org.rhq.core.domain.cloud.PartitionEventType; import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.server.PersistenceUtility; import org.rhq.core.domain.util.PageControl; @@ -44,6 +45,8 @@ import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.authz.AuthorizationManagerLocal; import org.rhq.enterprise.server.authz.RequiredPermission; import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal; +import org.rhq.enterprise.server.util.CriteriaQueryGenerator; +import org.rhq.enterprise.server.util.CriteriaQueryRunner; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -292,4 +295,11 @@ public class CloudManagerBean implements CloudManagerLocal { // regardless of the number of pending requests, as the work would be duplicated. partitionEventManager.processRequestedPartitionEvents(); } + + @RequiredPermission(Permission.MANAGE_INVENTORY) + public PageList<Server> findServersByCriteria(Subject subject, ServerCriteria criteria) { + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); + CriteriaQueryRunner<Server> runner = new CriteriaQueryRunner<Server>(criteria, generator, entityManager); + return runner.execute(); + } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java index 212f835..92b59d3 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerLocal.java @@ -26,6 +26,7 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.cloud.FailoverListDetails; import org.rhq.core.domain.cloud.Server; import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; +import org.rhq.core.domain.criteria.ServerCriteria; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; @@ -89,4 +90,6 @@ public interface CloudManagerLocal { PageList<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc);
void markStaleServersDown(Subject subject); + + PageList<Server> findServersByCriteria(Subject subject, ServerCriteria criteria); }
commit 134d6f6984e69dc06b105a3024f30f947c8f498a Author: Jirka Kremser jkremser@redhat.com Date: Fri Dec 14 15:21:53 2012 +0100
Revert "exposing the CloudManagerBean via CLI"
This reverts commit 60c1d42fa5750ef5d1829e97b6b15323501bc3f2.
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManager.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManager.java index 151267f..d374324 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManager.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManager.java @@ -24,7 +24,6 @@ import org.rhq.enterprise.server.alert.AlertManagerRemote; import org.rhq.enterprise.server.auth.SubjectManagerRemote; import org.rhq.enterprise.server.authz.RoleManagerRemote; import org.rhq.enterprise.server.bundle.BundleManagerRemote; -import org.rhq.enterprise.server.cloud.CloudManagerRemote; import org.rhq.enterprise.server.configuration.ConfigurationManagerRemote; import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; @@ -64,7 +63,6 @@ public enum RhqManager { BundleManager(BundleManagerRemote.class, "${BundleManager}"), // CallTimeDataManager(CallTimeDataManagerRemote.class, "${CallTimeDataManager}"), // RepoManager(RepoManagerRemote.class, "${RepoManager}"), // - CloudManager(CloudManagerRemote.class, "${CloudManager}"), // ConfigurationManager(ConfigurationManagerRemote.class, "${ConfigurationManager}"), // ContentManager(ContentManagerRemote.class, "${ContentManager}"), // DataAccessManager(DataAccessManagerRemote.class, "${DataAccessManager}"), // diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java index 391b9e4..4bfc1af 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerBean.java @@ -54,7 +54,7 @@ import org.rhq.enterprise.server.util.LookupUtil; * @author Joseph Marques */ @Stateless -public class CloudManagerBean implements CloudManagerLocal, CloudManagerRemote { +public class CloudManagerBean implements CloudManagerLocal { private final Log log = LogFactory.getLog(CloudManagerBean.class);
// A time sufficient to determine whether a server is down. Can be based on the initial delay set for the server instance diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerRemote.java deleted file mode 100644 index 1f97b99..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/CloudManagerRemote.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.enterprise.server.cloud; - -import java.util.List; - -import javax.ejb.Remote; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.cloud.Server; -import org.rhq.core.domain.cloud.composite.ServerWithAgentCountComposite; -import org.rhq.core.domain.util.PageControl; -import org.rhq.core.domain.util.PageList; - -/** - * @author Jiri Kremser - */ -@Remote -public interface CloudManagerRemote { - -// void deleteServers(Integer[] serverIds) throws CloudManagerException; -// -// void deleteServer(Integer serverId) throws CloudManagerException; -// -// List<Agent> getAgentsByServerName(String serverName); -// -// Server getServerById(int serverId); -// -// Server getServerByName(String serverName); -// -// /** -// * Return every server registered in the database considered part of the active cloud. This will exclude, for example, -// * servers in INSTALLED mode or any other mode that should not be included when performing cloud operations such as partitioning. -// * @return All servers available to the cloud. -// */ -// List<Server> getAllCloudServers(); -// - /** - * Return every server registered in the database. - * @return All servers, regardless of operation mode. - */ - List<Server> getAllServers(); - - PageList<ServerWithAgentCountComposite> getServerComposites(Subject subject, PageControl pc); -// -// /** -// * Returns the number of servers that are part of the "server cloud", which excludes -// * servers that have been installed but not associated with the cloud. -// * The returned count will include those servers that are down or in maintenance mode, -// * in addition to those servers that are currently running in a normal state. -// * -// * @return count of servers in the cloud -// */ -// int getServerCount(); -// -// /** -// * Returns the number of servers that are part of the "server cloud" that are currently -// * running in "normal" mode. -// * -// * This excludes all other servers such as those servers that have been installed but -// * not associated with the cloud, servers that are down or in maintenance mode. -// * -// * @return count of servers in the cloud that are in a normal running state -// */ -// int getNormalServerCount(); -// -// void updateServerMode(Integer[] serverIds, Server.OperationMode mode); -// -// Server updateServer(Subject subject, Server server); -// -// PageList<FailoverListDetails> getFailoverListDetailsByAgentId(int agentId, PageControl pc); -// -// void markStaleServersDown(Subject subject); -} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/RemoteAPIValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/RemoteAPIValidator.java index 453e0a5..fddc6c6 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/RemoteAPIValidator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/RemoteAPIValidator.java @@ -34,7 +34,6 @@ import org.rhq.enterprise.server.alert.AlertDefinitionManagerBean; import org.rhq.enterprise.server.alert.AlertManagerBean; import org.rhq.enterprise.server.auth.SubjectManagerBean; import org.rhq.enterprise.server.authz.RoleManagerBean; -import org.rhq.enterprise.server.cloud.CloudManagerBean; import org.rhq.enterprise.server.configuration.ConfigurationManagerBean; import org.rhq.enterprise.server.content.AdvisoryManagerBean; import org.rhq.enterprise.server.content.ContentManagerBean; @@ -69,7 +68,6 @@ public class RemoteAPIValidator { AvailabilityManagerBean.class,// CallTimeDataManagerBean.class, // RepoManagerBean.class,// - CloudManagerBean.class,// ConfigurationManagerBean.class, // ContentManagerBean.class, // //ContentSourceManagerBean.class, //
commit 756bac150c6f31e4dd5a60c9f519226fff7f28c1 Author: Jirka Kremser jkremser@redhat.com Date: Fri Dec 14 14:43:33 2012 +0100
adding comment
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java index edce33a..6dd2430 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/topology/FailoverListItemDatasource.java @@ -53,6 +53,8 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; public class FailoverListItemDatasource extends AbstractServerNodeDatasource<FailoverListDetails, Criteria> {
private final int agentId; + + // this delegate is there to not repeat the copyValues code private final ServerDatasource serverDatasource;
public FailoverListItemDatasource(int agentId) {
commit 2ecf112a35453de2ab40aa4c091aff039c73f26c Merge: 829bede e794a37 Author: Jirka Kremser jkremser@redhat.com Date: Fri Dec 14 13:30:23 2012 +0100
Merge branch 'master' into jkremser/ha-jsf-to-gwt-rewrite
commit e794a376e030ff34e237afcb9b4994768e489cd8 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Dec 13 17:27:45 2012 +0100
Fixed the ExportingInputStream to correctly define the XML namespaces (and thus work under woodstox, which is the XML streaming provider in AS7). Re-enabled the SynchronizationManagerBeanTest.
diff --git a/modules/enterprise/server/itests-2/pom.xml b/modules/enterprise/server/itests-2/pom.xml index f58396a..01b377f 100644 --- a/modules/enterprise/server/itests-2/pom.xml +++ b/modules/enterprise/server/itests-2/pom.xml @@ -656,7 +656,6 @@ <excludes> <!-- NOTE: PERF GROUP AND SOME CLASSES EXCLUDED (SEE BZ 874696) --> <exclude>**/LdapGroupManagerBeanTest.java</exclude> - <exclude>**/SynchronizationManagerBeanTest.java</exclude> <exclude>org/rhq/**/performance/**/*.java</exclude>
<!-- exclude the db tests which are not expected to run in this suite --> diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java index 19734f6..eae8d7d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java @@ -34,7 +34,6 @@ import java.util.zip.GZIPOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; -import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -238,19 +237,15 @@ public class ExportingInputStream extends InputStream { */ private void exportPrologue(XMLStreamWriter wrt) throws XMLStreamException { wrt.setDefaultNamespace(SynchronizationConstants.EXPORT_NAMESPACE); - wrt.setPrefix(SynchronizationConstants.EXPORT_NAMESPACE_PREFIX, SynchronizationConstants.EXPORT_NAMESPACE); - wrt.setPrefix(SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE_PREFIX, SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE); - wrt.setPrefix(SynchronizationConstants.CONFIGURATION_NAMESPACE_PREFIX, SynchronizationConstants.CONFIGURATION_NAMESPACE); - - NamespaceContext nsContext = SynchronizationConstants.createConfigurationExportNamespaceContext(); - - wrt.setNamespaceContext(nsContext);
wrt.writeStartDocument(); wrt.writeStartElement(SynchronizationConstants.EXPORT_NAMESPACE, SynchronizationConstants.CONFIGURATION_EXPORT_ELEMENT); - wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE_PREFIX, ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE); - wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_NAMESPACE_PREFIX, SynchronizationConstants.CONFIGURATION_NAMESPACE);
+ wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_INSTANCE_NAMESPACE_PREFIX, + ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE); + wrt.writeNamespace(SynchronizationConstants.CONFIGURATION_NAMESPACE_PREFIX, + SynchronizationConstants.CONFIGURATION_NAMESPACE); + writeValidators(wrt); }
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java index 6d56969..db6393e 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java @@ -28,6 +28,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; +import java.nio.charset.Charset; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -36,9 +38,19 @@ import java.util.List; import java.util.Set;
import javax.persistence.EntityManager; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -56,12 +68,14 @@ import org.rhq.core.domain.sync.ExporterMessages; import org.rhq.enterprise.server.sync.ExportReader; import org.rhq.enterprise.server.sync.ExportWriter; import org.rhq.enterprise.server.sync.ExportingInputStream; +import org.rhq.enterprise.server.sync.ImportException; import org.rhq.enterprise.server.sync.NoSingleEntity; import org.rhq.enterprise.server.sync.SynchronizationConstants; import org.rhq.enterprise.server.sync.Synchronizer; import org.rhq.enterprise.server.sync.exporters.AbstractDelegatingExportingIterator; import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.ExportingIterator; +import org.rhq.enterprise.server.sync.exporters.JAXBExportingIterator; import org.rhq.enterprise.server.sync.importers.ExportedEntityMatcher; import org.rhq.enterprise.server.sync.importers.Importer; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; @@ -90,7 +104,9 @@ public class ExportingInputStreamTest extends JMockTest { }
public void export(ExportWriter output) throws XMLStreamException { - output.writeCData(getCurrent().toString()); + output.writeStartElement("datum"); + output.writeCharacters(getCurrent().toString()); + output.writeEndElement(); }
public String getNotes() { @@ -191,6 +207,140 @@ public class ExportingInputStreamTest extends JMockTest { } }
+ public static class Entity { + public int value; + + public Entity(int value) { + this.value = value; + } + } + + @XmlRootElement(name = "exported-entity") + @XmlAccessorType(XmlAccessType.FIELD) + public static class ExportedEntity { + + @XmlAttribute + public int property; + } + + public static class JAXBExporter implements Exporter<Entity, ExportedEntity> { + + private static class JAXBIterator extends JAXBExportingIterator<ExportedEntity, Entity> { + + public JAXBIterator(java.util.Iterator<Entity> sourceIterator) { + super(sourceIterator, ExportedEntity.class); + } + + @Override + protected ExportedEntity convert(Entity object) { + ExportedEntity ret = new ExportedEntity(); + ret.property = object.value; + + return ret; + } + + @Override + public String getNotes() { + return null; + } + } + + @Override + public ExportingIterator<ExportedEntity> getExportingIterator() { + List<Entity> data = new ArrayList<Entity>(); + for(int i = 0; i < 4; ++i) { + data.add(new Entity(i)); + } + + return new JAXBIterator(data.iterator()); + } + + @Override + public String getNotes() { + return null; + } + + } + + public static class JAXBImporter implements Importer<Entity, ExportedEntity> { + + private Unmarshaller unmarshaller; + { + try { + JAXBContext context = JAXBContext.newInstance(ExportedEntity.class); + unmarshaller = context.createUnmarshaller(); + } catch (JAXBException e) { + throw new IllegalStateException(e); + } + } + + @Override + public ConfigurationDefinition getImportConfigurationDefinition() { + return null; + } + + @Override + public void configure(Configuration importConfiguration) { + } + + @Override + public ExportedEntityMatcher<Entity, ExportedEntity> getExportedEntityMatcher() { + return new ExportedEntityMatcher<Entity, ExportedEntity>() { + @Override + public Entity findMatch(ExportedEntity object) { + return new Entity(object.property); + } + }; + } + + @Override + public Set<EntityValidator<ExportedEntity>> getEntityValidators() { + return Collections.emptySet(); + } + + @Override + public void update(Entity entity, ExportedEntity exportedEntity) throws Exception { + entity.value = exportedEntity.property; + } + + @Override + public ExportedEntity unmarshallExportedEntity(ExportReader reader) throws XMLStreamException { + try { + return (ExportedEntity) unmarshaller.unmarshal(reader); + } catch (JAXBException e) { + throw new XMLStreamException(e); + } + } + + @Override + public String finishImport() throws Exception { + return null; + } + + } + + public static class JAXBSynchronizer implements Synchronizer<Entity, ExportedEntity> { + + @Override + public void initialize(Subject subject, EntityManager entityManager) { + } + + @Override + public Exporter<Entity, ExportedEntity> getExporter() { + return new JAXBExporter(); + } + + @Override + public Importer<Entity, ExportedEntity> getImporter() { + return new JAXBImporter(); + } + + @Override + public Set<ConsistencyValidator> getRequiredValidators() { + return Collections.emptySet(); + } + + }
public void testSucessfulExport() throws Exception { List<String> list1 = Arrays.asList("a", "b", "c"); @@ -203,11 +353,11 @@ public class ExportingInputStreamTest extends JMockTest {
InputStream export = new ExportingInputStream(exporters, new HashMap<String, ExporterMessages>(), 1024, false);
-// String exportContents = readAll(new InputStreamReader(export, "UTF-8")); -// -// LOG.info("Export contents:\n" + exportContents); -// -// export = new ByteArrayInputStream(exportContents.getBytes("UTF-8")); + String exportContents = readAll(new InputStreamReader(export, "UTF-8")); + + LOG.info("Export contents:\n" + exportContents); + + export = new ByteArrayInputStream(exportContents.getBytes("UTF-8"));
DocumentBuilder bld = DocumentBuilderFactory.newInstance().newDocumentBuilder();
@@ -264,16 +414,108 @@ public class ExportingInputStreamTest extends JMockTest { Node data = getDirectChildByTagName(entityElement, SynchronizationConstants.DATA_ELEMENT); assertNotNull(data, "Could not find data element in the entity.");
- String dataText = ((Element)data).getTextContent(); + Node datum = getDirectChildByTagName(data, "datum"); + assertNotNull(datum, "Could not find the exported datum element containing the actual data."); + + String datumText = ((Element) datum).getTextContent(); notesText = ((Element)note).getTextContent();
- assertEquals(notesText, ListToStringExporter.NOTE_PREFIX + dataText, "Unexpected discrepancy between data and notes in the export."); + assertEquals(notesText, ListToStringExporter.NOTE_PREFIX + datumText, + "Unexpected discrepancy between data and notes in the export."); }
++elementIndex; } }
+ @Test + public void testJAXBHandled() throws Exception { + JAXBSynchronizer sync = new JAXBSynchronizer(); + + Set<Synchronizer<?, ?>>syncs = this.<Synchronizer<?, ?>> asSet(sync); + + InputStream export = new ExportingInputStream(syncs, new HashMap<String, ExporterMessages>(), 1024, false); + + String exportContents = readAll(new InputStreamReader(export, "UTF-8")); + + XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader( + new ByteArrayInputStream(exportContents.getBytes(Charset.forName("UTF-8")))); + + try { + while (rdr.hasNext()) { + switch (rdr.next()) { + case XMLStreamReader.START_ELEMENT: + String tagName = rdr.getName().getLocalPart(); + if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) { + try { + importSingle(rdr); + } catch (Exception e) { + //fail fast on the import errors... This runs in a single transaction + //so all imports done so far will get rolled-back. + //(Even if we change our minds later and run a transaction per importer + //we should fail fast to prevent further damage due to possible + //constraint violations in the db, etc.) + throw new ImportException("Import failed.", e); + } + } + break; + } + } + } finally { + rdr.close(); + } + } + + private <E, X> void importSingle(XMLStreamReader rdr) + throws Exception { + String synchronizerClassName = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE); + + @SuppressWarnings("unchecked") + Synchronizer<E, X> synchronizer = instantiate(synchronizerClassName, Synchronizer.class, + "The synchronizer denoted in the export file ('%s') does not implement the importer interface. This should not happen."); + + Importer<E, X> importer = synchronizer.getImporter(); + + ExportedEntityMatcher<E, X> matcher = importer.getExportedEntityMatcher(); + + //the passed in configuration has precedence over the default one inlined in + //the config file. + while (rdr.hasNext()) { + boolean bailout = false; + switch (rdr.next()) { + case XMLStreamConstants.START_ELEMENT: + if (SynchronizationConstants.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) { + + rdr.nextTag(); + X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr)); + E entity = matcher == null ? null : matcher.findMatch(exportedEntity); + importer.update(entity, exportedEntity); + } + break; + case XMLStreamConstants.END_ELEMENT: + if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(rdr.getName().getLocalPart())) { + bailout = true; + } + } + + if (bailout) { + break; + } + } + } + + private <T> T instantiate(String className, Class<T> desiredClass, String notAssignableErrorMessage) + throws InstantiationException, IllegalAccessException, ClassNotFoundException { + Class<?> cls = Class.forName(className); + if (!desiredClass.isAssignableFrom(cls)) { + throw new IllegalStateException(String.format(notAssignableErrorMessage, className, desiredClass.getName())); + } + + Object instance = cls.newInstance(); + + return desiredClass.cast(instance); + } + @Test(expectedExceptions = IOException.class) public void testExceptionHandling_Exporter_getExportingIterator() throws Exception { final Exporter<?, ?> failingExporter = context.mock(Exporter.class); @@ -452,7 +694,7 @@ public class ExportingInputStreamTest extends JMockTest { return n; } } - + return null; } }
commit b62fb191a178d06fe48b47b2508fd4cb0aa039ca Author: Lukas Krejci lkrejci@redhat.com Date: Thu Dec 13 16:15:00 2012 +0100
Modified the access checking JNDI lookup wrappers to take into account the slightly different behavior needed when there was originally no initial context factory builder or if there originally was some.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java index 9681014..52addaa 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java @@ -32,6 +32,7 @@ import java.util.EnumMap; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; +import java.util.List; import java.util.Set;
import javax.naming.Context; @@ -138,7 +139,7 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex }
private enum FactoryType { - ACCESS_CHECKING { + ACCESS_CHECKING_URL_PREFERRING {
@Override public InitialContextFactory wrap(InitialContextFactory factory) { @@ -158,15 +159,34 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex
return new DecoratingInitialContextFactory(factory, pickers); } + }, + ACCESS_CHECKING { + + @Override + public InitialContextFactory wrap(InitialContextFactory factory) { + ArrayList<DecoratorPicker<Context, ContextDecorator>> pickers = new ArrayList<DecoratorPicker<Context, ContextDecorator>>(); + pickers.add(getAccessCheckingDecoratorPicker()); + + return new DecoratingInitialContextFactory(factory, pickers); + } + }, + PASS_THROUGH { + + @Override + public InitialContextFactory wrap(InitialContextFactory factory) { + List<DecoratorPicker<Context, ContextDecorator>> pickers = Collections.emptyList(); + + return new DecoratingInitialContextFactory(factory, pickers); + } };
public abstract InitialContextFactory wrap(InitialContextFactory factory);
- public static FactoryType detect(Hashtable<?, ?> environment) { + public static FactoryType detect(Hashtable<?, ?> environment, boolean pretendNoFactoryBuilder) { String providerUrl = (String) environment.get(Context.PROVIDER_URL);
if (providerUrl == null) { - return ACCESS_CHECKING; + return pretendNoFactoryBuilder ? ACCESS_CHECKING_URL_PREFERRING : ACCESS_CHECKING; } else { try { URI uri = new URI(providerUrl); @@ -175,9 +195,9 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex //check if we are accessing the RHQ server through some remoting //interface. if (uri.getPort() == JNP_PORT && SERVER_BIND_IPS.contains(providerHost)) { - return ACCESS_CHECKING; + return pretendNoFactoryBuilder ? ACCESS_CHECKING_URL_PREFERRING : ACCESS_CHECKING; } else { - return URL_PREFERRING; + return pretendNoFactoryBuilder ? URL_PREFERRING : PASS_THROUGH; } } catch (URISyntaxException e) { if (LOG.isDebugEnabled()) { @@ -185,7 +205,7 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex + Context.PROVIDER_URL + " is not a valid URI. Falling back to using the access checking wrapper.", e); } - return ACCESS_CHECKING; + return pretendNoFactoryBuilder ? ACCESS_CHECKING_URL_PREFERRING : ACCESS_CHECKING; } catch (UnknownHostException e) { //let the factory deal with the unknown host... //this most probably shouldn't be secured because localhost addresses @@ -195,7 +215,7 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex + Context.PROVIDER_URL + " is not resolvable. Falling back to using the URL preferring wrapper.", e); } - return URL_PREFERRING; + return pretendNoFactoryBuilder ? URL_PREFERRING : PASS_THROUGH; } } } @@ -219,15 +239,19 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex FactoryType.class);
private final String defaultFactoryClassName; - + private final boolean pretendNoFactoryBuilder; + /** * @param defaultFactory the default factory to use if none can be deduced from the environment. If null, an attempt * is made to obtain the default InitialContextFactory of JBoss AS (which may fail depending on the classloading * "situation"). + * @param pretendNoFactoryBuilder true if the naming contexts should pretend as if there was no initial context + * factory builder installed. This is to support environments as AS4, where there really was no builder initially + * and the lookup relied on that fact. * * @throws NamingException */ - public AccessCheckingInitialContextFactoryBuilder(InitialContextFactory defaultFactory) throws NamingException { + public AccessCheckingInitialContextFactoryBuilder(InitialContextFactory defaultFactory, final boolean pretendNoFactoryBuilder) throws NamingException { if (defaultFactory == null) { defaultFactory = getJbossDefaultInitialContextFactory(); } @@ -237,21 +261,22 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex for (FactoryType ft : FactoryType.values()) { typeDefaults.put(ft, ft.wrap(defaultFactory)); } + + this.pretendNoFactoryBuilder = pretendNoFactoryBuilder; + + this.defaultFactory = new InitialContextFactory() { + public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { + return typeDefaults.get(FactoryType.detect(environment, pretendNoFactoryBuilder)).getInitialContext( + environment); + } + }; }
/** * This is the default initial context factory that is returned when no other is * configured using the environment variables. - * <p> - * It uses {@link NamingContextFactory} as the underlying mechanism - the same - * as the default configuration in JBoss 4. */ - private final InitialContextFactory defaultFactory = new InitialContextFactory() { - public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { - return typeDefaults.get(FactoryType.detect(environment)).getInitialContext( - environment); - } - }; + private final InitialContextFactory defaultFactory;
/** * Create a InitialContext factory. If the environment does not override the factory class it will use the @@ -273,7 +298,7 @@ public class AccessCheckingInitialContextFactoryBuilder implements InitialContex try { final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader); InitialContextFactory configuredFactory = (InitialContextFactory) factoryClass.newInstance(); - return FactoryType.detect(environment).wrap(configuredFactory); + return FactoryType.detect(environment, pretendNoFactoryBuilder).wrap(configuredFactory); } catch (Exception e) { NamingException ne = new NamingException("Failed instantiate InitialContextFactory " + factoryClassName diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java index f21322f..a4173ca 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java @@ -79,7 +79,7 @@ public class NamingHack { }
NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder( - defaultFactory)); + defaultFactory, originalBuilder == null)); } catch (Exception e) { LOG.error("Failed to install a custom initial context factory builder. RHQ installation is unsecure!", e); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java index c92cc42..a5daa9f 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java @@ -106,7 +106,7 @@ public class DecoratingInvocationHandlerTest { @BeforeClass public void setBuilder() throws Exception { NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder( - new org.jboss.as.naming.InitialContextFactory())); + new org.jboss.as.naming.InitialContextFactory(), false)); }
public void testSimpleDispatch() throws Exception {
commit 3f1149427123c1bbafdb8596e87b776f84b59d54 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Dec 12 16:59:22 2012 +0100
Recovering from the merge of commit 2ce8b7aa063a56840090ed553f47b6e3a0ba7845. The SessionManager should do the security checks, we've got JNDI security working.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java index ccffd37..c2b8270 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java @@ -45,8 +45,7 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public final class SessionManager {
- // TODO JNDI - // private static final AllowRhqServerInternalsAccessPermission ACCESS_PERMISSION = new AllowRhqServerInternalsAccessPermission(); + private static final AllowRhqServerInternalsAccessPermission ACCESS_PERMISSION = new AllowRhqServerInternalsAccessPermission();
/** * Our source for random session IDs. @@ -278,8 +277,7 @@ public final class SessionManager { }
private static void checkPermission() { - // TODO JNDI - // SecurityManager sm = System.getSecurityManager(); - // if (sm != null) sm.checkPermission(ACCESS_PERMISSION); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) sm.checkPermission(ACCESS_PERMISSION); } } \ No newline at end of file
commit 2c9a8bd0e7b79dac706195f7a1a2474b1c39f631 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Dec 13 10:02:55 2012 -0500
Replace more instances of straight division with approach that maintains precision.
diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java index 8861378..e87bff2 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java @@ -203,7 +203,8 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { MeasurementAggregate actual = dataManager.getAggregate(overlord, dynamicSchedule.getId(), beginTime.getMillis(), endTime.getMillis());
- MeasurementAggregate expected = new MeasurementAggregate(1.1, (1.1 + 2.2 + 3.3 + 4.4 + 5.5 + 6.6) / 6, 6.6); + MeasurementAggregate expected = new MeasurementAggregate(1.1, divide((1.1 + 2.2 + 3.3 + 4.4 + 5.5 + 6.6), 6), + 6.6);
AssertUtils.assertPropertiesMatch(expected, actual, "Aggregate does not match"); } @@ -236,9 +237,9 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { assertEquals("Expected to get back 60 data points.", buckets.getNumDataPoints(), actualData.size());
MeasurementDataNumericHighLowComposite expectedBucket0Data = new MeasurementDataNumericHighLowComposite( - buckets.get(0), (2.0 + 5.0 + 3.0) / 3, 6.0, 1.0); + buckets.get(0), divide((2.0 + 5.0 + 3.0), 3), 6.0, 1.0); MeasurementDataNumericHighLowComposite expectedBucket59Data = new MeasurementDataNumericHighLowComposite( - buckets.get(59), (5.0 + 5.0 + 3.0) / 3, 9.0, 2.0); + buckets.get(59), divide((5.0 + 5.0 + 3.0), 3), 9.0, 2.0);
assertPropertiesMatch("The data for bucket 0 does not match the expected values.", expectedBucket0Data, actualData.get(0));
commit 64b887e487f4bc90677148778e3316b4e975c9fb Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Dec 13 09:41:48 2012 -0500
remove recovery plugin from postgres XA test datasource, not needed since the mem-leak issue is not relevant in a test run and the declaration of this workaround class is problematic.
diff --git a/modules/enterprise/server/itests-2/pom.xml b/modules/enterprise/server/itests-2/pom.xml index e1b466f..f58396a 100644 --- a/modules/enterprise/server/itests-2/pom.xml +++ b/modules/enterprise/server/itests-2/pom.xml @@ -520,9 +520,6 @@ <statement> <prepared-statement-cache-size>75</prepared-statement-cache-size> </statement> - <recovery no-recovery="false"> - <recover-plugin class-name="org.jboss.jca.core.recovery.ValidatingManagedConnectionFactoryRecoveryPlugin"/> - </recovery> </xa-datasource>]]></replacevalue> </replacefilter>
commit 866e7803407fe4fe18c6fdf54ca3344b70b02a25 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Dec 12 15:51:21 2012 -0500
installer work - remove debugging system.out.println - protect paths with quotes in rhq-installer.bat - reduce dev installer retry from 5 to 3 if the remote admin endpoint in AS isn't ready - not sure, this retry seems to do some wonky things on win
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java index 1b5b462..c3ceec2 100644 --- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java +++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java @@ -307,8 +307,6 @@ public class DatasourceJBossASClient extends JBossASClient { preparedStatementCacheSize, recoveryPluginClassName, securityDomain, staleConnectionCheckerClassName, transactionIsolation, validConnectionCheckerClassName);
- System.out.println("**** \n" + dmr); - Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, XA_DATA_SOURCE, name); final ModelNode request1 = ModelNode.fromString(dmr); request1.get(OPERATION).set(ADD); diff --git a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh index e7cadef..5369ab2 100755 --- a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh +++ b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh @@ -11,7 +11,7 @@ _INSTALLER_SCRIPT="${RHQ_SERVER_HOME}/bin/rhq-installer.sh" # we are normally executed just before the server starts, so give it time to initialize sleep 5
-_TRIES="1 2 3" +_TRIES="1 2" for _TRY in $_TRIES do echo Running Installer Now... diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java index c65001d..5c0316d 100644 --- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java +++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java @@ -522,13 +522,6 @@ public class ServerInstallUtil { props.put("PortNumber", "${rhq.server.database.port:5432}"); props.put("DatabaseName", "${rhq.server.database.db-name:rhq}");
- /* TODO: Use this version which defines the recovery plugin - xaDsRequest = client.createNewXADatasourceRequest(RHQ_DATASOURCE_NAME_XA, 30000, JDBC_DRIVER_POSTGRES, - "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, 5, 50, Boolean.FALSE, - (Boolean) null, 75, "org.jboss.jca.core.recovery.ValidatingManagedConnectionFactoryRecoveryPlugin", - RHQ_DS_SECURITY_DOMAIN, (String) null, "TRANSACTION_READ_COMMITTED", - "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker", props); - */ xaDsRequest = client.createNewXADatasourceRequest(RHQ_DATASOURCE_NAME_XA, 30000, JDBC_DRIVER_POSTGRES, "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, 5, 50, (Boolean) null, (Boolean) null, 75, (String) null, RHQ_DS_SECURITY_DOMAIN, (String) null, "TRANSACTION_READ_COMMITTED",
commit 2f61a838d951ef6746eb0f2989ec3cf5a24a8b75 Author: Simeon Pinder spinder@fulliautomatix.conchfritter.com Date: Wed Dec 12 14:47:54 2012 -0500
Update the zip and chmod processing filters for the agent to include all of the shared library file extensions.
diff --git a/modules/enterprise/agent/ant-run.xml b/modules/enterprise/agent/ant-run.xml index 4085efd..93ccd25 100644 --- a/modules/enterprise/agent/ant-run.xml +++ b/modules/enterprise/agent/ant-run.xml @@ -21,6 +21,7 @@ Ant Script that provides ways to package the Agent. <property name="jaxb-api.version" value="2.1"/> <property name="jaxb-impl.version" value="2.1"/> <property name="log4j.version" value="1.2.16"/> + <property name="so.exts" value="*.so.*"/>
<!-- ======================================================================= @@ -129,6 +130,7 @@ Ant Script that provides ways to package the Agent. <include name="**/lib/sigar.jar"/> <include name="**/lib/bcel*.jar"/> <include name="**/lib/*.so"/> + <include name="**/lib/${so.exts}"/> <include name="**/lib/*.sl"/> <include name="**/lib/*.dll"/> <include name="**/lib/*.dylib"/> @@ -139,21 +141,21 @@ Ant Script that provides ways to package the Agent. <fileset refid="augeas.native.fileset" /> <patternset> <include name="**/lib*/*.so"/> - <include name="**/lib*/*.so.1"/> + <include name="**/lib*/${so.exts}"/> </patternset> </unzip>
<move todir="${agent.distro.dir}/lib/augeas/lib" flatten="true" overwrite="false"> <fileset dir="${agent.distro.dir}/lib/augeas-native-${augeas.zip.version}/lib"> <include name="*.so" /> - <include name="*.so.1" /> + <include name="${so.exts}" /> </fileset> </move> <move todir="${agent.distro.dir}/lib/augeas/lib64" flatten="true" overwrite="false"> <fileset dir="${agent.distro.dir}/lib/augeas-native-${augeas.zip.version}/lib64"> <include name="*.so" /> - <include name="*.so.1" /> + <include name="${so.exts}" /> </fileset> </move> @@ -172,9 +174,9 @@ Ant Script that provides ways to package the Agent. <delete failonerror="false" includeEmptyDirs="true" verbose="true"> <fileset dir="${agent.distro.dir}/lib" includes="hyperic-sigar-*/"/> </delete> - <chmod dir="${agent.distro.dir}/lib" perm="ug+rx" includes="*.so,*.sl,*.dylib"/> - <chmod dir="${agent.distro.dir}/lib/augeas/lib" perm="ug+rx" includes="*.so,*.so.1"/> - <chmod dir="${agent.distro.dir}/lib/augeas/lib64" perm="ug+rx" includes="*.so,*.so.1"/> + <chmod dir="${agent.distro.dir}/lib" perm="ug+rx" includes="*.so,${so.exts},*.sl,*.dylib"/> + <chmod dir="${agent.distro.dir}/lib/augeas/lib" perm="ug+rx" includes="*.so,${so.exts}"/> + <chmod dir="${agent.distro.dir}/lib/augeas/lib64" perm="ug+rx" includes="*.so,${so.exts}"/>
<copy todir="${agent.distro.dir}/bin"> <fileset dir="${basedir}/src/etc" @@ -217,7 +219,7 @@ Ant Script that provides ways to package the Agent. <include name="rhq-agent/**"/> <exclude name="rhq-agent/bin/*.sh"/> <exclude name="rhq-agent/lib/*.so"/> - <exclude name="rhq-agent/lib/*.so.1"/> + <exclude name="rhq-agent/lib/${so.exts}"/> <exclude name="rhq-agent/lib/*.sl"/> <exclude name="rhq-agent/lib/*.dylib"/> <exclude name="rhq-agent/lib/augeas/**" /> @@ -225,12 +227,13 @@ Ant Script that provides ways to package the Agent. <zipfileset dir="${basedir}/target" filemode="755" dirmode="755"> <include name="rhq-agent/bin/*.sh"/> <include name="rhq-agent/lib/*.so"/> + <include name="rhq-agent/lib/${so.exts}"/> <include name="rhq-agent/lib/*.sl"/> <include name="rhq-agent/lib/*.dylib"/> <include name="rhq-agent/lib/augeas/lib/*.so"/> - <include name="rhq-agent/lib/augeas/lib/*.so.1"/> + <include name="rhq-agent/lib/augeas/lib/${so.exts}"/> <include name="rhq-agent/lib/augeas/lib64/*.so"/> - <include name="rhq-agent/lib/augeas/lib64/*.so.1"/> + <include name="rhq-agent/lib/augeas/lib64/${so.exts}"/> </zipfileset> </zip>
commit 685985600a5e0e9468b6e393c7fa09d5772b0afe Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 12 12:37:13 2012 -0500
this is for unix developers - only retry 3 times - if the installer can't do its thing by then, something is probably wrong anyway. this doesn't involve production functionality - rhq-autonistaller.sh is only for dev mode builds
diff --git a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh index f61a482..e7cadef 100755 --- a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh +++ b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.sh @@ -11,7 +11,7 @@ _INSTALLER_SCRIPT="${RHQ_SERVER_HOME}/bin/rhq-installer.sh" # we are normally executed just before the server starts, so give it time to initialize sleep 5
-_TRIES="1 2 3 4 5" +_TRIES="1 2 3" for _TRY in $_TRIES do echo Running Installer Now...
commit 7e1c0397aa94683d0efb35166c3970dae969ea46 Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 12 12:33:20 2012 -0500
only have it try 2 times (as opposed to 5). if the server isn't up in time for our installer to do its thing by then, something is probably wrong anyway this is only for windows developers use (dev mode) so this isn't involving production functionality
diff --git a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat index b756b31..888d147 100644 --- a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat +++ b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat @@ -19,7 +19,7 @@ rem we are normally executed just before the server starts, so give it time to i rem yes, this is a sleep of 5s, backwards compatible to XP ping 127.0.0.1 -n 5 -w 1000 > nul
-for /L %%i in (1,1,5) do ( +for /L %%i in (1,1,2) do ( echo Running Installer Now... CALL "%_INSTALLER_SCRIPT%" if ERRORLEVEL 2 (
commit 5f3dbdeeb2e800f3b730dc0f3befad9b244e6615 Author: John Mazzitelli mazz@redhat.com Date: Wed Dec 12 12:26:04 2012 -0500
fix windows script so dir names are quoted when starting the vm
diff --git a/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.bat b/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.bat index 81d83ad..3140467 100644 --- a/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.bat +++ b/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-installer.bat @@ -136,7 +136,7 @@ if defined RHQ_SERVER_DEBUG echo _JBOSS_MODULEPATH: %_JBOSS_MODULEPATH% echo Starting RHQ Server installer ...
rem start the AS instance with our main installer module -%RHQ_SERVER_JAVA_EXE_FILE_PATH% %RHQ_SERVER_INSTALLER_JAVA_OPTS% %RHQ_SERVER_INSTALLER_ADDITIONAL_JAVA_OPTS% -jar %RHQ_SERVER_HOME%\jbossas\jboss-modules.jar -mp %_JBOSS_MODULEPATH% org.rhq.rhq-installer-util %* +"%RHQ_SERVER_JAVA_EXE_FILE_PATH%" %RHQ_SERVER_INSTALLER_JAVA_OPTS% %RHQ_SERVER_INSTALLER_ADDITIONAL_JAVA_OPTS% -jar "%RHQ_SERVER_HOME%\jbossas\jboss-modules.jar" -mp "%_JBOSS_MODULEPATH%" org.rhq.rhq-installer-util %*
goto :done
commit 946dee4b2e8c8ce275f069a3c79efedd3c7aaf74 Author: Jay Shaughnessy jshaughn@jshaughn.csb Date: Wed Dec 12 09:12:47 2012 -0500
Oracle testing - Add no-tx-separate=pools=true for ora XA datasource to avoid connection issues - remove SetBigStringTryClob conn prop for oracle because we shouldn't need it with the Ora11 driver and trying to set hits an AS bug - apply necessary changes to installer as well as test code - fix issues with aggressive and sometimes non-functioning cleanup code in MeasurementDataManagerBeanTest - Add oracle driver jar to test deployment to support dbunit Also - Add support for recovery-plugin class for postgres to avoid mem leak in 7.1.1.Final. (note - the actual use of that hook will be in a subsequent commit)
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java index ab44796..1b5b462 100644 --- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java +++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/DatasourceJBossASClient.java @@ -261,9 +261,12 @@ public class DatasourceJBossASClient extends JBossASClient { * @param idleTimeoutMinutes * @param minPoolSize * @param maxPoolSize + * @param noRecovery optional, left unset if null + * @param noTxSeparatePools optional, left unset if null * @param preparedStatementCacheSize + * @param recoveryPluginClassName optional, left unset if null * @param securityDomain - * @param staleConnectionCheckerClassName + * @param staleConnectionCheckerClassName optional, left unset if null * @param transactionIsolation * @param validConnectionCheckerClassName * @param xaDatasourceProperties @@ -271,9 +274,10 @@ public class DatasourceJBossASClient extends JBossASClient { * @return the request that can be used to create the XA datasource */ public ModelNode createNewXADatasourceRequest(String name, int blockingTimeoutWaitMillis, String driverName, - String exceptionSorterClassName, int idleTimeoutMinutes, int minPoolSize, int maxPoolSize, - int preparedStatementCacheSize, String securityDomain, String staleConnectionCheckerClassName, - String transactionIsolation, String validConnectionCheckerClassName, Map<String, String> xaDatasourceProperties) { + String exceptionSorterClassName, int idleTimeoutMinutes, int minPoolSize, int maxPoolSize, Boolean noRecovery, + Boolean noTxSeparatePools, int preparedStatementCacheSize, String recoveryPluginClassName, + String securityDomain, String staleConnectionCheckerClassName, String transactionIsolation, + String validConnectionCheckerClassName, Map<String, String> xaDatasourceProperties) {
String jndiName = "java:jboss/datasources/" + name;
@@ -286,8 +290,11 @@ public class DatasourceJBossASClient extends JBossASClient { + ", "jndi-name" => "%s" " // + ", "jta" => true " // + ", "min-pool-size" => %d " // - + ", "max-pool-size" => %d " // + + ", "max-pool-size" => %d " // + + ", "no-recovery" => %b " // + + ", "no-tx-separate-pools" => %b " // + ", "prepared-statements-cache-size" => %dL " // + + ", "recovery-plugin-class-name" => "%s" " // + ", "security-domain" => "%s" " // + ", "stale-connection-checker-class-name" => "%s" " // + ", "transaction-isolation" => "%s" " // @@ -296,8 +303,11 @@ public class DatasourceJBossASClient extends JBossASClient { + "}";
String dmr = String.format(dmrTemplate, blockingTimeoutWaitMillis, driverName, exceptionSorterClassName, - idleTimeoutMinutes, jndiName, minPoolSize, maxPoolSize, preparedStatementCacheSize, securityDomain, - staleConnectionCheckerClassName, transactionIsolation, validConnectionCheckerClassName); + idleTimeoutMinutes, jndiName, minPoolSize, maxPoolSize, noRecovery, noTxSeparatePools, + preparedStatementCacheSize, recoveryPluginClassName, securityDomain, staleConnectionCheckerClassName, + transactionIsolation, validConnectionCheckerClassName); + + System.out.println("**** \n" + dmr);
Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_DATASOURCES, XA_DATA_SOURCE, name); final ModelNode request1 = ModelNode.fromString(dmr); @@ -327,6 +337,22 @@ public class DatasourceJBossASClient extends JBossASClient { batch[n++] = requestN; }
- return createBatchRequest(batch); + ModelNode result = createBatchRequest(batch); + + // remove unset args + if (null == noRecovery) { + result.get("steps").get(0).remove("no-recovery"); + } + if (null == noTxSeparatePools) { + result.get("steps").get(0).remove("no-tx-separate-pools"); + } + if (null == recoveryPluginClassName) { + result.get("steps").get(0).remove("recovery-plugin-class-name"); + } + if (null == staleConnectionCheckerClassName) { + result.get("steps").get(0).remove("stale-connection-checker-class-name"); + } + + return result; } } diff --git a/modules/core/domain/pom.xml b/modules/core/domain/pom.xml index e874c08..cb7699b 100644 --- a/modules/core/domain/pom.xml +++ b/modules/core/domain/pom.xml @@ -381,7 +381,7 @@ </timeout> <statement> <prepared-statement-cache-size>75</prepared-statement-cache-size> - </statement> + </statement> </xa-datasource>]]></replacevalue> </replacefilter>
@@ -441,6 +441,11 @@ <xa-pool> <min-pool-size>5</min-pool-size> <max-pool-size>50</max-pool-size> + <!-- + Oracle does not like XA connections getting used both inside and outside a JTA transaction. + To workaround the problem you can create separate sub-pools for the different contexts using <no-tx-separate-pools/> + --> + <no-tx-separate-pools>true</no-tx-separate-pools> </xa-pool> <security> <security-domain>RHQDSSecurityDomain</security-domain> diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java index 516dca6..c65001d 100644 --- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java +++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/ServerInstallUtil.java @@ -511,7 +511,7 @@ public class ServerInstallUtil { "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, false, 2, 5, 75, RHQ_DS_SECURITY_DOMAIN, "-unused-stale-conn-checker-", "TRANSACTION_READ_COMMITTED", "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker", props); - noTxDsRequest.get("steps").get(0).remove("stale-connection-checker-class-name"); // we don't have one of these for postgres + noTxDsRequest.get("steps").get(0).remove("stale-connection-checker-class-name"); // we don't have one of these for postgres } else { LOG.info("Postgres datasource [" + RHQ_DATASOURCE_NAME_NOTX + "] already exists"); } @@ -522,11 +522,18 @@ public class ServerInstallUtil { props.put("PortNumber", "${rhq.server.database.port:5432}"); props.put("DatabaseName", "${rhq.server.database.db-name:rhq}");
+ /* TODO: Use this version which defines the recovery plugin xaDsRequest = client.createNewXADatasourceRequest(RHQ_DATASOURCE_NAME_XA, 30000, JDBC_DRIVER_POSTGRES, - "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, 5, 50, 75, - RHQ_DS_SECURITY_DOMAIN, "-unused-stale-conn-checker-", "TRANSACTION_READ_COMMITTED", + "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, 5, 50, Boolean.FALSE, + (Boolean) null, 75, "org.jboss.jca.core.recovery.ValidatingManagedConnectionFactoryRecoveryPlugin", + RHQ_DS_SECURITY_DOMAIN, (String) null, "TRANSACTION_READ_COMMITTED", + "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker", props); + */ + xaDsRequest = client.createNewXADatasourceRequest(RHQ_DATASOURCE_NAME_XA, 30000, JDBC_DRIVER_POSTGRES, + "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter", 15, 5, 50, (Boolean) null, + (Boolean) null, 75, (String) null, RHQ_DS_SECURITY_DOMAIN, (String) null, "TRANSACTION_READ_COMMITTED", "org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker", props); - xaDsRequest.get("steps").get(0).remove("stale-connection-checker-class-name"); // we don't have one of these for postgres + } else { LOG.info("Postgres XA datasource [" + RHQ_DATASOURCE_NAME_XA + "] already exists"); } @@ -549,7 +556,6 @@ public class ServerInstallUtil {
if (!client.isDatasource(RHQ_DATASOURCE_NAME_NOTX)) { props.put("char.encoding", "UTF-8"); - props.put("SetBigStringTryClob", "true");
noTxDsRequest = client.createNewDatasourceRequest(RHQ_DATASOURCE_NAME_NOTX, 30000, "${rhq.server.database.connection-url:jdbc:oracle:thin:@127.0.0.1:1521:rhq}", JDBC_DRIVER_ORACLE, @@ -564,11 +570,11 @@ public class ServerInstallUtil { if (!client.isDatasource(RHQ_DATASOURCE_NAME_XA)) { props.clear(); props.put("URL", "${rhq.server.database.connection-url:jdbc:oracle:thin:@127.0.0.1:1521:rhq}"); - props.put("ConnectionProperties", "SetBigStringTryClob=true");
xaDsRequest = client.createNewXADatasourceRequest(RHQ_DATASOURCE_NAME_XA, 30000, JDBC_DRIVER_ORACLE, - "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter", 15, 5, 50, 75, - RHQ_DS_SECURITY_DOMAIN, "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker", + "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter", 15, 5, 50, (Boolean) null, + Boolean.TRUE, 75, (String) null, RHQ_DS_SECURITY_DOMAIN, + "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker", "TRANSACTION_READ_COMMITTED", "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker", props); } else { diff --git a/modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/client/DatasourceJBossASClientTest.java b/modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/client/DatasourceJBossASClientTest.java index f2dd7bc..52a3478 100644 --- a/modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/client/DatasourceJBossASClientTest.java +++ b/modules/enterprise/server/installer/src/test/java/org/rhq/enterprise/server/installer/client/DatasourceJBossASClientTest.java @@ -106,7 +106,8 @@ public class DatasourceJBossASClientTest { xaDSProps.put("ConnectionProperties", "SetBigStringTryClob=true");
ModelNode request = client.createNewXADatasourceRequest("RHQDS", 30000, "oracle", - "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter", 15, 2, 5, 75, "RHQDSSecurityDomain", + "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter", 15, 2, 5, (Boolean) null, + Boolean.TRUE, 75, (String) null, "RHQDSSecurityDomain", "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker", "TRANSACTION_READ_COMMITTED", "org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker", xaDSProps);
diff --git a/modules/enterprise/server/itests-2/pom.xml b/modules/enterprise/server/itests-2/pom.xml index c0c420e..e1b466f 100644 --- a/modules/enterprise/server/itests-2/pom.xml +++ b/modules/enterprise/server/itests-2/pom.xml @@ -23,7 +23,8 @@ <properties> <jboss.zip>${settings.localRepository}/org/jboss/as/jboss-as-dist/${jboss.version}/jboss-as-dist-${jboss.version}.zip</jboss.zip> <jboss.unzip.location>${basedir}/target/jboss-as-${jboss.version}</jboss.unzip.location> - <jboss.vm.args>-Xmx700m -XX:MaxPermSize=200m -Djava.security.manager -Djava.security.policy==${jboss.unzip.location}/security.policy</jboss.vm.args> + <jboss.vm.args>-Xmx700m -XX:MaxPermSize=200m -Djava.security.manager + -Djava.security.policy==${jboss.unzip.location}/security.policy</jboss.vm.args> <jboss.vm.args.debug></jboss.vm.args.debug> <!-- -Ditest.debug can override this, see below --> </properties>
@@ -225,11 +226,9 @@ <echo>JBossAS ${jboss.version} should now be at: ${jboss.unzip.location}</echo>
<echo>Copying security policy to JBossAS</echo> - <copy file="${project.build.directory}/test-classes/security.policy" tofile="${jboss.unzip.location}/security.policy"/> - - <property - name="jboss.conf" - location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> + <copy file="${project.build.directory}/test-classes/security.policy" tofile="${jboss.unzip.location}/security.policy" /> + + <property name="jboss.conf" location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> <echo>Will now add test configuration to JBossAS config file: ${jboss.conf}</echo> <replace file="${jboss.conf}">
@@ -520,7 +519,10 @@ </timeout> <statement> <prepared-statement-cache-size>75</prepared-statement-cache-size> - </statement> + </statement> + <recovery no-recovery="false"> + <recover-plugin class-name="org.jboss.jca.core.recovery.ValidatingManagedConnectionFactoryRecoveryPlugin"/> + </recovery> </xa-datasource>]]></replacevalue> </replacefilter>
@@ -580,6 +582,11 @@ <xa-pool> <min-pool-size>5</min-pool-size> <max-pool-size>50</max-pool-size> + <!-- + Oracle does not like XA connections getting used both inside and outside a JTA transaction. + To workaround the problem you can create separate sub-pools for the different contexts using <no-tx-separate-pools/> + --> + <no-tx-separate-pools>true</no-tx-separate-pools> </xa-pool> <security> <security-domain>RHQDSSecurityDomain</security-domain> @@ -631,15 +638,8 @@ <clean.db>${clean.db}</clean.db> <log4j.configDebug>false</log4j.configDebug> <project.version>${project.version}</project.version> - - <rhq.test.ds.type-mapping>${rhq.test.ds.type-mapping}</rhq.test.ds.type-mapping> - <rhq.test.ds.server-name>${rhq.test.ds.server-name}</rhq.test.ds.server-name> - <rhq.test.ds.db-name>${rhq.test.ds.db-name}</rhq.test.ds.db-name> - <rhq.test.ds.connection-url>${rhq.test.ds.connection-url}</rhq.test.ds.connection-url> - <rhq.db.admin.username>${rhq.db.admin.username}</rhq.db.admin.username> - <rhq.db.admin.password>${rhq.db.admin.password}</rhq.db.admin.password> - <rhq.test.ds.user-name>${rhq.test.ds.user-name}</rhq.test.ds.user-name> - <rhq.test.ds.password>${rhq.test.ds.password}</rhq.test.ds.password> + <rhq.skip.oracle>${skip.oracle}</rhq.skip.oracle> + <rhq.ojdbc.version>${ojdbc6.version}</rhq.ojdbc.version> </systemPropertyVariables> <additionalClasspathElements> <!-- The below is required for tests to run against Oracle. --> diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java index 9c2882c..8861378 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/measurement/MeasurementDataManagerBeanTest.java @@ -31,6 +31,8 @@ import static org.rhq.core.domain.measurement.NumericType.DYNAMIC; import static org.rhq.core.domain.resource.ResourceCategory.SERVER; import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+import java.math.BigDecimal; +import java.math.MathContext; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; @@ -46,6 +48,7 @@ import org.testng.annotations.Test;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.EntityContext; +import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.measurement.MeasurementDataNumeric; import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.measurement.MeasurementReport; @@ -59,8 +62,10 @@ import org.rhq.core.util.jdbc.JDBCUtil; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.drift.DriftServerPluginService; import org.rhq.enterprise.server.measurement.util.MeasurementDataManagerUtility; +import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.test.TransactionCallback; +import org.rhq.enterprise.server.util.ResourceTreeHelper; import org.rhq.test.AssertUtils;
/** @@ -108,6 +113,9 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { @EJB private MeasurementDataManagerLocal dataManager;
+ @EJB + private ResourceManagerLocal resourceManager; + @Override protected void beforeMethod() throws Exception { overlord = subjectManager.getOverlord(); @@ -149,15 +157,14 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { dataManager.mergeMeasurementReport(report);
List<MeasurementDataNumericHighLowComposite> actualData = findDataForContext(overlord, - EntityContext.forResource(resource.getId()), dynamicSchedule, beginTime.getMillis(), - endTime.getMillis()); + EntityContext.forResource(resource.getId()), dynamicSchedule, beginTime.getMillis(), endTime.getMillis());
assertEquals("Expected to get back 60 data points.", buckets.getNumDataPoints(), actualData.size());
MeasurementDataNumericHighLowComposite expectedBucket0Data = new MeasurementDataNumericHighLowComposite( - buckets.get(0), (1.1 + 2.2 + 3.3) / 3, 3.3, 1.1); + buckets.get(0), divide((1.1 + 2.2 + 3.3), 3), 3.3, 1.1); MeasurementDataNumericHighLowComposite expectedBucket59Data = new MeasurementDataNumericHighLowComposite( - buckets.get(59), (4.4 + 5.5 + 6.6) / 3, 6.6, 4.4); + buckets.get(59), divide((4.4 + 5.5 + 6.6), 3), 6.6, 4.4); MeasurementDataNumericHighLowComposite expectedBucket29Data = new MeasurementDataNumericHighLowComposite( buckets.get(29), Double.NaN, Double.NaN, Double.NaN);
@@ -169,6 +176,11 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { actualData.get(29)); }
+ static double divide(double dividend, int divisor) { + return new BigDecimal(Double.toString(dividend)).divide(new BigDecimal(Integer.toString(divisor)), + MathContext.DECIMAL64).doubleValue(); + } + @Test(enabled = true) public void getRawAggregate() { DateTime now = new DateTime(); @@ -191,8 +203,7 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { MeasurementAggregate actual = dataManager.getAggregate(overlord, dynamicSchedule.getId(), beginTime.getMillis(), endTime.getMillis());
- MeasurementAggregate expected = new MeasurementAggregate(1.1, (1.1 + 2.2 + 3.3 + 4.4 + 5.5 + 6.6) / 6, - 6.6); + MeasurementAggregate expected = new MeasurementAggregate(1.1, (1.1 + 2.2 + 3.3 + 4.4 + 5.5 + 6.6) / 6, 6.6);
AssertUtils.assertPropertiesMatch(expected, actual, "Aggregate does not match"); } @@ -206,19 +217,16 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { // results in an interval or bucket size of 4.4 hours Buckets buckets = new Buckets(beginTime, endTime);
- List<AggregateTestData> data = asList( - new AggregateTestData(buckets.get(0), dynamicSchedule.getId(), 2.0, 3.0, 1.0), - new AggregateTestData(buckets.get(0) + Hours.ONE.toStandardDuration().getMillis(), - dynamicSchedule.getId(), 5.0, 6.0, 4.0), - new AggregateTestData(buckets.get(0) + Hours.TWO.toStandardDuration().getMillis(), + List<AggregateTestData> data = asList(new AggregateTestData(buckets.get(0), dynamicSchedule.getId(), 2.0, 3.0, + 1.0), + new AggregateTestData(buckets.get(0) + Hours.ONE.toStandardDuration().getMillis(), dynamicSchedule.getId(), + 5.0, 6.0, 4.0), new AggregateTestData(buckets.get(0) + Hours.TWO.toStandardDuration().getMillis(), dynamicSchedule.getId(), 3.0, 3.0, 3.0),
- new AggregateTestData(buckets.get(59), dynamicSchedule.getId(), 5.0, 9.0, 2.0), - new AggregateTestData(buckets.get(59) + Hours.ONE.toStandardDuration().getMillis(), - dynamicSchedule.getId(), 5.0, 6.0, 4.0), + new AggregateTestData(buckets.get(59), dynamicSchedule.getId(), 5.0, 9.0, 2.0), new AggregateTestData( + buckets.get(59) + Hours.ONE.toStandardDuration().getMillis(), dynamicSchedule.getId(), 5.0, 6.0, 4.0), new AggregateTestData(buckets.get(59) + Hours.TWO.toStandardDuration().getMillis(), - dynamicSchedule.getId(), 3.0, 3.0, 3.0) - ); + dynamicSchedule.getId(), 3.0, 3.0, 3.0));
insert1HourData(data);
@@ -281,11 +289,20 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { executeInTransaction(false, new TransactionCallback() { @Override public void execute() throws Exception { + ResourceCriteria c = new ResourceCriteria(); + c.addFilterInventoryStatus(null); + c.addFilterResourceKey(RESOURCE_KEY); + c.fetchSchedules(true); + List<Resource> r = resourceManager.findResourcesByCriteria(subjectManager.getOverlord(), c);
// Note that the order of deletes is important due to FK // constraints. - deleteMeasurementSchedules(); - deleteResource(); + if (!r.isEmpty()) { + assertTrue("Should be only 1 resource", r.size() == 1); + Resource doomedResource = r.get(0); + deleteMeasurementSchedules(doomedResource); + deleteResource(doomedResource); + } deleteAgent(); deleteDynamicMeasurementDef(); deleteResourceType(); @@ -294,38 +311,31 @@ public class MeasurementDataManagerBeanTest extends AbstractEJB3Test { }
private void deleteDynamicMeasurementDef() { - em.createQuery("delete from MeasurementDefinition " + - "where dataType = :dataType and " + - "name = :name") - .setParameter("dataType", MEASUREMENT) - .setParameter("name", DYNAMIC_DEF_NAME) - .executeUpdate(); + em.createQuery("delete from MeasurementDefinition " + "where dataType = :dataType and " + "name = :name") + .setParameter("dataType", MEASUREMENT).setParameter("name", DYNAMIC_DEF_NAME).executeUpdate(); }
private void deleteAgent() { - em.createQuery("delete from Agent where name = :name") - .setParameter("name", AGENT_NAME) - .executeUpdate(); + em.createQuery("delete from Agent where name = :name").setParameter("name", AGENT_NAME).executeUpdate(); }
private void deleteResourceType() { em.createQuery("delete from ResourceType where name = :name and plugin = :plugin") - .setParameter("name", RESOURCE_TYPE) - .setParameter("plugin", PLUGIN) - .executeUpdate(); + .setParameter("name", RESOURCE_TYPE).setParameter("plugin", PLUGIN).executeUpdate(); }
- private void deleteResource() { - em.createQuery("delete from Availability").executeUpdate(); - - em.createQuery("delete from Resource where resourceKey = :key and uuid = :uuid") - .setParameter("key", RESOURCE_KEY) - .setParameter("uuid", RESOURCE_UUID) - .executeUpdate(); + private void deleteResource(Resource doomedResource) { + ResourceTreeHelper.deleteResource(em, doomedResource); + em.flush(); }
- private void deleteMeasurementSchedules() { - em.createQuery("delete from MeasurementSchedule").executeUpdate(); + private void deleteMeasurementSchedules(Resource doomedResource) { + for (MeasurementSchedule ms : doomedResource.getSchedules()) { + int i = em.createQuery("delete from MeasurementSchedule where id = :msId").setParameter("msId", ms.getId()) + .executeUpdate(); + em.flush(); + System.out.println("Deleted [" + i + "] schedules with id [" + ms.getId() + "]"); + } }
private void insertDummyReport() { diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java index deceebc..dd46a29 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java @@ -338,6 +338,13 @@ public abstract class AbstractEJB3Test extends Arquillian { dependencies.addAll(resolver.artifact("org.rhq:test-utils").resolveAs(JavaArchive.class)); dependencies.addAll(resolver.artifact("org.rhq.helpers:perftest-support").resolveAs(JavaArchive.class));
+ // If we're running oracle we need to include the OJDBC driver because dbunit needs it. Note that we need + // add it explicitly even though it is a provided module used by the datasource. + if (!Boolean.valueOf(System.getProperty("rhq.skip.oracle"))) { + dependencies.addAll(resolver.artifact("com.oracle:ojdbc6:jar:" + System.getProperty("rhq.ojdbc.version")) + .resolveAs(JavaArchive.class)); + } + // Transitive deps required by the above and for some reason not sucked in. Note that // these require an explicit version. TODO (jshaughn): Can we make these transitive or // avoid the explicit version?
commit a33df9ca8700523e66d6443b4454977433330233 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Dec 12 13:41:08 2012 +0100
Forgot to re-enable the now fixed and working JndiAccessTest in itests-2.
diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java index e831a2b..fabe6ae 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java @@ -47,8 +47,7 @@ import org.rhq.enterprise.server.util.LookupUtil; * * @author Lukas Krejci */ -@Test(enabled = false) -// TODO JNDI: reenable after fixing secure jndi lookups +@Test public class JndiAccessTest extends AbstractEJB3Test {
public void testScriptCantOverrideSystemProperties() throws Exception {
commit 4a2e78668aae419f5f47bbc45c4f4ac7b7c339ac Author: Stefan Negrea snegrea@redhat.com Date: Wed Dec 12 00:17:32 2012 -0600
Update Cassandra plugin pom to include the dev profile for dev container deployments.
diff --git a/modules/plugins/cassandra/pom.xml b/modules/plugins/cassandra/pom.xml index ab61220..d8cfd68 100644 --- a/modules/plugins/cassandra/pom.xml +++ b/modules/plugins/cassandra/pom.xml @@ -13,12 +13,6 @@ <name>RHQ Cassandra Plugin</name> <description>An RHQ plugin for monitoring and managing a Cassandra cluster</description>
- <properties> - <rhq.rootDir>../../..</rhq.rootDir> - <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> - <rhq.deploymentDir>${rhq.containerDir}/${rhq.agentPluginDir}</rhq.deploymentDir> - </properties> - <dependencies> <dependency> <groupId>commons-logging</groupId> @@ -156,62 +150,11 @@ </execution> </executions> </plugin> + <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> - <id>deploy</id> - <phase>package</phase> - <configuration> - <target> - <mkdir dir="${rhq.deploymentDir}"/> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> - <echo>*** Updating ${deployment.file}...</echo> - <jar destfile="${deployment.file}" basedir="${project.build.outputDirectory}"/> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - <execution> - <id>deploy-jar-meta-inf</id> - <phase>package</phase> - <configuration> - <target> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> - <echo>*** Updating META-INF dir in ${deployment.file}...</echo> - <unjar src="${project.build.directory}/${project.build.finalName}.jar" - dest="${project.build.outputDirectory}"> - <patternset> - <include name="META-INF/**"/> - </patternset> - </unjar> - <jar destfile="${deployment.file}" manifest="${project.build.outputDirectory}/META-INF/MANIFEST.MF" - update="true"> - </jar> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - <execution> - <id>undeploy</id> - <phase>clean</phase> - <configuration> - <target> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> - <echo>*** Deleting ${deployment.file}...</echo> - <delete file="${deployment.file}"/> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - - <execution> <phase>pre-integration-test</phase> <configuration> <target> @@ -224,9 +167,6 @@ <fileset dir="${settings.localRepository}/"> <include name="org/rhq/rhq-jmx-plugin/${project.version}/rhq-jmx-plugin-${project.version}.jar" /> </fileset> - <fileset dir="${rhq.deploymentDir}"> - <include name="${project.artifactId}-${project.version}.jar" /> - </fileset> <fileset dir="${project.build.directory}" includes="${project.artifactId}-${project.version}.jar" /> </copy>
@@ -290,4 +230,78 @@ </plugin> </plugins> </build> + + <profiles> + <profile> + <id>dev</id> + + <properties> + <rhq.rootDir>../../..</rhq.rootDir> + <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> + <rhq.deploymentDir>${rhq.containerDir}/${rhq.agentPluginDir}</rhq.deploymentDir> + </properties> + + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <id>deploy</id> + <phase>package</phase> + <configuration> + <target> + <mkdir dir="${rhq.deploymentDir}"/> + <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> + <echo>*** Updating ${deployment.file}...</echo> + <jar destfile="${deployment.file}" basedir="${project.build.outputDirectory}"/> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>deploy-jar-meta-inf</id> + <phase>package</phase> + <configuration> + <target> + <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> + <echo>*** Updating META-INF dir in ${deployment.file}...</echo> + <unjar src="${project.build.directory}/${project.build.finalName}.jar" + dest="${project.build.outputDirectory}"> + <patternset> + <include name="META-INF/**"/> + </patternset> + </unjar> + <jar destfile="${deployment.file}" manifest="${project.build.outputDirectory}/META-INF/MANIFEST.MF" + update="true"> + </jar> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>undeploy</id> + <phase>clean</phase> + <configuration> + <target> + <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar"/> + <echo>*** Deleting ${deployment.file}...</echo> + <delete file="${deployment.file}"/> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> + </project>
commit 681e5d638ac4b5f1c8770cc34d56141aad6346ac Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 15:49:31 2012 -0500
put the war in the new ear location
diff --git a/modules/enterprise/gui/rest-examples-war/pom.xml b/modules/enterprise/gui/rest-examples-war/pom.xml index e0d801f..1eb1ad2 100644 --- a/modules/enterprise/gui/rest-examples-war/pom.xml +++ b/modules/enterprise/gui/rest-examples-war/pom.xml @@ -57,7 +57,7 @@ <rhq.rootDir>../../../..</rhq.rootDir> <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> <rhq.deploymentName>${project.build.finalName}.war</rhq.deploymentName> - <rhq.deploymentDir>${rhq.containerDir}/jbossas/standalone/deployments/${rhq.earName}/${rhq.deploymentName}</rhq.deploymentDir> + <rhq.deploymentDir>${rhq.containerDir}/${rhq.earDeployDir}/${rhq.deploymentName}</rhq.deploymentDir> </properties>
<build>
commit af5d45b9d4f18d13762ac7b90232e69522e5d91f Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 15:42:13 2012 -0500
fix location where cassandra plugin goes in dev profile mode (though there is no dev profile declaration - this should be fixed also)
diff --git a/modules/plugins/cassandra/pom.xml b/modules/plugins/cassandra/pom.xml index a65384c..ab61220 100644 --- a/modules/plugins/cassandra/pom.xml +++ b/modules/plugins/cassandra/pom.xml @@ -16,7 +16,7 @@ <properties> <rhq.rootDir>../../..</rhq.rootDir> <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> - <rhq.deploymentDir>${rhq.containerDir}/jbossas/server/default/deploy/${rhq.earName}/rhq-downloads/rhq-plugins</rhq.deploymentDir> + <rhq.deploymentDir>${rhq.containerDir}/${rhq.agentPluginDir}</rhq.deploymentDir> </properties>
<dependencies>
commit e22bbe3464a5e36cafc3ba3a152b4ce8e4669a95 Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 15:35:20 2012 -0500
trivial changes to generated props file
diff --git a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml index 47dd0d5..d84f8c4 100644 --- a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml +++ b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml @@ -345,8 +345,8 @@ # If you are using Oracle, comment out the Postgres settings and # uncomment the Oracle settings below, adjusting the values as appropriate. # NOTE: rhq.server.database.password is not to be set to the actual password -# but instead should be that actual password in encoded form as generated -# by the "rhq-installer.sh(.bat) --dbpassword=<your password>". +# but instead should be the password in encoded form as generated by: +# rhq-installer.sh(.bat) --dbpassword=<your password> #############################################################################
# PostgreSQL database @@ -567,7 +567,7 @@ rhq.sync.endpoint-address=false # persist content for well known binary file types like .ear, .war, .zip, .so, # etc. The server does however persist content for text files or any other # files that are not known binary types. -# rhq.server.drift.store-binary-content=${rhq.server.drift.store-binary-content} +#rhq.server.drift.store-binary-content=${rhq.server.drift.store-binary-content}
</echo>
commit 9f69c42dcd96046982b66022f92c5f00f660b416 Author: Heiko W. Rupp hwr@redhat.com Date: Tue Dec 11 17:54:04 2012 +0100
BZ 861491 - Choose a better display name and description for the 'promote' operation. (cherry-picked from e4203a2, BZ 860665)
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml index 46b3084..ba4fe29 100644 --- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml @@ -1114,9 +1114,9 @@ <c:simple-property name="path" default="deployment" readOnly="true"/> </plugin-configuration>
- <operation name="promote" displayName="Deploy to Server-Group" description="Deploy this deployment to a server group"> + <operation name="promote" displayName="Assign to Server-Group" description="Assigns this deployment to one or all server group(s)"> <parameters> - <c:simple-property name="server-group" required="true" description="Server group to deploy to" type="string"> + <c:simple-property name="server-group" required="true" description="Server group to assign to" type="string"> <c:property-options> <c:option value="__all" name="All"/> </c:property-options>
commit 6123c8974ddfd2ac9d44aefbc90668b846e823de Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 11:00:30 2012 -0500
make the oracle module an optional dep in the installer to support those cases where we can't ship the Oracle JDBC driver jar.
diff --git a/modules/enterprise/server/installer/src/main/resources/module/main/module.xml b/modules/enterprise/server/installer/src/main/resources/module/main/module.xml index fcc5cc0..4358c6b 100644 --- a/modules/enterprise/server/installer/src/main/resources/module/main/module.xml +++ b/modules/enterprise/server/installer/src/main/resources/module/main/module.xml @@ -28,7 +28,7 @@ <module name="org.jboss.staxmapper"/> <module name="org.picketbox"/> <module name="org.rhq.postgres"/> - <module name="org.rhq.oracle"/> + <module name="org.rhq.oracle" optional="true" /> <module name="javax.api"/> </dependencies>
commit f7dcb1f2bc8e88e1febcb735f1a9a3c6caa6af15 Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 10:32:47 2012 -0500
we dont use this now, but in case we bring it back, i'll fix this now
diff --git a/modules/enterprise/server/sars/agent-sar/src/main/resources/embedded-agent-configuration-overrides.properties b/modules/enterprise/server/sars/agent-sar/src/main/resources/embedded-agent-configuration-overrides.properties index 3bcc7d7..c14c614 100644 --- a/modules/enterprise/server/sars/agent-sar/src/main/resources/embedded-agent-configuration-overrides.properties +++ b/modules/enterprise/server/sars/agent-sar/src/main/resources/embedded-agent-configuration-overrides.properties @@ -11,7 +11,7 @@ rhq.communications.connector.bind-port=${rhq.server.embedded-agent.bind-port:261 # location where data files can be stored rhq.agent.data-directory=${jboss.server.data.dir}/embedded-agent # location of the plugins -rhq.agent.plugins.directory=${jboss.server.base.dir}/deployments/rhq.ear/rhq-downloads/rhq-plugins +rhq.agent.plugins.directory=${rhq.server.home}/modules/org/rhq/rhq-enterprise-server-startup-subsystem/main/deployments/rhq.ear/rhq-downloads/rhq-plugins # Client-side SSL Security Configuration (for sending messages to the server) rhq.agent.client.security.secure-socket-protocol=${rhq.communications.connector.security.secure-socket-protocol:TLS} rhq.agent.client.security.keystore.file=${rhq.communications.connector.security.keystore.file}
commit 2499c815bced188a19168d31451eaaaea41ed530 Author: John Mazzitelli mazz@redhat.com Date: Tue Dec 11 10:27:05 2012 -0500
fix default location for download files
diff --git a/modules/enterprise/server/sars/services-sar/src/main/resources/server-comm-configuration-overrides.properties b/modules/enterprise/server/sars/services-sar/src/main/resources/server-comm-configuration-overrides.properties index da5427b..7a407cc 100644 --- a/modules/enterprise/server/sars/services-sar/src/main/resources/server-comm-configuration-overrides.properties +++ b/modules/enterprise/server/sars/services-sar/src/main/resources/server-comm-configuration-overrides.properties @@ -1,5 +1,5 @@ # location of the plugin jars and other files agents can download directly from sever -rhq.server.agent-files-directory=${jboss.server.base.dir}/deployments/rhq.ear/rhq-downloads +rhq.server.agent-files-directory=${rhq.server.home}/modules/org/rhq/rhq-enterprise-server-startup-subsystem/main/deployments/rhq.ear/rhq-downloads # location where data files can be stored rhq.communications.data-directory=${jboss.server.data.dir} # global limit on number of concurrent incoming messages allowed
commit 58f8f8a2ef42f3ea624a0d122605917214ea8d96 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Dec 10 16:09:52 2012 -0500
Domain itest changes - remove the -ds.xml files and perform datasource decl in the standalone.xml (via the pom), analogous now to the way it is done in the server itests. - beef up the error handling in AbstractEJB3Test __before/__afterMethods to more readily flag exceptions thrown in overrides. - similarly beef up domain test Before/After methods that don't leverage the overrides - remove the SetBigStringTryClob=true connection prop for oracle, trying to set it was causing us to hit https://issues.jboss.org/browse/AS7-4673 and it seems no longer necessary with oracle11 JDBC driver (http://docs.oracle.com/cd/E11882_01/java.112/e16548/oralob.htm#CHDGEIHF). - fix some domain tests that were manhandling the entitymanager
diff --git a/modules/core/domain/pom.xml b/modules/core/domain/pom.xml index 1c2d940..e874c08 100644 --- a/modules/core/domain/pom.xml +++ b/modules/core/domain/pom.xml @@ -318,6 +318,157 @@ <goal>run</goal> </goals> </execution> + + <execution> + <id>prepare Postgres datasource</id> + <phase>process-test-resources</phase> + <configuration> + <skip>${skip.postgres}</skip> + <target> + <property name="jboss.conf" location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> + <echo>Will now add test configuration datasource to JBossAS config file: ${jboss.conf}</echo> + <replace file="${jboss.conf}"> + + <replacefilter> + <replacetoken></datasource></replacetoken> + <replacevalue><![CDATA[ + </datasource> + <!-- FOR RHQ TESTING --> + <datasource jta="false" jndi-name="java:jboss/datasources/NoTxRHQDS" pool-name="NoTxRHQDS" enabled="true" use-java-context="true"> + <connection-url>${rhq.test.ds.connection-url}</connection-url> + <connection-property name="char.encoding">UTF-8</connection-property> + <driver>postgres</driver> + <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> + <pool> + <min-pool-size>2</min-pool-size> + <max-pool-size>5</max-pool-size> + </pool> + <security> + <security-domain>RHQDSSecurityDomain</security-domain> + </security> + <validation> + <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/> + <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/> + </validation> + <timeout> + <blocking-timeout-millis>30000</blocking-timeout-millis> + <idle-timeout-minutes>15</idle-timeout-minutes> + </timeout> + <statement> + <prepared-statement-cache-size>75</prepared-statement-cache-size> + </statement> + </datasource> + <xa-datasource jta="true" jndi-name="java:jboss/datasources/RHQDS" pool-name="RHQDS" enabled="true" use-java-context="true"> + <xa-datasource-property name="DatabaseName">${rhq.test.ds.db-name}</xa-datasource-property> + <xa-datasource-property name="PortNumber">${rhq.test.ds.port}</xa-datasource-property> + <xa-datasource-property name="ServerName">${rhq.test.ds.server-name}</xa-datasource-property> + <driver>postgres</driver> + <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> + <xa-pool> + <min-pool-size>5</min-pool-size> + <max-pool-size>50</max-pool-size> + </xa-pool> + <security> + <security-domain>RHQDSSecurityDomain</security-domain> + </security> + <validation> + <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/> + <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/> + </validation> + <timeout> + <blocking-timeout-millis>30000</blocking-timeout-millis> + <idle-timeout-minutes>15</idle-timeout-minutes> + </timeout> + <statement> + <prepared-statement-cache-size>75</prepared-statement-cache-size> + </statement> + </xa-datasource>]]></replacevalue> + </replacefilter> + + </replace> + + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + <execution> + <id>prepare Oracle datasource</id> + <phase>process-test-resources</phase> + <configuration> + <skip>${skip.oracle}</skip> + <target> + <property name="jboss.conf" location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> + <echo>Will now add test configuration datasource to JBossAS config file: ${jboss.conf}</echo> + <replace file="${jboss.conf}"> + + <replacefilter> + <replacetoken></datasource></replacetoken> + <replacevalue><![CDATA[ + </datasource> + <!-- FOR RHQ TESTING --> + <datasource jta="false" jndi-name="java:jboss/datasources/NoTxRHQDS" pool-name="NoTxRHQDS" enabled="true" use-java-context="true"> + <connection-url>${rhq.test.ds.connection-url}</connection-url> + <connection-property name="char.encoding">UTF-8</connection-property> + <driver>oracle</driver> + <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> + <pool> + <min-pool-size>2</min-pool-size> + <max-pool-size>5</max-pool-size> + </pool> + <security> + <security-domain>RHQDSSecurityDomain</security-domain> + </security> + <validation> + <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker" /> + <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker" /> + <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter" /> + </validation> + <timeout> + <blocking-timeout-millis>30000</blocking-timeout-millis> + <idle-timeout-minutes>15</idle-timeout-minutes> + </timeout> + <statement> + <prepared-statement-cache-size>75</prepared-statement-cache-size> + </statement> + </datasource> + <xa-datasource jta="true" jndi-name="java:jboss/datasources/RHQDS" pool-name="RHQDS" enabled="true" use-java-context="true"> + <xa-datasource-property name="URL">${rhq.test.ds.connection-url}</xa-datasource-property> + <driver>oracle</driver> + <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> + <xa-pool> + <min-pool-size>5</min-pool-size> + <max-pool-size>50</max-pool-size> + </xa-pool> + <security> + <security-domain>RHQDSSecurityDomain</security-domain> + </security> + <validation> + <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker" /> + <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker" /> + <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter" /> + </validation> + <timeout> + <blocking-timeout-millis>30000</blocking-timeout-millis> + <idle-timeout-minutes>15</idle-timeout-minutes> + </timeout> + <statement> + <prepared-statement-cache-size>75</prepared-statement-cache-size> + </statement> + </xa-datasource>]]></replacevalue> + </replacefilter> + + </replace> + + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> </plugin>
@@ -513,6 +664,38 @@ </plugins> </build> </profile> + + <profile> + <id>postgres</id> + <activation> + <activeByDefault>true</activeByDefault> + </activation> + <properties> + <skip.postgres>false</skip.postgres> + <skip.oracle>true</skip.oracle> + </properties> + </profile> + + <profile> + <id>oracle</id> + <properties> + <skip.postgres>true</skip.postgres> + <skip.oracle>false</skip.oracle> + </properties> + </profile> + + <profile> + <id>itest.debug</id> + <activation> + <property> + <name>itest.debug</name> + </property> + </activation> + <properties> + <jboss.vm.args.debug>-Xrunjdwp:transport=dt_socket,address=8798,server=y,suspend=y</jboss.vm.args.debug> + </properties> + </profile> + </profiles>
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceSyncResultsTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceSyncResultsTest.java index 9ed1b95..c906a1a 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceSyncResultsTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceSyncResultsTest.java @@ -24,8 +24,6 @@ package org.rhq.core.domain.content.test;
import java.util.List;
-import javax.persistence.EntityManager; - import org.testng.annotations.Test;
import org.rhq.core.domain.content.Architecture; @@ -47,8 +45,6 @@ public class ContentSourceSyncResultsTest extends AbstractEJB3Test { public void testInsert() throws Exception { getTransactionManager().begin(); try { - EntityManager em = getEntityManager(); - ResourceType rt = new ResourceType("testCSSRResourceType", "testPlugin", ResourceCategory.PLATFORM, null); Resource resource = new Resource("testCSSRResource", "testCSSRResource", rt); resource.setUuid("uuid"); @@ -74,8 +70,6 @@ public class ContentSourceSyncResultsTest extends AbstractEJB3Test { em.persist(results); cs.addSyncResult(results); em.flush(); - //em.close(); - em = getEntityManager();
cs = em.find(ContentSource.class, cs.getId()); assert cs != null; @@ -100,8 +94,6 @@ public class ContentSourceSyncResultsTest extends AbstractEJB3Test { em.persist(results); cs.addSyncResult(results); em.flush(); - //em.close(); - em = getEntityManager();
cs = em.find(ContentSource.class, cs.getId()); assert cs != null; diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceTest.java index 733e0eb..00234db 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/content/test/ContentSourceTest.java @@ -24,8 +24,6 @@ package org.rhq.core.domain.content.test;
import java.util.Random;
-import javax.persistence.EntityManager; - import org.testng.annotations.Test;
import org.rhq.core.domain.configuration.Configuration; @@ -46,7 +44,6 @@ public class ContentSourceTest extends AbstractEJB3Test { public void testInsert() throws Exception { getTransactionManager().begin(); try { - EntityManager em = getEntityManager();
ResourceType rt = new ResourceType("testCSResourceType", "testPlugin", ResourceCategory.PLATFORM, null); Resource resource = new Resource("testCSResource", "testCSResource", rt); @@ -71,8 +68,6 @@ public class ContentSourceTest extends AbstractEJB3Test { em.persist(cst); em.persist(cs); em.flush(); - //em.close(); - em = getEntityManager();
cs = em.find(ContentSource.class, cs.getId()); assert cs != null; @@ -93,8 +88,6 @@ public class ContentSourceTest extends AbstractEJB3Test { public void testNullSyncSchedule() throws Exception { getTransactionManager().begin(); try { - EntityManager em = getEntityManager(); - ResourceType rt = new ResourceType("testCSResourceType", "testPlugin", ResourceCategory.PLATFORM, null); Resource resource = new Resource("testCSResource", "testCSResource", rt); resource.setUuid("" + new Random().nextInt()); @@ -120,8 +113,6 @@ public class ContentSourceTest extends AbstractEJB3Test { em.persist(cst); em.persist(cs); em.flush(); - //em.close(); - em = getEntityManager();
cs = em.find(ContentSource.class, cs.getId()); assert cs != null; @@ -143,8 +134,6 @@ public class ContentSourceTest extends AbstractEJB3Test { // using empty strings to see that Oracle still behaves itself getTransactionManager().begin(); try { - EntityManager em = getEntityManager(); - ResourceType rt = new ResourceType("testCSResourceType", "testPlugin", ResourceCategory.PLATFORM, null); Resource resource = new Resource("testCSResource", "testCSResource", rt); resource.setUuid("" + new Random().nextInt()); @@ -170,8 +159,6 @@ public class ContentSourceTest extends AbstractEJB3Test { em.persist(cst); em.persist(cs); em.flush(); - //em.close(); - em = getEntityManager();
cs = em.find(ContentSource.class, cs.getId()); assert cs != null; diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDataAccessTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDataAccessTest.java index 7138416..083a756 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDataAccessTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDataAccessTest.java @@ -38,7 +38,14 @@ public class DriftDataAccessTest extends AbstractEJB3Test { executeInTransaction(false, new TransactionCallback() { @Override public void execute() throws Exception { - purgeDB(); + try { + purgeDB(); + + } catch (Exception e) { + System.out.println("BEFORE METHOD FAILURE, TEST DID NOT RUN!!!"); + e.printStackTrace(); + throw e; + } } }); } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDefinitionTemplateTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDefinitionTemplateTest.java index 9329ae6..49e4e26 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDefinitionTemplateTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftDefinitionTemplateTest.java @@ -52,9 +52,16 @@ public class DriftDefinitionTemplateTest extends DriftDataAccessTest { executeInTransaction(false, new TransactionCallback() { @Override public void execute() throws Exception { - purgeDB(); - createResourceType(); - em.persist(resourceType); + try { + purgeDB(); + createResourceType(); + em.persist(resourceType); + + } catch (Exception e) { + System.out.println("BEFORE METHOD FAILURE, TEST DID NOT RUN!!!"); + e.printStackTrace(); + throw e; + } } }); } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/JPADriftChangeSetTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/JPADriftChangeSetTest.java index 9d5248f..2709158 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/JPADriftChangeSetTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/JPADriftChangeSetTest.java @@ -64,18 +64,25 @@ public class JPADriftChangeSetTest extends DriftDataAccessTest { executeInTransaction(false, new TransactionCallback() { @Override public void execute() throws Exception { - purgeDB(); + try { + purgeDB();
- EntityManager em = getEntityManager(); + EntityManager em = getEntityManager(); + + resourceType = createResourceType(); + em.persist(resourceType);
- resourceType = createResourceType(); - em.persist(resourceType); + resource = createResource(resourceType);
- resource = createResource(resourceType); + definition = createDriftDefinition(); + resource.addDriftDefinition(definition); + getEntityManager().persist(resource);
- definition = createDriftDefinition(); - resource.addDriftDefinition(definition); - getEntityManager().persist(resource); + } catch (Exception e) { + System.out.println("BEFORE METHOD FAILURE, TEST DID NOT RUN!!!"); + e.printStackTrace(); + throw e; + } } }); } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/operation/OperationHistoryTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/operation/OperationHistoryTest.java index ff9b96c..34837a1 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/operation/OperationHistoryTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/operation/OperationHistoryTest.java @@ -24,7 +24,6 @@ package org.rhq.core.domain.operation;
import java.util.Random;
-import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.Query;
@@ -65,12 +64,11 @@ public class OperationHistoryTest extends AbstractEJB3Test {
@Test(groups = "integration.ejb3") public void testUpdate() throws Exception { - EntityManager em = getEntityManager(); getTransactionManager().begin(); try { - ResourceOperationHistory r1 = createIndividualResourceHistory(em); - GroupOperationHistory g1 = createGroupResourceHistory(em); - ResourceOperationHistory r2 = createGroupIndividualResourceHistory(em, g1); + ResourceOperationHistory r1 = createIndividualResourceHistory(); + GroupOperationHistory g1 = createGroupResourceHistory(); + ResourceOperationHistory r2 = createGroupIndividualResourceHistory(g1);
Configuration results = new Configuration(); results.put(new PropertySimple("exitCode", "1")); @@ -134,10 +132,9 @@ public class OperationHistoryTest extends AbstractEJB3Test {
@Test(groups = "integration.ejb3") public void testCreate() throws Exception { - EntityManager em = getEntityManager(); getTransactionManager().begin(); try { - ResourceOperationHistory r1 = createIndividualResourceHistory(em); + ResourceOperationHistory r1 = createIndividualResourceHistory();
Thread.sleep(100); // without sleeping, test goes so fast that the getDuration() is saying 0 assert r1.getId() > 0; @@ -160,7 +157,7 @@ public class OperationHistoryTest extends AbstractEJB3Test { assert r1.getSubjectName().equals("user"); assert r1.getStatus() == OperationRequestStatus.INPROGRESS;
- GroupOperationHistory g1 = createGroupResourceHistory(em); + GroupOperationHistory g1 = createGroupResourceHistory();
Thread.sleep(100); // without sleeping, test goes so fast that the getDuration() is saying 0 assert g1.getId() > 0; @@ -178,7 +175,7 @@ public class OperationHistoryTest extends AbstractEJB3Test { assert g1.getStatus() == OperationRequestStatus.INPROGRESS;
// the individual resource history that was part of a group execution - ResourceOperationHistory r2 = createGroupIndividualResourceHistory(em, g1); + ResourceOperationHistory r2 = createGroupIndividualResourceHistory(g1);
Thread.sleep(100); // without sleeping, test goes so fast that the getDuration() is saying 0 assert r2.getId() > 0; @@ -205,28 +202,24 @@ public class OperationHistoryTest extends AbstractEJB3Test {
@Test(groups = "integration.ejb3") public void testQueryByJobId() throws Exception { - EntityManager em; ResourceOperationHistory r1; GroupOperationHistory g1; ResourceOperationHistory r2;
getTransactionManager().begin(); - em = getEntityManager();
try { - r1 = createIndividualResourceHistory(em); - g1 = createGroupResourceHistory(em); - r2 = createGroupIndividualResourceHistory(em, g1); + r1 = createIndividualResourceHistory(); + g1 = createGroupResourceHistory(); + r2 = createGroupIndividualResourceHistory(g1); getTransactionManager().commit(); - em.close(); + } catch (Throwable t) { getTransactionManager().rollback(); - em.close(); throw new Exception(t); }
getTransactionManager().begin(); - em = getEntityManager();
ResourceOperationHistory r1_dup; GroupOperationHistory g1_dup; @@ -270,10 +263,8 @@ public class OperationHistoryTest extends AbstractEJB3Test { assert r2_dup.getStatus().equals(r2.getStatus()); } finally { getTransactionManager().rollback(); - em.close();
getTransactionManager().begin(); - em = getEntityManager();
r1 = em.find(ResourceOperationHistory.class, r1.getId()); em.remove(r1); @@ -281,21 +272,18 @@ public class OperationHistoryTest extends AbstractEJB3Test { em.remove(g1); // this should cascade and delete r2
getTransactionManager().commit(); - em.close();
try { // make sure our cascading on remove worked getTransactionManager().begin(); - em = getEntityManager(); assert em.find(ResourceOperationHistory.class, r2.getId()) == null; } finally { getTransactionManager().rollback(); - em.close(); } } }
- private ResourceOperationHistory createGroupIndividualResourceHistory(EntityManager em, GroupOperationHistory g1) { + private ResourceOperationHistory createGroupIndividualResourceHistory(GroupOperationHistory g1) { ResourceOperationHistory r2 = new ResourceOperationHistory("job3" + System.currentTimeMillis(), "group3", "user", newOperation, null, newResource, g1); r2.setStartedTime(); @@ -303,14 +291,14 @@ public class OperationHistoryTest extends AbstractEJB3Test { return r2; }
- private GroupOperationHistory createGroupResourceHistory(EntityManager em) { + private GroupOperationHistory createGroupResourceHistory() { GroupOperationHistory g1 = new GroupOperationHistory("job2" + System.currentTimeMillis(), "group2", "user", newOperation, null, newGroup); em.persist(g1); return g1; }
- private ResourceOperationHistory createIndividualResourceHistory(EntityManager em) { + private ResourceOperationHistory createIndividualResourceHistory() { ResourceOperationHistory r1 = new ResourceOperationHistory("job1" + System.currentTimeMillis(), "group1", "user", newOperation, null, newResource, null); r1.setStartedTime(); @@ -320,37 +308,32 @@ public class OperationHistoryTest extends AbstractEJB3Test {
private Resource createNewResource() throws Exception { getTransactionManager().begin(); - EntityManager em = getEntityManager(); - Resource resource;
try { - try { - ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test", - ResourceCategory.PLATFORM, null); + ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test", + ResourceCategory.PLATFORM, null);
- OperationDefinition def = new OperationDefinition(resourceType, "testOp"); - def.setTimeout(1); - resourceType.addOperationDefinition(def); + OperationDefinition def = new OperationDefinition(resourceType, "testOp"); + def.setTimeout(1); + resourceType.addOperationDefinition(def);
- em.persist(resourceType); + em.persist(resourceType);
- resource = new Resource("key" + System.currentTimeMillis(), "name", resourceType); - resource.setUuid("" + new Random().nextInt()); - em.persist(resource); + resource = new Resource("key" + System.currentTimeMillis(), "name", resourceType); + resource.setUuid("" + new Random().nextInt()); + em.persist(resource);
- ResourceGroup group = new ResourceGroup("testgroupOH" + System.currentTimeMillis(), resourceType); - em.persist(group); - group.addExplicitResource(resource); - } catch (Exception e) { - System.out.println(e); - getTransactionManager().rollback(); - throw e; - } + ResourceGroup group = new ResourceGroup("testgroupOH" + System.currentTimeMillis(), resourceType); + em.persist(group); + group.addExplicitResource(resource);
getTransactionManager().commit(); - } finally { - em.close(); + + } catch (Exception e) { + System.out.println(e); + getTransactionManager().rollback(); + throw e; }
return resource; @@ -359,7 +342,7 @@ public class OperationHistoryTest extends AbstractEJB3Test { private void deleteNewResource(Resource resource) throws Exception { if (resource != null) { getTransactionManager().begin(); - EntityManager em = getEntityManager(); + try { ResourceType type = em.find(ResourceType.class, resource.getResourceType().getId()); Resource res = em.find(Resource.class, resource.getId()); @@ -382,8 +365,6 @@ public class OperationHistoryTest extends AbstractEJB3Test { }
throw e; - } finally { - em.close(); } } } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ProblemResourceTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ProblemResourceTest.java index c836632..4d3c471 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ProblemResourceTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ProblemResourceTest.java @@ -344,7 +344,6 @@ public class ProblemResourceTest extends AbstractEJB3Test { SystemException { entityManager.flush(); getTransactionManager().commit(); - entityManager.close(); }
private void begin() throws NotSupportedException, SystemException { diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java index a6e2eba..ac73f49 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java @@ -25,7 +25,6 @@ package org.rhq.core.domain.resource.test; import java.util.List; import java.util.Random;
-import javax.persistence.EntityManager; import javax.persistence.Query;
import org.testng.annotations.Test; @@ -54,7 +53,6 @@ public class ResourceErrorTest extends AbstractEJB3Test {
public void testCreateErrors() throws Exception { getTransactionManager().begin(); - EntityManager em = getEntityManager();
try { ResourceError re; @@ -97,7 +95,6 @@ public class ResourceErrorTest extends AbstractEJB3Test { assert q.getResultList().size() == 2; } finally { getTransactionManager().rollback(); - em.close(); } }
@@ -108,7 +105,6 @@ public class ResourceErrorTest extends AbstractEJB3Test { List<ResourceError> errors;
getTransactionManager().begin(); - EntityManager em = getEntityManager();
try { q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID); @@ -141,34 +137,29 @@ public class ResourceErrorTest extends AbstractEJB3Test {
} finally { getTransactionManager().rollback(); - em.close(); } }
private Resource createNewResource() throws Exception { getTransactionManager().begin(); - EntityManager em = getEntityManager();
Resource resource;
try { - try { - ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test", - ResourceCategory.PLATFORM, null); - em.persist(resourceType); - resource = new Resource("key" + System.currentTimeMillis(), "name", resourceType); - resource.setUuid("" + new Random().nextInt()); - em.persist(resource); - System.out.println("Created resource with id " + resource.getId()); - } catch (Exception e) { - System.out.println(e); - getTransactionManager().rollback(); - throw e; - } + ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test", + ResourceCategory.PLATFORM, null); + em.persist(resourceType); + resource = new Resource("key" + System.currentTimeMillis(), "name", resourceType); + resource.setUuid("" + new Random().nextInt()); + em.persist(resource); + System.out.println("Created resource with id " + resource.getId());
getTransactionManager().commit(); - } finally { - em.close(); + + } catch (Exception e) { + System.out.println(e); + getTransactionManager().rollback(); + throw e; }
return resource; @@ -177,7 +168,7 @@ public class ResourceErrorTest extends AbstractEJB3Test { private void deleteNewResource(Resource resource) throws Exception { if (resource != null) { getTransactionManager().begin(); - EntityManager em = getEntityManager(); + try { ResourceType type = em.find(ResourceType.class, resource.getResourceType().getId()); Resource res = em.find(Resource.class, resource.getId()); @@ -197,8 +188,6 @@ public class ResourceErrorTest extends AbstractEJB3Test { }
throw e; - } finally { - em.close(); } } } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceGroupTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceGroupTest.java index be2875d..60caec0 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceGroupTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceGroupTest.java @@ -24,8 +24,6 @@ package org.rhq.core.domain.resource.test;
import java.util.Random;
-import javax.persistence.EntityManager; - import org.testng.annotations.Test;
import org.rhq.core.domain.measurement.Availability; @@ -80,11 +78,8 @@ public class ResourceGroupTest extends AbstractEJB3Test {
private Resource createNewResource() throws Exception { getTransactionManager().begin(); - EntityManager em = getEntityManager(); - Resource resource;
- try { try { ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test", ResourceCategory.PLATFORM, null); @@ -97,24 +92,22 @@ public class ResourceGroupTest extends AbstractEJB3Test { ResourceGroup group = new ResourceGroup("testgroupRG" + System.currentTimeMillis(), resourceType); em.persist(group); group.addExplicitResource(resource); + + getTransactionManager().commit(); + } catch (Exception e) { System.out.println(e); getTransactionManager().rollback(); throw e; }
- getTransactionManager().commit(); - } finally { - em.close(); - } - return resource; }
private void deleteNewResource(Resource resource) throws Exception { if (resource != null) { getTransactionManager().begin(); - EntityManager em = getEntityManager(); + try { ResourceType type = em.find(ResourceType.class, resource.getResourceType().getId()); Resource res = em.find(Resource.class, resource.getId()); @@ -137,8 +130,6 @@ public class ResourceGroupTest extends AbstractEJB3Test { }
throw e; - } finally { - em.close(); } } } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java b/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java index d0942b1..4eff131 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java @@ -1,6 +1,7 @@ package org.rhq.core.domain.test;
import java.io.File; +import java.lang.reflect.Method; import java.util.Collection; import java.util.Date; import java.util.HashSet; @@ -16,6 +17,7 @@ import javax.persistence.PersistenceContext; import javax.transaction.TransactionManager;
import org.testng.AssertJUnit; +import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod;
@@ -58,23 +60,8 @@ public abstract class AbstractEJB3Test extends Arquillian { @Deployment protected static EnterpriseArchive getBaseDeployment() {
- // depending on the db in use, set up the necessary datasource - String dialect = System.getProperty("hibernate.dialect"); - if (dialect == null) { - System.out.println("!!! hibernate.dialect is not set! Assuming you want to test on postgres"); - dialect = "postgres"; - } - - String dataSourceXml; - if (dialect.toLowerCase().contains("postgres")) { - dataSourceXml = "jbossas-postgres-ds.xml"; - } else { - dataSourceXml = "jbossas-oracle-ds.xml"; - } - // Create the domain jar which will subsequently be packaged in the ear deployment JavaArchive ejbJar = ShrinkWrap.create(JavaArchive.class, "rhq-core-domain-ejb3.jar") // - .addAsManifestResource(dataSourceXml) // the datasource .addAsManifestResource("ejb-jar.xml") // the empty ejb jar descriptor .addAsManifestResource("test-persistence.xml", "persistence.xml") // the test persistence context .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml") // add CDI injection (needed by arquillian injection) @@ -213,12 +200,20 @@ public abstract class AbstractEJB3Test extends Arquillian { * and {@link #inContainer()} call. */ @BeforeMethod - protected void __beforeMethod() throws Exception { + protected void __beforeMethod(Method method) throws Throwable { // Note that Arquillian calls the testng BeforeMethod twice (as of 1.0.2.Final, once // out of container and once in container. In general the expectation is to execute it // one time, and doing it in container allows for the expected injections and context. if (inContainer()) { - beforeMethod(); + try { + beforeMethod(); + + } catch (Throwable t) { + // Arquillian is eating these, make sure they show up in some way + System.out.println("BEFORE METHOD FAILURE, TEST DID NOT RUN!!! [" + method.getName() + "]"); + t.printStackTrace(); + throw t; + } } }
@@ -229,9 +224,18 @@ public abstract class AbstractEJB3Test extends Arquillian { * Instead, override {@link #afterMethod()}. */ @AfterMethod(alwaysRun = true) - protected void __afterMethod() throws Exception { - // currently no special handling necessary - afterMethod(); + protected void __afterMethod(ITestResult result, Method method) throws Throwable { + try { + if (inContainer()) { + afterMethod(); + } + } catch (Throwable t) { + System.out + .println("AFTER METHOD FAILURE, TEST CLEAN UP FAILED!!! MAY NEED TO CLEAN DB BEFORE RUNNING MORE TESTS! [" + + method.getName() + "]"); + t.printStackTrace(); + throw t; + } }
protected boolean inContainer() { diff --git a/modules/core/domain/src/test/resources/jbossas-oracle-ds.xml b/modules/core/domain/src/test/resources/jbossas-oracle-ds.xml deleted file mode 100644 index 8906dca..0000000 --- a/modules/core/domain/src/test/resources/jbossas-oracle-ds.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<datasources xmlns="http://www.jboss.org/ironjacamar/schema" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd%22%3E - - <xa-datasource jndi-name="java:jboss/datasources/RHQDS" pool-name="RHQDS" enabled="true" use-java-context="true"> - - <xa-datasource-property name="URL">${rhq.test.ds.connection-url}</xa-datasource-property> - <xa-datasource-property name="ConnectionProperties">SetBigStringTryClob=true</xa-datasource-property> - <driver>oracle</driver> - <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> - <xa-pool> - <min-pool-size>5</min-pool-size> - <max-pool-size>50</max-pool-size> - <is-same-rm-override>false</is-same-rm-override> - <no-tx-separate-pools /> - </xa-pool> - <security> - <security-domain>RHQDSSecurityDomain</security-domain> - </security> - <validation> - <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleValidConnectionChecker" /> - <stale-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleStaleConnectionChecker" /> - <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.oracle.OracleExceptionSorter" /> - </validation> - <timeout> - <blocking-timeout-millis>30000</blocking-timeout-millis> - <idle-timeout-minutes>15</idle-timeout-minutes> - </timeout> - <statement> - <prepared-statement-cache-size>75</prepared-statement-cache-size> - </statement> - </xa-datasource> - -</datasources> \ No newline at end of file diff --git a/modules/core/domain/src/test/resources/jbossas-postgres-ds.xml b/modules/core/domain/src/test/resources/jbossas-postgres-ds.xml deleted file mode 100644 index 23db62c..0000000 --- a/modules/core/domain/src/test/resources/jbossas-postgres-ds.xml +++ /dev/null @@ -1,40 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<datasources - xmlns="http://www.jboss.org/ironjacamar/schema" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation=" - http://www.jboss.org/ironjacamar/schema - http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd%22%3E - - <xa-datasource - jndi-name="java:jboss/datasources/RHQDS" - pool-name="RHQDS" - enabled="true" - use-java-context="true"> - - <xa-datasource-property name="DatabaseName">${rhq.test.ds.db-name}</xa-datasource-property> - <xa-datasource-property name="PortNumber">${rhq.test.ds.port}</xa-datasource-property> - <xa-datasource-property name="ServerName">${rhq.test.ds.server-name}</xa-datasource-property> - <driver>postgres</driver> - <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> - <xa-pool> - <min-pool-size>5</min-pool-size> - <max-pool-size>50</max-pool-size> - </xa-pool> - <security> - <security-domain>RHQDSSecurityDomain</security-domain> - </security> - <validation> - <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker" /> - <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter" /> - </validation> - <timeout> - <blocking-timeout-millis>30000</blocking-timeout-millis> - <idle-timeout-minutes>15</idle-timeout-minutes> - </timeout> - <statement> - <prepared-statement-cache-size>75</prepared-statement-cache-size> - </statement> - </xa-datasource> - -</datasources> \ No newline at end of file diff --git a/modules/enterprise/server/itests-2/pom.xml b/modules/enterprise/server/itests-2/pom.xml index cc9c941..c0c420e 100644 --- a/modules/enterprise/server/itests-2/pom.xml +++ b/modules/enterprise/server/itests-2/pom.xml @@ -575,7 +575,6 @@ </datasource> <xa-datasource jta="true" jndi-name="java:jboss/datasources/RHQDS" pool-name="RHQDS" enabled="true" use-java-context="true"> <xa-datasource-property name="URL">${rhq.test.ds.connection-url}</xa-datasource-property> - <xa-datasource-property name="ConnectionProperties">SetBigStringTryClob=true</xa-datasource-property> <driver>oracle</driver> <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation> <xa-pool>
commit 2249a73ebf553242ca37276d8a9d4179e00050a8 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Dec 10 18:23:57 2012 +0100
Code coverage support for Arquillian-based tests.
diff --git a/modules/core/arquillian-integration/container/src/test/resources/arquillian.xml b/modules/core/arquillian-integration/container/src/test/resources/arquillian.xml index 930603f..3bf9e46 100644 --- a/modules/core/arquillian-integration/container/src/test/resources/arquillian.xml +++ b/modules/core/arquillian-integration/container/src/test/resources/arquillian.xml @@ -26,4 +26,11 @@ </configuration> </container> </group> -</arquillian> \ No newline at end of file + + <!-- We actually have to exclude all the classes from instrumentation by Arquillian Jacoco extension, because our + Arquillian RHQ agent plugin extension only runs in-process with the test execution that does the Jacoco instrumentation, too. --> + <extension qualifier="jacoco"> + <property name="excludes">*</property> + </extension> + +</arquillian> diff --git a/modules/core/domain/src/test/resources/arquillian.xml b/modules/core/domain/src/test/resources/arquillian.xml index 55e8021..368ce23 100644 --- a/modules/core/domain/src/test/resources/arquillian.xml +++ b/modules/core/domain/src/test/resources/arquillian.xml @@ -23,4 +23,9 @@ <property name="jbossHome">${jboss.unzip.location}</property> </configuration> </container> + + <extension qualifier="jacoco"> + <property name="includes">org.rhq.*</property> + </extension> + </arquillian> diff --git a/modules/core/plugin-container-itest/src/test/resources/arquillian.xml b/modules/core/plugin-container-itest/src/test/resources/arquillian.xml index 964e07e..a2dd2f3 100644 --- a/modules/core/plugin-container-itest/src/test/resources/arquillian.xml +++ b/modules/core/plugin-container-itest/src/test/resources/arquillian.xml @@ -38,4 +38,10 @@ </container> </group>
-</arquillian> \ No newline at end of file + <!-- We actually have to exclude all the classes from instrumentation by Arquillian Jacoco extension, because our + Arquillian RHQ agent plugin extension only runs in-process with the test execution that does the Jacoco instrumentation, too. --> + <extension qualifier="jacoco"> + <property name="excludes">*</property> + </extension> + +</arquillian> diff --git a/modules/enterprise/server/itests-2/src/test/resources/arquillian.xml b/modules/enterprise/server/itests-2/src/test/resources/arquillian.xml index c1dcf1b..b32c647 100644 --- a/modules/enterprise/server/itests-2/src/test/resources/arquillian.xml +++ b/modules/enterprise/server/itests-2/src/test/resources/arquillian.xml @@ -15,6 +15,10 @@ <property name="deploymentClass">org.rhq.enterprise.server.test.AbstractEJB3Test</property> </extension>
+ <extension qualifier="jacoco"> + <property name="includes">org.rhq.*</property> + </extension> + <container qualifier="RHQAS7" default="true"> diff --git a/modules/integration-tests/jndi-access/jndi-access-test/src/test/resources/arquillian.xml b/modules/integration-tests/jndi-access/jndi-access-test/src/test/resources/arquillian.xml index da392c2..23502f1 100644 --- a/modules/integration-tests/jndi-access/jndi-access-test/src/test/resources/arquillian.xml +++ b/modules/integration-tests/jndi-access/jndi-access-test/src/test/resources/arquillian.xml @@ -9,5 +9,9 @@ <property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m -Djava.security.manager -Djava.security.policy==${jboss.unzip.location}/security.policy -Djnp.port=${jnp.port}</property> </configuration> </container> + + <extension qualifier="jacoco"> + <property name="includes">org.rhq.*</property> + </extension>
-</arquillian> \ No newline at end of file +</arquillian> diff --git a/modules/plugins/jboss-as-5/src/test/resources/itest/arquillian.xml b/modules/plugins/jboss-as-5/src/test/resources/itest/arquillian.xml index 9ac2ece..8ae2d8c 100644 --- a/modules/plugins/jboss-as-5/src/test/resources/itest/arquillian.xml +++ b/modules/plugins/jboss-as-5/src/test/resources/itest/arquillian.xml @@ -15,4 +15,9 @@ </configuration> </container>
+ <!-- We actually have to exclude all the classes from instrumentation by Arquillian Jacoco extension, because our + Arquillian RHQ agent plugin extension only runs in-process with the test execution that does the Jacoco instrumentation, too. --> + <extension qualifier="jacoco"> + <property name="excludes">*</property> + </extension> </arquillian> diff --git a/modules/plugins/jboss-as-7/src/test/resources/itest/arquillian.xml b/modules/plugins/jboss-as-7/src/test/resources/itest/arquillian.xml index b88a367..0fec6c8 100644 --- a/modules/plugins/jboss-as-7/src/test/resources/itest/arquillian.xml +++ b/modules/plugins/jboss-as-7/src/test/resources/itest/arquillian.xml @@ -15,4 +15,9 @@ </configuration> </container>
+ <!-- We actually have to exclude all the classes from instrumentation by Arquillian Jacoco extension, because our + Arquillian RHQ agent plugin extension only runs in-process with the test execution that does the Jacoco instrumentation, too. --> + <extension qualifier="jacoco"> + <property name="excludes">*</property> + </extension> </arquillian> diff --git a/pom.xml b/pom.xml index afef562..a0f6cce 100644 --- a/pom.xml +++ b/pom.xml @@ -232,6 +232,7 @@ <intentional-api-changes-file>intentional-api-changes-since-${signature-check-base-version}.xml</intentional-api-changes-file>
<jacoco.version>0.6.0.201210061924</jacoco.version> + <jacoco-arquillian-extension.version>1.0.0.Alpha5</jacoco-arquillian-extension.version> </properties>
@@ -618,7 +619,18 @@ <scope>import</scope> </dependency>
- </dependencies> + <dependency> + <groupId>org.jboss.arquillian.extension</groupId> + <artifactId>arquillian-jacoco</artifactId> + <version>${jacoco-arquillian-extension.version}</version> + </dependency> + + <dependency> + <groupId>org.jacoco</groupId> + <artifactId>org.jacoco.core</artifactId> + <version>${jacoco.version}</version> + </dependency> + </dependencies>
</dependencyManagement>
@@ -1304,7 +1316,7 @@
<!-- This profile is the "opposite" of the code coverage profile and provides default values for properties that are set in the code-coverage profile - to kick of jacoco java agent. --> + to kick of jacoco java agent. --> <profile> <id>no-code-coverage</id> <activation> @@ -1326,6 +1338,21 @@ <name>code-coverage</name> </property> </activation> + + <dependencies> + <dependency> + <groupId>org.jboss.arquillian.extension</groupId> + <artifactId>arquillian-jacoco</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jacoco</groupId> + <artifactId>org.jacoco.core</artifactId> + <scope>test</scope> + </dependency> + </dependencies> + <build> <plugins> <!-- This definition creates the 2 independent coverage reports -
commit 4021b2c0e0466a5e3e0ac31426340af0268909c2 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Dec 10 13:51:50 2012 +0100
Removing the SecurityActions for obtaining a logger instance during class initialization.
The standard script permissions include a permission for that so no special code has to exist in the normal codebase.
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java index 3a7d046..184e08e 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java @@ -23,12 +23,9 @@ import java.io.FilePermission; import java.io.SerializablePermission; import java.lang.reflect.ReflectPermission; import java.net.SocketPermission; -import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; -import java.security.ProtectionDomain; -import java.security.cert.Certificate; import java.util.Enumeration; import java.util.PropertyPermission; import java.util.logging.LoggingPermission; @@ -99,6 +96,7 @@ public class StandardScriptPermissions extends PermissionCollection { //we don't consider the scripts malevolent. add(new PrivateCredentialPermission("* * "*"", "read"));
+ //adding this so that new classes with loggers can be initialized. add(new LoggingPermission("control", null)); }
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java index 3b993a8..3bf4729 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java @@ -24,8 +24,8 @@ import javassist.util.proxy.ProxyFactory; import javax.jws.WebParam;
import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory;
-import org.rhq.bindings.security.SecurityActions; import org.rhq.bindings.util.ConfigurationClassBuilder; import org.rhq.bindings.util.ResourceTypeFingerprint; import org.rhq.core.domain.resource.ResourceCreationDataType; @@ -42,7 +42,7 @@ public class ResourceClientFactory { public Class<?> iface; }
- private static final Log LOG = SecurityActions.getLog(ResourceClientFactory.class); + private static final Log LOG = LogFactory.getLog(ResourceClientFactory.class);
//keys are resource type ids private static HashMap<Integer, CacheRecord> CUSTOM_CLASS_CACHE = new HashMap<Integer, CacheRecord>(); diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java index 1b71678..7361fe8 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java @@ -32,8 +32,8 @@ import java.util.Set; import javassist.util.proxy.MethodHandler;
import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory;
-import org.rhq.bindings.security.SecurityActions; import org.rhq.bindings.util.ConfigurationClassBuilder; import org.rhq.bindings.util.LazyLoadScenario; import org.rhq.bindings.util.ResourceTypeFingerprint; @@ -84,7 +84,7 @@ import org.rhq.enterprise.server.resource.ResourceTypeNotFoundException; */ public class ResourceClientProxy {
- private static final Log LOG = SecurityActions.getLog(ResourceClientProxy.class); + private static final Log LOG = LogFactory.getLog(ResourceClientProxy.class);
private ResourceClientFactory proxyFactory; private RhqFacade remoteClient; diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java index 4d33fb2..2a1f944 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java @@ -28,10 +28,10 @@ import java.nio.charset.Charset; import java.util.List;
import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory;
import org.rhq.bindings.StandardBindings; import org.rhq.bindings.client.RhqFacade; -import org.rhq.bindings.security.SecurityActions; import org.rhq.core.domain.content.Repo; import org.rhq.core.domain.content.composite.PackageAndLatestVersionComposite; import org.rhq.core.domain.criteria.PackageCriteria; @@ -53,7 +53,7 @@ import org.rhq.enterprise.server.content.RepoManagerRemote; public class RepoScriptSourceProvider extends BaseRhqSchemeScriptSourceProvider implements StandardBindings.RhqFacadeChangeListener {
- private static final Log LOG = SecurityActions.getLog(RepoScriptSourceProvider.class); + private static final Log LOG = LogFactory.getLog(RepoScriptSourceProvider.class);
private static final String AUTHORITY = "repositories";
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java deleted file mode 100644 index cdde2ff..0000000 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * RHQ Management Platform - * Copyright 2012, Red Hat Middleware LLC, and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.bindings.security; - -import java.security.AccessController; -import java.security.PrivilegedAction; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Lukas Krejci - * - */ -public class SecurityActions { - - private SecurityActions() { - - } - - public static Log getLog(final Class<?> cls) { - return AccessController.doPrivileged(new PrivilegedAction<Log>() { - @Override - public Log run() { - return LogFactory.getLog(cls); - }; - }); - } - - public static Log getLog(final String name) { - return AccessController.doPrivileged(new PrivilegedAction<Log>() { - @Override - public Log run() { - return LogFactory.getLog(name); - }; - }); - } -} diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java index d2724d1..8ce7bc6 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java @@ -52,8 +52,8 @@ import javassist.bytecode.annotation.ShortMemberValue; import javassist.bytecode.annotation.StringMemberValue;
import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory;
-import org.rhq.bindings.security.SecurityActions; import org.rhq.core.domain.auth.Subject;
/** @@ -64,7 +64,7 @@ import org.rhq.core.domain.auth.Subject; * @author Lukas Krejci */ public class InterfaceSimplifier { - private static final Log LOG = SecurityActions.getLog(InterfaceSimplifier.class); + private static final Log LOG = LogFactory.getLog(InterfaceSimplifier.class);
private InterfaceSimplifier() {
commit e04317bc66733a72b68444b8d7833106078afd66 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Dec 10 13:20:44 2012 +0100
Removing the obsolete javaURLContextFactory from the server/jar. It was a left-over from a failed attempt at securing the JNDI look up in a saner way than we do now.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java deleted file mode 100644 index fc4d02b..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.rhq.enterprise.server.naming.interfaces.java; - -import java.util.Hashtable; - -import javax.naming.CompositeName; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.spi.ObjectFactory; - -import org.jboss.as.naming.NamingContext; - -import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; - -/** @deprecated this is not used after all */ -@Deprecated -public class javaURLContextFactory implements ObjectFactory { - - private static final AllowRhqServerInternalsAccessPermission PERM = new AllowRhqServerInternalsAccessPermission(); - - @Override - @SuppressWarnings("unchecked") - public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) - throws Exception { - - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(PERM); - } - - return new NamingContext(name != null ? name : new CompositeName(""), (Hashtable<String, Object>) environment); - } -}
commit 1cdbda29cabe38a9acf7057f5d1457f508fca27b Author: Thomas SEGISMONT tsegismo@redhat.com Date: Mon Dec 10 10:20:00 2012 +0100
Bug 858138 rhq-agent-env.sh gives example of bad su command
-l overrides -m behavior in RHQ_AGENT_START_COMMAND example
diff --git a/modules/enterprise/agent/src/etc/rhq-agent-env.sh b/modules/enterprise/agent/src/etc/rhq-agent-env.sh index c7a259e..4fa4311 100755 --- a/modules/enterprise/agent/src/etc/rhq-agent-env.sh +++ b/modules/enterprise/agent/src/etc/rhq-agent-env.sh @@ -156,8 +156,8 @@ # some special string manipulation to get the # agent script to start. See below for an # example of how to do this. -#RHQ_AGENT_START_COMMAND="su -m -l user -c '${RHQ_AGENT_HOME}/bin/rhq-agent.sh'" -#RHQ_AGENT_START_COMMAND="su -m -l user -c '$(echo ${RHQ_AGENT_HOME}|sed 's/ /\ /')/bin/rhq-agent.sh'" +#RHQ_AGENT_START_COMMAND="su -m user -c '${RHQ_AGENT_HOME}/bin/rhq-agent.sh'" +#RHQ_AGENT_START_COMMAND="su -m user -c '$(echo ${RHQ_AGENT_HOME}|sed 's/ /\ /')/bin/rhq-agent.sh'"
# RHQ_AGENT_PASSWORD_PROMPT - if "true", this indicates that the user # that is to run the agent must type the
commit e9c7ed2d9845308b549b437fc9bcd368ee44c04b Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 15:07:30 2012 -0500
container-lib module went away
diff --git a/.classpath b/.classpath index b67aafb..d8e11f6 100644 --- a/.classpath +++ b/.classpath @@ -68,7 +68,6 @@ <classpathentry kind="src" path="modules/enterprise/server/safe-invoker/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/startup-subsystem/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/startup-subsystem/src/test/java"/> - <classpathentry kind="src" path="modules/enterprise/server/container-lib/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/ant-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/filetemplate-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/alert-subject/src/main/java"/>
commit bdc8d78f4ee918c38bff6a6ce2c1ed12ff91977b Merge: 5d8fa1c dddf788 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 13:48:45 2012 -0500
Merge remote-tracking branch 'origin/master' into rhq-on-as7
Conflicts: modules/enterprise/pom.xml modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java modules/enterprise/server/jar/pom.xml modules/enterprise/server/pom.xml modules/pom.xml
diff --cc modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java index 5dcf8c3,fabe6ae..e831a2b --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java @@@ -46,10 -47,24 +47,25 @@@ import org.rhq.enterprise.server.util.L * * @author Lukas Krejci */ -@Test +@Test(enabled = false) +// TODO JNDI: reenable after fixing secure jndi lookups public class JndiAccessTest extends AbstractEJB3Test {
+ public void testScriptCantOverrideSystemProperties() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); + + ScriptEngine engine = getEngine(overlord); + + try { + engine.eval("java.lang.System.setProperty('java.naming.factory.url.pkgs', 'counterfeit');"); + } catch (ScriptException e) { + Assert.assertTrue( + e.getMessage().contains( + "access denied ("java.util.PropertyPermission" "java.naming.factory.url.pkgs" "write")"), + "The script shouldn't have write access to the system properties."); + } + } + public void testEjbsAccessibleThroughPrivilegedCode() { LookupUtil.getSubjectManager().getOverlord(); }
commit 5d8fa1c9ac674c33f57c72c75c1b316d3454b645 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 13:41:35 2012 -0500
trivial comment change
diff --git a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml index 55aca3d..47dd0d5 100644 --- a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml +++ b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml @@ -598,7 +598,7 @@ rhq.sync.endpoint-address=false </copy> <echo>Putting a developer setting in rhq-server.properties to turn on/off strict agent update version checking</echo> <echo file="${project.build.outputDirectory}/bin/rhq-server.properties" append="true">rhq.server.agent-update.nonstrict-version-check=true</echo> - <echo>Add auto-installer to rhq-server.sh script so developers don't have to run the installer in a separate step</echo> + <echo>Add auto-installer to rhq-server scripts so developers don't have to run the installer in a separate step</echo> <replace file="${project.build.outputDirectory}/bin/rhq-server.sh"> <replacefilter> <replacetoken># START SERVER</replacetoken>
commit dc9c35393d9b7be9804be4755fe7d817a2e6fbde Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 13:39:24 2012 -0500
give alittle luv to our brethern developers running on windows
diff --git a/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.bat b/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.bat index f15298c..1811564 100644 --- a/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.bat +++ b/modules/enterprise/server/appserver/src/main/bin-resources/bin/rhq-server.bat @@ -170,6 +170,7 @@ if defined RHQ_SERVER_RUN_AS set _WRAPPER_NTSERVICE_ACCOUNT="wrapper.ntservice.a if defined RHQ_SERVER_RUN_AS_ME set _WRAPPER_NTSERVICE_ACCOUNT="wrapper.ntservice.account=.%USERNAME%"
if /i "%1"=="console" ( + rem START SERVER "%RHQ_SERVER_WRAPPER_EXE_FILE_PATH%" -c "%RHQ_SERVER_WRAPPER_CONF_FILE_PATH%" "set.RHQ_SERVER_HOME=%RHQ_SERVER_HOME%" "set.RHQ_SERVER_INSTANCE_NAME=%RHQ_SERVER_INSTANCE_NAME%" "set.RHQ_SERVER_JAVA_EXE_FILE_PATH=%RHQ_SERVER_JAVA_EXE_FILE_PATH%" "set.RHQ_SERVER_OS_PLATFORM=%RHQ_SERVER_OS_PLATFORM%" "set.RHQ_SERVER_WRAPPER_LOG_DIR_PATH=%RHQ_SERVER_WRAPPER_LOG_DIR_PATH%" %_WRAPPER_NTSERVICE_ACCOUNT% %_DEBUG_OPTS% goto done ) diff --git a/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat new file mode 100644 index 0000000..b756b31 --- /dev/null +++ b/modules/enterprise/server/appserver/src/main/dev-resources/bin/rhq-autoinstall.bat @@ -0,0 +1,41 @@ +@echo off +setlocal + +set RHQ_SERVER_BIN_DIR_PATH=%~dp0 +if not defined RHQ_SERVER_HOME ( + cd "%RHQ_SERVER_BIN_DIR_PATH%.." +) else ( + cd "%RHQ_SERVER_HOME%" || ( + echo Cannot go to the RHQ_SERVER_HOME directory: %RHQ_SERVER_HOME% + exit /B 1 + ) +) +set RHQ_SERVER_HOME=%CD% +cd %RHQ_SERVER_HOME%\bin + +set _INSTALLER_SCRIPT=%RHQ_SERVER_HOME%\bin\rhq-installer.bat + +rem we are normally executed just before the server starts, so give it time to initialize +rem yes, this is a sleep of 5s, backwards compatible to XP +ping 127.0.0.1 -n 5 -w 1000 > nul + +for /L %%i in (1,1,5) do ( + echo Running Installer Now... + CALL "%_INSTALLER_SCRIPT%" + if ERRORLEVEL 2 ( + echo Installer failed - will try again in a few seconds + ping 127.0.0.1 -n 5 -w 1000 > nul + ) else ( + if ERRORLEVEL 1 ( + echo The installer has been disabled - please fix rhq-server.properties + goto :done + ) else ( + echo Installer finished + goto :done + ) + ) +) +echo Aborting installation - installer failed. + +:done +endlocal \ No newline at end of file diff --git a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml index 25a2916..55aca3d 100644 --- a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml +++ b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml @@ -605,6 +605,12 @@ rhq.sync.endpoint-address=false <replacevalue><![CDATA[export RHQ_SERVER_HOME; ${RHQ_SERVER_HOME}/bin/rhq-autoinstall.sh &]]></replacevalue> </replacefilter> </replace> + <replace file="${project.build.outputDirectory}/bin/rhq-server.bat"> + <replacefilter> + <replacetoken>rem START SERVER</replacetoken> + <replacevalue><![CDATA[start /B %RHQ_SERVER_HOME%\bin\rhq-autoinstall.bat]]></replacevalue> + </replacefilter> + </replace> </target>
<!-- The prepare-release target must be run AFTER the resources:resources goal has executed. -->
commit dddf7884e2a8bea735a4a68733edd778bd01b727 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 7 18:20:16 2012 +0100
BZ 885169 - explicitly prepend /rest/ as some browsers may misunderstand relative links.
diff --git a/modules/enterprise/server/jar/src/main/resources/rest_templates/index.ftl b/modules/enterprise/server/jar/src/main/resources/rest_templates/index.ftl index e135ce6..3ffdca3 100644 --- a/modules/enterprise/server/jar/src/main/resources/rest_templates/index.ftl +++ b/modules/enterprise/server/jar/src/main/resources/rest_templates/index.ftl @@ -35,7 +35,7 @@ mobile client (Android) of the API. <ul> <#list var as var> <li> - <a href="${var.href}">${var.rel}</a> + <a href="/rest/${var.href}">${var.rel}</a> </li> </#list> </ul>
commit 7ab6fc4ed78085304ea1a243758369c93ca1b1dc Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Dec 7 12:13:17 2012 -0500
API checker work for latest release, post rhq-on-as7 merge - Add latest intentional API changes files - Resolve some maven complaints - Add server/jar includes to check goal in pom
diff --git a/modules/core/domain/intentional-api-changes-since-4.5.1.xml b/modules/core/domain/intentional-api-changes-since-4.5.1.xml new file mode 100644 index 0000000..ff10f26 --- /dev/null +++ b/modules/core/domain/intentional-api-changes-since-4.5.1.xml @@ -0,0 +1,21 @@ +<?xml version="1.0"?> +<differences> + <difference> + <className>org/rhq/core/domain/configuration/definition/PropertyDefinitionMap</className> + <differenceType>7006</differenceType><!-- method return type changed --> + <method>java.util.List getPropertyDefinitions()</method> + <to>java.util.Map</to> + <justification> + We are reverting back to the previous signature for this method, correcting the prior change + that broke API compatibility. + </justification> + </difference> + <difference> + <className>org/rhq/core/domain/criteria/MeasurementScheduleCriteria</className> + <differenceType>6011</differenceType><!-- removed constant field --> + <field>SORT_FIELD_*</field> + <justification> + A few sort specifiers that were actually in error and if used would have produced a downstream error. + </justification> + </difference> +</differences> diff --git a/modules/enterprise/server/jar/intentional-api-changes-since-4.5.1.xml b/modules/enterprise/server/jar/intentional-api-changes-since-4.5.1.xml new file mode 100644 index 0000000..c7a95dd --- /dev/null +++ b/modules/enterprise/server/jar/intentional-api-changes-since-4.5.1.xml @@ -0,0 +1,24 @@ +<?xml version="1.0"?> +<differences> + <difference> + <className>**/WebservicesRemote</className> + <differenceType>8001</differenceType> <!-- class removed --> + <justification>Removed already deprecated web services in this release</justification> + </difference> + <difference> + <className>**/WebServiceTestRemote</className> + <differenceType>8001</differenceType> <!-- class removed --> + <justification>Removed already deprecated web services in this release</justification> + </difference> + <difference> + <className>**/RemoteWsInvocationHandler</className> + <differenceType>8001</differenceType> <!-- class removed --> + <justification>Removed already deprecated web services in this release</justification> + </difference> + <difference> + <className>**/ServerVersion</className> + <differenceType>8001</differenceType> <!-- class removed --> + <justification>Removed already deprecated web services in this release, this file was used for WS client-server + compatibility</justification> + </difference> +</differences> diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index f035ed6..44b0df4 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -1046,6 +1046,31 @@ </plugins> </build> </profile> + + <profile> + <id>signature-check</id> + <activation> + <property> + <name>signature-check-base-version</name> + </property> + </activation> + <build> + <plugins> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>clirr-maven-plugin</artifactId> + <version>${clirr.version}</version> + <configuration> + <includes> + <include>**/*Remote</include> + <include>**/ServerVersion</include> + </includes> + </configuration> + </plugin> + </plugins> + </build> + </profile> + </profiles>
<reporting> diff --git a/pom.xml b/pom.xml index 6af4a4b..35dc56f 100644 --- a/pom.xml +++ b/pom.xml @@ -226,7 +226,7 @@
<jacoco.version>0.6.0.201210061924</jacoco.version> </properties> - +
<dependencyManagement>
@@ -1646,6 +1646,7 @@ <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>clirr-maven-plugin</artifactId> + <version>${clirr.version}</version> <executions> <execution> <id>signature-check</id> @@ -1665,8 +1666,6 @@ <failOnError>true</failOnError> <failOnWarning>true</failOnWarning> <skip>${rhq.internal}</skip> - <!-- note that this is only available in clirr maven plugin 2.5, but internally we use a patched version for our CI builds. - Once new Clirr maven plugin is released, this will work for you, too. --> <ignoredDifferencesFile>${intentional-api-changes-file}</ignoredDifferencesFile> </configuration> </execution> @@ -1680,6 +1679,7 @@ <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>clirr-maven-plugin</artifactId> + <version>${clirr.version}</version> <configuration> <comparisonVersion>${signature-check-base-version}</comparisonVersion> <comparisonArtifacts>
commit 92c96c8dbb4a2d1c5cc6141c13faea1cb6e377c5 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Dec 7 12:11:15 2012 -0500
API Checker detected a change in this constant, no reason not to make this an ObjectName at decl-time, I think.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServerMBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServerMBean.java index 1e4796f..c0a1254 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServerMBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServerMBean.java @@ -21,7 +21,10 @@ package org.rhq.enterprise.server.core; import java.io.File; import java.util.Date;
+import javax.management.ObjectName; + import org.rhq.core.domain.common.ProductInfo; +import org.rhq.core.util.ObjectNameFactory;
/** * An MBean that exposes various global attributes of the underlying AS Server (version, uptime, etc.). @@ -30,7 +33,7 @@ public interface CoreServerMBean { /** * The name of this MBean when deployed. */ - String OBJECT_NAME = "rhq:service=CoreServer"; + ObjectName OBJECT_NAME = ObjectNameFactory.create("rhq:service=CoreServer");
/** * Returns the version of the core RHQ server. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java index 7b784fa..4a48e28 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.server.util; import java.lang.management.ManagementFactory;
import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.persistence.EntityManager; @@ -585,13 +584,9 @@ public final class LookupUtil { }
public static CoreServerMBean getCoreServer() { - CoreServerMBean rhqServer; - try { - MBeanServer mbs = getJBossMBeanServer(); - rhqServer = (CoreServerMBean) MBeanProxyExt.create(CoreServerMBean.class, CoreServerMBean.OBJECT_NAME, mbs); - } catch (MalformedObjectNameException e) { - throw new RuntimeException(e); - } + MBeanServer mbs = getJBossMBeanServer(); + CoreServerMBean rhqServer = (CoreServerMBean) MBeanProxyExt.create(CoreServerMBean.class, + CoreServerMBean.OBJECT_NAME, mbs); return rhqServer; }
@@ -640,7 +635,8 @@ public final class LookupUtil { return "java:global/rhq/rhq-enterprise-server-ejb3/" + beanName + "!" + interfaceName; }
- private static <T> String getLocalJNDIName(@NotNull Class<? super T> beanClass) { + private static <T> String getLocalJNDIName(@NotNull + Class<? super T> beanClass) { return getLocalJNDIName(beanClass.getSimpleName(), beanClass.getName().replace("Bean", "Local")); }
commit 76b7542636c64e40b718b18b1c0a9c1e1031acb7 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Dec 7 12:03:52 2012 -0500
Augeas plugin coding error I'm not sure what effect this change may have, but the code as written was clearly wrong and so I changed it.
diff --git a/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/impl/DefaultAugeasTreeBuilder.java b/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/impl/DefaultAugeasTreeBuilder.java index 5153145..55ffee5 100644 --- a/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/impl/DefaultAugeasTreeBuilder.java +++ b/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/impl/DefaultAugeasTreeBuilder.java @@ -51,7 +51,7 @@ public class DefaultAugeasTreeBuilder implements AugeasTreeBuilder {
AugeasTree tree; AugeasModuleConfig module = moduleConfig.getModuleByName(name); - if (lazy = true) + if (lazy) tree = new AugeasTreeLazy(component.getAugeas(), module); else tree = new AugeasTreeReal(component.getAugeas(), module);
commit c6def959b1e19c02e419647839e595460c9071d4 Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 12:02:07 2012 -0500
check to see if the extension is there to know if the installer already ran, that's more foolproof than checking for the ear being deployed
diff --git a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/CoreJBossASClient.java b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/CoreJBossASClient.java index 09e1b84..e75a399 100644 --- a/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/CoreJBossASClient.java +++ b/modules/common/jboss-as-dmr-client/src/main/java/org/rhq/common/jbossas/client/controller/CoreJBossASClient.java @@ -209,6 +209,17 @@ public class CoreJBossASClient extends JBossASClient { }
/** + * Returns true if the given extension is already in existence. + * + * @param name the name of the extension to check + * @return true if the extension already exists; false if not + * @throws Exception + */ + public boolean isExtension(String name) throws Exception { + return null != readResource(Address.root().add(EXTENSION, name)); + } + + /** * Adds a new subsystem to the core system. * * @param name the name of the new subsystem @@ -225,6 +236,17 @@ public class CoreJBossASClient extends JBossASClient { }
/** + * Returns true if the given subsystem is already in existence. + * + * @param name the name of the subsystem to check + * @return true if the subsystem already exists; false if not + * @throws Exception + */ + public boolean isSubsystem(String name) throws Exception { + return null != readResource(Address.root().add(SUBSYSTEM, name)); + } + + /** * Invokes the management "reload" operation which will shut down all the app server services and * restart them again. This is required for certain configuration changes to take effect. * This does not shutdown the JVM itself. diff --git a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java index 5b42094..589efca 100644 --- a/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java +++ b/modules/enterprise/server/installer/src/main/java/org/rhq/enterprise/server/installer/InstallerServiceImpl.java @@ -47,6 +47,8 @@ import org.rhq.enterprise.server.installer.ServerInstallUtil.SupportedDatabaseTy */ public class InstallerServiceImpl implements InstallerService {
+ private static final String RHQ_EXTENSION_NAME = "org.rhq.rhq-enterprise-server-startup-subsystem"; + private static final String RHQ_SUBSYSTEM_NAME = "rhq-startup"; private static final String EAR_NAME = "rhq.ear"; private static final String SYSPROP_PROPFILE = "rhq.server.properties-file";
@@ -204,6 +206,17 @@ public class InstallerServiceImpl implements InstallerService { if (isEarDeployed()) { return ""; // if the ear is deployed, we've already been fully installed } + + // its possible the ear is not yet deployed (during server init/startup, it won't show up) + // but our extension should always show up and its one of the last things our installer deploys. + // if this doesn't exist, our installation isn't done yet + if (isExtensionDeployed()) { + return ""; // installer has done all it could - just need to wait for the EAR to fully startup + } + + // in the future, if we can determine if any errors occurred during past installations, + // we can return that error message here. For now, just assume the installer is free to try to install. + return null; }
@@ -630,6 +643,18 @@ public class InstallerServiceImpl implements InstallerService { } }
+ private boolean isExtensionDeployed() throws Exception { + ModelControllerClient mcc = null; + try { + mcc = getModelControllerClient(); + final CoreJBossASClient client = new CoreJBossASClient(mcc); + boolean isDeployed = client.isExtension(RHQ_EXTENSION_NAME); + return isDeployed; + } finally { + safeClose(mcc); + } + } + private String getLogDir() throws Exception { ModelControllerClient mcc = null; try { @@ -920,7 +945,7 @@ public class InstallerServiceImpl implements InstallerService { mcc = getModelControllerClient(); CoreJBossASClient client = new CoreJBossASClient(mcc); log("Installing RHQ EAR startup subsystem extension"); - client.addExtension("org.rhq.rhq-enterprise-server-startup-subsystem"); + client.addExtension(RHQ_EXTENSION_NAME); } finally { safeClose(mcc); } @@ -932,7 +957,7 @@ public class InstallerServiceImpl implements InstallerService { mcc = getModelControllerClient(); CoreJBossASClient client = new CoreJBossASClient(mcc); log("Installing RHQ EAR subsystem"); - client.addSubsystem("rhq-startup"); + client.addSubsystem(RHQ_SUBSYSTEM_NAME); } finally { safeClose(mcc); }
commit 4c222409553e1e7d2d6331ff405a337abcca2bbd Author: Lukas Krejci lkrejci@redhat.com Date: Fri Dec 7 17:00:34 2012 +0100
Moving the JNDI security infrastructure to the server/jar and updating it to work with AS7.
* Got rid of container-lib as there were no other classes left there.
* The StartupBean server/jar now takes care of initializing this stuff instead of the custom MBean we used to use in the AS4-based container.
* Updated the tests to work with this new arrangement.
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java index 5822d44..3a7d046 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/StandardScriptPermissions.java @@ -23,14 +23,19 @@ import java.io.FilePermission; import java.io.SerializablePermission; import java.lang.reflect.ReflectPermission; import java.net.SocketPermission; +import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; +import java.security.ProtectionDomain; +import java.security.cert.Certificate; import java.util.Enumeration; import java.util.PropertyPermission; +import java.util.logging.LoggingPermission;
import javax.management.MBeanPermission; import javax.management.ObjectName; +import javax.security.auth.PrivateCredentialPermission;
/** * @author Lukas Krejci @@ -58,13 +63,11 @@ public class StandardScriptPermissions extends PermissionCollection { //JVM defined runtime perms add(new RuntimePermission("createClassLoader")); add(new RuntimePermission("getClassLoader")); - add(new RuntimePermission("setContextClassLoader")); add(new RuntimePermission("getenv.*")); add(new RuntimePermission("getProtectionDomain")); add(new RuntimePermission("getFileSystemAttributes")); add(new RuntimePermission("readFileDescriptor")); add(new RuntimePermission("writeFileDescriptor")); - add(new RuntimePermission("loadLibrary.*")); add(new RuntimePermission("accessClassInPackage.*")); add(new RuntimePermission("defineClassInPackage.*")); add(new RuntimePermission("accessDeclaredMembers")); @@ -85,10 +88,18 @@ public class StandardScriptPermissions extends PermissionCollection {
add(new ReflectPermission("suppressAccessChecks"));
- //these 2 are required for server-side scripts to be able to + //these are required for server-side scripts to be able to //invoke remote EJBs. + add(new SerializablePermission("creator")); + add(new SerializablePermission("allowSerializationReflection")); add(new SerializablePermission("enableSubclassImplementation")); - add(new RuntimePermission("reflectionFactoryAccess")); + add(new RuntimePermission("reflectionFactoryAccess")); + + //by default allow the scripts access to any credentials of any user + //we don't consider the scripts malevolent. + add(new PrivateCredentialPermission("* * "*"", "read")); + + add(new LoggingPermission("control", null)); }
public void add(Permission permission) { diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java index 74c0019..3b993a8 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientFactory.java @@ -9,11 +9,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Set;
-import javax.jws.WebParam; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; @@ -26,6 +21,11 @@ import javassist.bytecode.annotation.StringMemberValue; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory;
+import javax.jws.WebParam; + +import org.apache.commons.logging.Log; + +import org.rhq.bindings.security.SecurityActions; import org.rhq.bindings.util.ConfigurationClassBuilder; import org.rhq.bindings.util.ResourceTypeFingerprint; import org.rhq.core.domain.resource.ResourceCreationDataType; @@ -42,7 +42,7 @@ public class ResourceClientFactory { public Class<?> iface; }
- private static final Log LOG = LogFactory.getLog(ResourceClientFactory.class); + private static final Log LOG = SecurityActions.getLog(ResourceClientFactory.class);
//keys are resource type ids private static HashMap<Integer, CacheRecord> CUSTOM_CLASS_CACHE = new HashMap<Integer, CacheRecord>(); diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java index 7361fe8..1b71678 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java @@ -32,8 +32,8 @@ import java.util.Set; import javassist.util.proxy.MethodHandler;
import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory;
+import org.rhq.bindings.security.SecurityActions; import org.rhq.bindings.util.ConfigurationClassBuilder; import org.rhq.bindings.util.LazyLoadScenario; import org.rhq.bindings.util.ResourceTypeFingerprint; @@ -84,7 +84,7 @@ import org.rhq.enterprise.server.resource.ResourceTypeNotFoundException; */ public class ResourceClientProxy {
- private static final Log LOG = LogFactory.getLog(ResourceClientProxy.class); + private static final Log LOG = SecurityActions.getLog(ResourceClientProxy.class);
private ResourceClientFactory proxyFactory; private RhqFacade remoteClient; diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java index 2a1f944..4d33fb2 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/script/RepoScriptSourceProvider.java @@ -28,10 +28,10 @@ import java.nio.charset.Charset; import java.util.List;
import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory;
import org.rhq.bindings.StandardBindings; import org.rhq.bindings.client.RhqFacade; +import org.rhq.bindings.security.SecurityActions; import org.rhq.core.domain.content.Repo; import org.rhq.core.domain.content.composite.PackageAndLatestVersionComposite; import org.rhq.core.domain.criteria.PackageCriteria; @@ -53,7 +53,7 @@ import org.rhq.enterprise.server.content.RepoManagerRemote; public class RepoScriptSourceProvider extends BaseRhqSchemeScriptSourceProvider implements StandardBindings.RhqFacadeChangeListener {
- private static final Log LOG = LogFactory.getLog(RepoScriptSourceProvider.class); + private static final Log LOG = SecurityActions.getLog(RepoScriptSourceProvider.class);
private static final String AUTHORITY = "repositories";
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java new file mode 100644 index 0000000..cdde2ff --- /dev/null +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/security/SecurityActions.java @@ -0,0 +1,56 @@ +/* + * RHQ Management Platform + * Copyright 2012, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.bindings.security; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * @author Lukas Krejci + * + */ +public class SecurityActions { + + private SecurityActions() { + + } + + public static Log getLog(final Class<?> cls) { + return AccessController.doPrivileged(new PrivilegedAction<Log>() { + @Override + public Log run() { + return LogFactory.getLog(cls); + }; + }); + } + + public static Log getLog(final String name) { + return AccessController.doPrivileged(new PrivilegedAction<Log>() { + @Override + public Log run() { + return LogFactory.getLog(name); + }; + }); + } +} diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java index 8ce7bc6..d2724d1 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/util/InterfaceSimplifier.java @@ -52,8 +52,8 @@ import javassist.bytecode.annotation.ShortMemberValue; import javassist.bytecode.annotation.StringMemberValue;
import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory;
+import org.rhq.bindings.security.SecurityActions; import org.rhq.core.domain.auth.Subject;
/** @@ -64,7 +64,7 @@ import org.rhq.core.domain.auth.Subject; * @author Lukas Krejci */ public class InterfaceSimplifier { - private static final Log LOG = LogFactory.getLog(InterfaceSimplifier.class); + private static final Log LOG = SecurityActions.getLog(InterfaceSimplifier.class);
private InterfaceSimplifier() {
diff --git a/modules/enterprise/pom.xml b/modules/enterprise/pom.xml index 4e935ec..a43fb1e 100644 --- a/modules/enterprise/pom.xml +++ b/modules/enterprise/pom.xml @@ -28,7 +28,6 @@ <module>comm</module> <module>agent</module> <module>agentupdate</module> - <module>server/container-lib</module> <module>server/xml-schemas</module> <module>server/jar</module> <module>server/safe-invoker</module> @@ -56,7 +55,6 @@ <module>comm</module> <module>agent</module> <module>agentupdate</module> - <module>server/container-lib</module> <module>server/xml-schemas</module> <module>server/jar</module> <module>server/safe-invoker</module> diff --git a/modules/enterprise/server/appserver/pom.xml b/modules/enterprise/server/appserver/pom.xml index 1ae6cdb..96babf8 100644 --- a/modules/enterprise/server/appserver/pom.xml +++ b/modules/enterprise/server/appserver/pom.xml @@ -25,14 +25,6 @@ <version>${project.version}</version> </dependency>
-<!-- - <dependency> - <groupId>org.rhq</groupId> - <artifactId>rhq-container-lib</artifactId> - <version>${project.version}</version> - </dependency> - --> - <!-- 3rd Party Deps -->
<dependency> diff --git a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml index 5922afb..9216787 100644 --- a/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml +++ b/modules/enterprise/server/appserver/src/main/scripts/rhq-container.build.xml @@ -167,10 +167,6 @@ <echo>Installing patched hibernate jar ...</echo> <copy file="${settings.localRepository}/hibernate/hibernate3/${hibernate3.version}/hibernate3-${hibernate3.version}.jar" tofile="${jboss.home}/server/default/lib/hibernate3.jar" verbose="true"/> - - <echo>Installing custom container library...</echo> - <copy file="${settings.localRepository}/org/rhq/rhq-container-lib/${rhq.version}/rhq-container-lib-${rhq.version}.jar" - tofile="${jboss.home}/server/default/lib/rhq-container-lib-${rhq.version}.jar" verbose="true"/> -->
<echo>Adding JDBC modules to ${jboss.modules.dir} ...</echo> diff --git a/modules/enterprise/server/client-api/pom.xml b/modules/enterprise/server/client-api/pom.xml index 08ef4a1..1459e31 100644 --- a/modules/enterprise/server/client-api/pom.xml +++ b/modules/enterprise/server/client-api/pom.xml @@ -16,13 +16,6 @@ <description>The implementation of the client API when accessing the server locally</description>
<dependencies> - <!-- - <dependency> - <groupId>org.rhq</groupId> - <artifactId>rhq-container-lib</artifactId> - <version>${project.version}</version> - </dependency> - --> <dependency> <groupId>org.rhq</groupId> <artifactId>rhq-enterprise-server</artifactId> diff --git a/modules/enterprise/server/container-lib/pom.xml b/modules/enterprise/server/container-lib/pom.xml deleted file mode 100644 index 05f8bd4..0000000 --- a/modules/enterprise/server/container-lib/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.rhq</groupId> - <artifactId>rhq-parent</artifactId> - <version>4.6.0-SNAPSHOT</version> - <relativePath>../../../../pom.xml</relativePath> - </parent> - - <groupId>org.rhq</groupId> - <artifactId>rhq-container-lib</artifactId> - <packaging>jar</packaging> - - <name>RHQ Enterprise Container Library</name> - <description>A library of classes that will be deployed in the server container itself, above the main EAR</description> - - <dependencies> - - <dependency> - <groupId>org.jboss.jbossts</groupId> - <artifactId>jbossjts</artifactId> - <version>4.16.2.Final</version> - <scope>provided</scope> <!-- by JBossAS --> - </dependency> - - <dependency> - <groupId>org.jboss</groupId> - <artifactId>jboss-common-core</artifactId> - <scope>provided</scope> <!-- by JBossAS --> - </dependency> - - <dependency> - <groupId>jboss</groupId> - <artifactId>jbosssx</artifactId> - <version>4.2.3.GA</version> - <scope>provided</scope> <!-- by JBossAS --> - </dependency> - - <dependency> - <groupId>jboss</groupId> - <artifactId>jnpserver</artifactId> - <version>4.2.2.GA</version> - <scope>provided</scope> - </dependency> - </dependencies> - - <profiles> - - <profile> - <id>dev</id> - - <properties> - <rhq.rootDir>../../../..</rhq.rootDir> - <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> - <rhq.deploymentDir>${rhq.containerDir}/jbossas/standalone/lib</rhq.deploymentDir> - </properties> - - <build> - <plugins> - - <plugin> - <artifactId>maven-antrun-plugin</artifactId> - <executions> - - <execution> - <id>deploy</id> - <phase>compile</phase> - <configuration> - <target> - <mkdir dir="${rhq.deploymentDir}" /> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar" /> - <echo>*** Updating ${deployment.file}...</echo> - <jar destfile="${deployment.file}" basedir="${project.build.outputDirectory}" /> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - - <execution> - <id>undeploy</id> - <phase>clean</phase> - <configuration> - <target> - <property name="deployment.file" location="${rhq.deploymentDir}/${project.build.finalName}.jar" /> - <echo>*** Deleting ${deployment.file}...</echo> - <delete file="${deployment.file}" /> - </target> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution> - - </executions> - </plugin> - - </plugins> - </build> - </profile> - - </profiles> - -</project> diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AccessCheckingInitialContextFactoryBuilder.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AccessCheckingInitialContextFactoryBuilder.java deleted file mode 100644 index 1e35a4e..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AccessCheckingInitialContextFactoryBuilder.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ -package org.rhq.jndi; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.event.EventContext; -import javax.naming.event.EventDirContext; -import javax.naming.ldap.LdapContext; -import javax.naming.spi.InitialContextFactory; -import javax.naming.spi.InitialContextFactoryBuilder; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.rhq.jndi.context.AccessCheckingContextDecorator; -import org.rhq.jndi.context.AccessCheckingContextDecoratorSetContext; -import org.rhq.jndi.context.ContextDecorator; -import org.rhq.jndi.context.URLPreferringContextDecoratorSetContext; -import org.rhq.jndi.util.DecoratorPicker; - -/** - * This initial context factory builder is installed early on during the RHQ server startup - * and is later on used for obtaining the {@link Context}s for all JNDI lookups in the - * RHQ server. - * <p> - * We use a custom initial context factory builder to prevent the potential malicious 3rd party - * code (like CLI alert scripts) from supplying custom environment variables to {@link InitialContext} - * that would modify the JNDI lookup to skip our security access checks. - * <p> - * By using a builder we effectively take control of the initial context creation process - * and are free to ignore whatever the script is trying to supply. - * <p> - * This builder makes sure to install the RHQ server's security access checks to whatever - * initial context that is configured by the standard environment variables - * ({@link Context#INITIAL_CONTEXT_FACTORY}, etc.) - * <p> - * This class is heavily inspired by the implementation of a similar builder in JBoss AS 7. - * - * @see AllowRhqServerInternalsAccessPermission - * - * @author Lukas Krejci - */ -public class AccessCheckingInitialContextFactoryBuilder implements InitialContextFactoryBuilder { - private static final Log LOG = LogFactory.getLog(AccessCheckingInitialContextFactoryBuilder.class); - - /** - * The list of JNDI name schemes that should be checked for security permissions - * (in addition to the names with no scheme). - * - * @see AccessCheckingContextDecorator - */ - private static final String[] CHECKED_SCHEMES = { "java" }; - - private static final Set<Class<? extends Context>> SUPPORTED_CONTEXT_INTERFACES; - - static { - SUPPORTED_CONTEXT_INTERFACES = new HashSet<Class<? extends Context>>(); - SUPPORTED_CONTEXT_INTERFACES.add(Context.class); - SUPPORTED_CONTEXT_INTERFACES.add(DirContext.class); - SUPPORTED_CONTEXT_INTERFACES.add(EventContext.class); - SUPPORTED_CONTEXT_INTERFACES.add(EventDirContext.class); - SUPPORTED_CONTEXT_INTERFACES.add(LdapContext.class); - } - - private static final Set<InetAddress> SERVER_BIND_IPS; - static { - SERVER_BIND_IPS = new HashSet<InetAddress>(); - - try { - String bindingAddressString = System.getProperty("jboss.bind.address"); - InetAddress bindingAddress = InetAddress.getByName(bindingAddressString); - - if (bindingAddress.isAnyLocalAddress()) { - Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); - while (ifaces.hasMoreElements()) { - NetworkInterface iface = ifaces.nextElement(); - SERVER_BIND_IPS.addAll(Collections.list(iface.getInetAddresses())); - } - } else { - SERVER_BIND_IPS.add(bindingAddress); - } - } catch (SocketException e) { - LOG.error("Could not obtain the list of local IPs", e); - } catch (UnknownHostException e) { - LOG.error("Failed to get the binding address of the RHQ server.", e); - } - } - - private static final int JNP_PORT = Integer.parseInt(System.getProperty("rhq.server.startup.namingservice.port", - "2099")); - - /** - * This is the default initial context factory that is returned when no other is - * configured using the environment variables. - * <p> - * It uses {@link NamingContextFactory} as the underlying mechanism - the same - * as the default configuration in JBoss 4. - */ - private static final InitialContextFactory DEFAULT_FACTORY = new InitialContextFactory() { - public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { - return null; // TODO: how to do this in AS7? createSecureWrapper(new NamingContextFactory(), environment).getInitialContext(environment); - } - }; - - /** - * Create a InitialContext factory. If the environment does not override the factory class it will use the - * default context factory. - * - * @param environment The environment - * @return An initial context factory - * @throws NamingException If an error occurs loading the factory class. - */ - public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { - final String factoryClassName = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY); - if (factoryClassName == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("No " + Context.INITIAL_CONTEXT_FACTORY + " set. Using the default factory."); - } - return DEFAULT_FACTORY; - } - final ClassLoader classLoader = getContextClassLoader(); - try { - final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader); - InitialContextFactory configuredFactory = (InitialContextFactory) factoryClass.newInstance(); - return createSecureWrapper(configuredFactory, environment); - } catch (Exception e) { - throw new NamingException("Failed instantiate InitialContextFactory " + factoryClassName - + " from classloader " + classLoader); - } - } - - private ClassLoader getContextClassLoader() { - return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { - public ClassLoader run() { - return Thread.currentThread().getContextClassLoader(); - } - }); - } - - private static InitialContextFactory - createSecureWrapper(InitialContextFactory factory, Hashtable<?, ?> environment) { - String providerUrl = (String) environment.get(Context.PROVIDER_URL); - - if (providerUrl == null) { - if (LOG.isTraceEnabled()) { - LOG.trace("Wrapping " + factory + " of class " + factory.getClass() + " in an access checking wrapper. No provider URL detected."); - } - return getAccessCheckingFactory(factory); - } else { - try { - URI uri = new URI(providerUrl); - InetAddress providerHost = InetAddress.getByName(uri.getHost()); - - //check if we are accessing the RHQ server through some remoting - //interface. - if (uri.getPort() == JNP_PORT && SERVER_BIND_IPS.contains(providerHost)) { - if (LOG.isTraceEnabled()) { - LOG.trace("Wrapping " + factory + " of class " + factory.getClass() + " in an access checking wrapper. The provider URL points to this server."); - } - return getAccessCheckingFactory(factory); - } else { - if (LOG.isTraceEnabled()) { - LOG.trace("Wrapping " + factory + " of class " + factory.getClass() + " in an URL preferring wrapper to enable remote connections."); - } - return getURLPreferringFactory(factory); - } - } catch (URISyntaxException e) { - if (LOG.isDebugEnabled()) { - LOG.debug("The " + Context.PROVIDER_URL - + " is not a valid URI. Falling back to using the access checking wrapper for the factory " - + factory + " of class " + factory.getClass() + ".", e); - } - return getAccessCheckingFactory(factory); - } catch (UnknownHostException e) { - //let the factory deal with the unknown host... - //this most probably shouldn't be secured because localhost addresses - //should be resolvable. - if (LOG.isDebugEnabled()) { - LOG.debug("The " + Context.PROVIDER_URL - + " is not resolvable. Falling back to using the URL preferring wrapper for the factory " - + factory + " of class " + factory.getClass() + ".", e); - } - return getURLPreferringFactory(factory); - } - } - } - - private static InitialContextFactory getAccessCheckingFactory(InitialContextFactory original) { - ArrayList<DecoratorPicker<Context, ContextDecorator>> pickers = new ArrayList<DecoratorPicker<Context,ContextDecorator>>(); - pickers.add(getURLPreferringDecoratorPicker()); - pickers.add(getAccessCheckingDecoratorPicker()); - - return new DecoratingInitialContextFactory(original, pickers); - } - - private static InitialContextFactory getURLPreferringFactory(InitialContextFactory original) { - ArrayList<DecoratorPicker<Context, ContextDecorator>> pickers = new ArrayList<DecoratorPicker<Context,ContextDecorator>>(); - pickers.add(getURLPreferringDecoratorPicker()); - - return new DecoratingInitialContextFactory(original, pickers); - } - - private static DecoratorPicker<Context, ContextDecorator> getAccessCheckingDecoratorPicker() { - DecoratorPicker<Context, ContextDecorator> ret = new DecoratorPicker<Context, ContextDecorator>(); - ret.setContext(new AccessCheckingContextDecoratorSetContext(SUPPORTED_CONTEXT_INTERFACES, CHECKED_SCHEMES)); - - return ret; - } - - private static DecoratorPicker<Context, ContextDecorator> getURLPreferringDecoratorPicker() { - DecoratorPicker<Context, ContextDecorator> ret = new DecoratorPicker<Context, ContextDecorator>(); - ret.setContext(new URLPreferringContextDecoratorSetContext(SUPPORTED_CONTEXT_INTERFACES)); - - return ret; - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AllowRhqServerInternalsAccessPermission.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AllowRhqServerInternalsAccessPermission.java deleted file mode 100644 index aa807d6..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/AllowRhqServerInternalsAccessPermission.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi; - -import java.security.BasicPermission; - -/** - * - * - * @author Lukas Krejci - */ -public class AllowRhqServerInternalsAccessPermission extends BasicPermission { - - private static final long serialVersionUID = 1L; - - public AllowRhqServerInternalsAccessPermission() { - super("org.rhq.allow.server.internals.access"); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/DecoratingInitialContextFactory.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/DecoratingInitialContextFactory.java deleted file mode 100644 index e0f1d84..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/DecoratingInitialContextFactory.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi; - -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Set; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; - -import org.rhq.jndi.context.ContextDecorator; -import org.rhq.jndi.util.DecoratorPicker; -import org.rhq.jndi.util.DecoratingInvocationHandler; - -/** - * This class implements an initial context factory that decorates the contexts - * returned from a "wrapped" initial factory passed to this class in the constructor. - * <p> - * The contexts returned from the wrapped initial factory are hidden behind a proxy - * that implements the intersection of interfaces from the <code>supportedContextInterfaces</code> - * constructor parameter and the actual interfaces the wrapped context implements. - * <p> - * The proxy method calls are handled using the {@link DecoratingInvocationHandler} which is initialized - * with the list of {@link DecoratorPicker pickers} that are used to intercept the method - * calls on the wrapped context. - * - * @see DecoratorPicker - * @see DecoratingInvocationHandler - * - * @author Lukas Krejci - */ -public class DecoratingInitialContextFactory implements InitialContextFactory { - - List<DecoratorPicker<Context, ContextDecorator>> pickers; - private InitialContextFactory factory; - private Set<Class<? extends Context>> supportedContextInterfaces; - - public DecoratingInitialContextFactory(InitialContextFactory factory, List<DecoratorPicker<Context, ContextDecorator>> decoratorPickers) { - this.factory = factory; - this.pickers = decoratorPickers; - this.supportedContextInterfaces = new HashSet<Class<? extends Context>>(); - for(DecoratorPicker<Context, ContextDecorator> picker : pickers) { - supportedContextInterfaces.addAll(picker.getContext().getSupportedInterfaces()); - } - } - - public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { - Context ctx = factory.getInitialContext(environment); - - Set<Class<?>> implementedIfaces = getAllImplementedInterfaces(ctx.getClass()); - Class<?>[] ii = new Class<?>[implementedIfaces.size()]; - implementedIfaces.toArray(ii); - - return (Context) Proxy.newProxyInstance(ctx.getClass().getClassLoader(), ii, new DecoratingInvocationHandler<Context, ContextDecorator>(pickers, ctx)); - } - - private Set<Class<?>> getAllImplementedInterfaces(Class<?> cls) { - HashSet<Class<?>> ret = new HashSet<Class<?>>(); - getAllImplementedInterfaces(cls, ret); - - ret.retainAll(supportedContextInterfaces); - - return ret; - } - - private static void getAllImplementedInterfaces(Class<?> cls, Set<Class<?>> output) { - Class<?>[] ifaces = cls.getInterfaces(); - - for (Class<?> iface : Arrays.asList(ifaces)) { - output.add(iface); - getAllImplementedInterfaces(iface, output); - } - - if (cls.getSuperclass() != null) { - getAllImplementedInterfaces(cls.getSuperclass(), output); - } - } - - @Override - public int hashCode() { - return factory.hashCode(); - } - - @Override - public boolean equals(Object o) { - return factory.equals(o); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecorator.java deleted file mode 100644 index 8970b0a..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecorator.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.List; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; - -import org.rhq.jndi.AllowRhqServerInternalsAccessPermission; - -/** - * This is the "meat" of the RHQ's secured JNDI access. This {@link Context} decorator - * applied security checks in each method (lookups, (un)bindings, etc). - * <p> - * The security check consists of checking if the current callstack has the {@link AllowRhqServerInternalsAccessPermission}. - * <p> - * This decorator applies the security check on any JNDI name without a scheme and - * on any name that has a scheme listed in the {@link #checkedSchemes} list supplied - * in the constructor. - * - * @author Lukas Krejci - */ -public class AccessCheckingContextDecorator implements Context, ContextDecorator, Serializable { - - private static final long serialVersionUID = 1L; - - private static final AllowRhqServerInternalsAccessPermission PERM = new AllowRhqServerInternalsAccessPermission(); - private Context original; - private List<String> checkedSchemes; - - public AccessCheckingContextDecorator(String... checkedSchemes) { - this.checkedSchemes = Arrays.asList(checkedSchemes); - } - - public AccessCheckingContextDecorator(Context original, String... checkedSchemes) { - this.original = original; - this.checkedSchemes = Arrays.asList(checkedSchemes); - } - - public void init(Context ctx) { - this.original = ctx; - } - - protected Context getOriginal() { - return original; - } - - protected static void check() { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) sm.checkPermission(PERM); - } - - private void checkScheme(String scheme) { - if (scheme == null || checkedSchemes.contains(scheme)) { - check(); - } - } - - protected void check(String name) { - checkScheme(getURLScheme(name)); - } - - protected void check(Name name) { - if (name.size() == 0) { - check(); - } else { - String first = name.get(0); - checkScheme(getURLScheme(first)); - } - } - - public Object lookup(Name name) throws NamingException { - check(name); - return original.lookup(name); - } - - public Object lookup(String name) throws NamingException { - check(name); - return original.lookup(name); - } - - public void bind(Name name, Object obj) throws NamingException { - check(name); - original.bind(name, obj); - } - - public void bind(String name, Object obj) throws NamingException { - check(name); - original.bind(name, obj); - } - - public void rebind(Name name, Object obj) throws NamingException { - check(name); - original.rebind(name, obj); - } - - public void rebind(String name, Object obj) throws NamingException { - check(name); - original.rebind(name, obj); - } - - public void unbind(Name name) throws NamingException { - check(name); - original.unbind(name); - } - - public void unbind(String name) throws NamingException { - check(name); - original.unbind(name); - } - - public void rename(Name oldName, Name newName) throws NamingException { - check(oldName); - check(newName); - original.rename(oldName, newName); - } - - public void rename(String oldName, String newName) throws NamingException { - check(oldName); - check(newName); - original.rename(oldName, newName); - } - - public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { - check(name); - return original.list(name); - } - - public NamingEnumeration<NameClassPair> list(String name) throws NamingException { - check(name); - return original.list(name); - } - - public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { - check(name); - return original.listBindings(name); - } - - public NamingEnumeration<Binding> listBindings(String name) throws NamingException { - check(name); - return original.listBindings(name); - } - - public void destroySubcontext(Name name) throws NamingException { - check(name); - original.destroySubcontext(name); - } - - public void destroySubcontext(String name) throws NamingException { - check(name); - original.destroySubcontext(name); - } - - public Context createSubcontext(Name name) throws NamingException { - check(name); - return original.createSubcontext(name); - } - - public Context createSubcontext(String name) throws NamingException { - check(name); - return original.createSubcontext(name); - } - - public Object lookupLink(Name name) throws NamingException { - check(name); - return original.lookupLink(name); - } - - public Object lookupLink(String name) throws NamingException { - check(name); - return original.lookupLink(name); - } - - public NameParser getNameParser(Name name) throws NamingException { - check(name); - return original.getNameParser(name); - } - - public NameParser getNameParser(String name) throws NamingException { - check(name); - return original.getNameParser(name); - } - - public Name composeName(Name name, Name prefix) throws NamingException { - check(name); - return original.composeName(name, prefix); - } - - public String composeName(String name, String prefix) throws NamingException { - check(name); - return original.composeName(name, prefix); - } - - public Object addToEnvironment(String propName, Object propVal) throws NamingException { - check(); - return original.addToEnvironment(propName, propVal); - } - - public Object removeFromEnvironment(String propName) throws NamingException { - check(); - return original.removeFromEnvironment(propName); - } - - public Hashtable<?, ?> getEnvironment() throws NamingException { - check(); - return original.getEnvironment(); - } - - public void close() throws NamingException { - check(); - original.close(); - } - - public String getNameInNamespace() throws NamingException { - check(); - return original.getNameInNamespace(); - } - - //copied from InitialContext - private static String getURLScheme(String str) { - int colon_posn = str.indexOf(':'); - int slash_posn = str.indexOf('/'); - - if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn)) - return str.substring(0, colon_posn); - return null; - } - - @Override - public int hashCode() { - return getOriginal() == null ? super.hashCode() : getOriginal().hashCode(); - } - - @Override - public boolean equals(Object o) { - return getOriginal() == null ? super.equals(o) : getOriginal().equals(o); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecoratorSetContext.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecoratorSetContext.java deleted file mode 100644 index 284fd0c..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingContextDecoratorSetContext.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.lang.reflect.Constructor; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import javax.naming.Context; - -import org.rhq.jndi.util.DecoratorSetContext; - -/** - * - * - * @author Lukas Krejci - */ -public class AccessCheckingContextDecoratorSetContext implements DecoratorSetContext<Context, ContextDecorator> { - - private static final Set<Class<? extends ContextDecorator>> DECORATOR_CLASSES; - static { - HashSet<Class<? extends ContextDecorator>> tmp = new HashSet<Class<? extends ContextDecorator>>(); - tmp.add(AccessCheckingContextDecorator.class); - tmp.add(AccessCheckingDirContextDecorator.class); - tmp.add(AccessCheckingEventContextDecorator.class); - tmp.add(AccessCheckingEventDirContextDecorator.class); - tmp.add(AccessCheckingLdapContextDecorator.class); - - DECORATOR_CLASSES = Collections.unmodifiableSet(tmp); - } - - private Set<Class<? extends Context>> supportedInterfaces; - private String[] checkedSchemes; - - public AccessCheckingContextDecoratorSetContext(Set<Class<? extends Context>> supportedInterfaces, String... checkedSchemes) { - this.supportedInterfaces = supportedInterfaces; - this.checkedSchemes = checkedSchemes; - } - - public ContextDecorator instantiate(Class<? extends ContextDecorator> decoratorClass) throws Exception { - Constructor<? extends ContextDecorator> ctor = decoratorClass.getConstructor(String[].class); - - return ctor.newInstance((Object)checkedSchemes); - } - - public Set<Class<? extends Context>> getSupportedInterfaces() { - return supportedInterfaces; - } - - public Set<Class<? extends ContextDecorator>> getDecoratorClasses() { - return DECORATOR_CLASSES; - } - - public void init(ContextDecorator decorator, Context object) throws Exception { - decorator.init(object); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingDirContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingDirContextDecorator.java deleted file mode 100644 index 1614180..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingDirContextDecorator.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Name; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; - -/** - * A decorator of {@link DirContext}. - * - * @author Lukas Krejci - */ -public class AccessCheckingDirContextDecorator extends AccessCheckingContextDecorator implements DirContext { - - private static final long serialVersionUID = 1L; - - public AccessCheckingDirContextDecorator(String... checkedSchemes) { - super(checkedSchemes); - } - - public AccessCheckingDirContextDecorator(DirContext original, String... checkedSchemes) { - super(original, checkedSchemes); - } - - @Override - protected DirContext getOriginal() { - return (DirContext) super.getOriginal(); - } - - public Attributes getAttributes(Name name) throws NamingException { - check(name); - return getOriginal().getAttributes(name); - } - - public Attributes getAttributes(String name) throws NamingException { - check(name); - return getOriginal().getAttributes(name); - } - - public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { - check(name); - return getOriginal().getAttributes(name, attrIds); - } - - public Attributes getAttributes(String name, String[] attrIds) throws NamingException { - check(name); - return getOriginal().getAttributes(name, attrIds); - } - - public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { - check(name); - getOriginal().modifyAttributes(name, mod_op, attrs); - } - - public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { - check(name); - getOriginal().modifyAttributes(name, mod_op, attrs); - } - - public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { - check(name); - getOriginal().modifyAttributes(name, mods); - } - - public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { - check(name); - getOriginal().modifyAttributes(name, mods); - } - - public void bind(Name name, Object obj, Attributes attrs) throws NamingException { - check(name); - getOriginal().bind(name, obj, attrs); - } - - public void bind(String name, Object obj, Attributes attrs) throws NamingException { - check(name); - getOriginal().bind(name, obj, attrs); - } - - public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { - check(name); - getOriginal().rebind(name, obj, attrs); - } - - public void rebind(String name, Object obj, Attributes attrs) throws NamingException { - check(name); - getOriginal().rebind(name, obj, attrs); - } - - public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { - check(name); - return getOriginal().createSubcontext(name, attrs); - } - - public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { - check(name); - return getOriginal().createSubcontext(name, attrs); - } - - public DirContext getSchema(Name name) throws NamingException { - check(name); - return getOriginal().getSchema(name); - } - - public DirContext getSchema(String name) throws NamingException { - check(name); - return getOriginal().getSchema(name); - } - - public DirContext getSchemaClassDefinition(Name name) throws NamingException { - check(name); - return getOriginal().getSchemaClassDefinition(name); - } - - public DirContext getSchemaClassDefinition(String name) throws NamingException { - check(name); - return getOriginal().getSchema(name); - } - - public NamingEnumeration<SearchResult> - search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { - check(name); - return getOriginal().search(name, matchingAttributes, attributesToReturn); - } - - public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, - String[] attributesToReturn) throws NamingException { - check(name); - return getOriginal().search(name, matchingAttributes, attributesToReturn); - } - - public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { - check(name); - return getOriginal().search(name, matchingAttributes); - } - - public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { - check(name); - return getOriginal().search(name, matchingAttributes); - } - - public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { - check(name); - return getOriginal().search(name, filter, cons); - } - - public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) - throws NamingException { - check(name); - return getOriginal().search(name, filter, cons); - } - - public NamingEnumeration<SearchResult> - search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { - check(name); - return getOriginal().search(name, filterExpr, filterArgs, cons); - } - - public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, - SearchControls cons) throws NamingException { - check(name); - return getOriginal().search(name, filterExpr, filterArgs, cons); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventContextDecorator.java deleted file mode 100644 index 67a9527..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventContextDecorator.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.event.EventContext; -import javax.naming.event.NamingListener; - -/** - * - * - * @author Lukas Krejci - */ -public class AccessCheckingEventContextDecorator extends AccessCheckingContextDecorator implements EventContext { - - private static final long serialVersionUID = 1L; - - public AccessCheckingEventContextDecorator(String... checkedSchemes) { - super(checkedSchemes); - } - - public AccessCheckingEventContextDecorator(EventContext original, String... checkedSchemes) { - super(original, checkedSchemes); - } - - @Override - protected EventContext getOriginal() { - return (EventContext) super.getOriginal(); - } - - public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { - check(target); - getOriginal().addNamingListener(target, scope, l); - } - - public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { - check(target); - getOriginal().addNamingListener(target, scope, l); - } - - public void removeNamingListener(NamingListener l) throws NamingException { - check(); - getOriginal().removeNamingListener(l); - } - - public boolean targetMustExist() throws NamingException { - check(); - return getOriginal().targetMustExist(); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventDirContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventDirContextDecorator.java deleted file mode 100644 index ed7a848..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingEventDirContextDecorator.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.directory.SearchControls; -import javax.naming.event.EventDirContext; -import javax.naming.event.NamingListener; - -/** - * - * - * @author Lukas Krejci - */ -public class AccessCheckingEventDirContextDecorator extends AccessCheckingDirContextDecorator implements - EventDirContext { - - private static final long serialVersionUID = 1L; - - public AccessCheckingEventDirContextDecorator(String... checkedSchemes) { - super(checkedSchemes); - } - - public AccessCheckingEventDirContextDecorator(EventDirContext original, String... checkedSchemes) { - super(original, checkedSchemes); - } - - @Override - protected EventDirContext getOriginal() { - return (EventDirContext) super.getOriginal(); - } - - public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { - check(target); - getOriginal().addNamingListener(target, scope, l); - } - - public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { - check(target); - getOriginal().addNamingListener(target, scope, l); - } - - public void removeNamingListener(NamingListener l) throws NamingException { - check(); - getOriginal().removeNamingListener(l); - } - - public boolean targetMustExist() throws NamingException { - check(); - return getOriginal().targetMustExist(); - } - - public void addNamingListener(Name target, String filter, SearchControls ctls, NamingListener l) - throws NamingException { - check(target); - getOriginal().addNamingListener(target, filter, ctls, l); - } - - public void addNamingListener(String target, String filter, SearchControls ctls, NamingListener l) - throws NamingException { - check(target); - getOriginal().addNamingListener(target, filter, ctls, l); - } - - public void - addNamingListener(Name target, String filter, Object[] filterArgs, SearchControls ctls, NamingListener l) - throws NamingException { - check(target); - getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); - } - - public void addNamingListener(String target, String filter, Object[] filterArgs, SearchControls ctls, - NamingListener l) throws NamingException { - check(target); - getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingLdapContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingLdapContextDecorator.java deleted file mode 100644 index e361db8..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/AccessCheckingLdapContextDecorator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.NamingException; -import javax.naming.ldap.Control; -import javax.naming.ldap.ExtendedRequest; -import javax.naming.ldap.ExtendedResponse; -import javax.naming.ldap.LdapContext; - -/** - * - * - * @author Lukas Krejci - */ -public class AccessCheckingLdapContextDecorator extends AccessCheckingDirContextDecorator implements LdapContext { - - private static final long serialVersionUID = 1L; - - public AccessCheckingLdapContextDecorator(String... checkedSchemes) { - super(checkedSchemes); - } - - public AccessCheckingLdapContextDecorator(LdapContext original, String... checkedSchemes) { - super(original, checkedSchemes); - } - - @Override - protected LdapContext getOriginal() { - return (LdapContext) super.getOriginal(); - } - - public ExtendedResponse extendedOperation(ExtendedRequest request) throws NamingException { - check(); - return getOriginal().extendedOperation(request); - } - - public LdapContext newInstance(Control[] requestControls) throws NamingException { - check(); - return getOriginal().newInstance(requestControls); - } - - public void reconnect(Control[] connCtls) throws NamingException { - check(); - getOriginal().reconnect(connCtls); - } - - public Control[] getConnectControls() throws NamingException { - check(); - return getOriginal().getConnectControls(); - } - - public void setRequestControls(Control[] requestControls) throws NamingException { - check(); - getOriginal().setRequestControls(requestControls); - } - - public Control[] getRequestControls() throws NamingException { - check(); - return getOriginal().getRequestControls(); - } - - public Control[] getResponseControls() throws NamingException { - check(); - return getOriginal().getResponseControls(); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/ContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/ContextDecorator.java deleted file mode 100644 index 5755ebd..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/ContextDecorator.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Context; -import javax.naming.NamingException; - -/** - * - * - * @author Lukas Krejci - */ -public interface ContextDecorator extends Context { - - void init(Context context) throws NamingException; -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecorator.java deleted file mode 100644 index 3f3a95d..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecorator.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.io.Serializable; -import java.util.Hashtable; - -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; - -import org.rhq.jndi.AccessCheckingInitialContextFactoryBuilder; - -/** - * This is a wrapper class around another {@link Context} implementation that - * prefers to use an URL context for some operation if the JNDI name contains - * a scheme rather than the original. This is the behavior of {@link InitialContext} - * which we need to restore in the contexts created by the {@link AccessCheckingInitialContextFactoryBuilder} - * (which an {@link InitialContext} uses exclusively if the builder is set). - * <p> - * This is important because RHQ server has its own initial context factory - * builder that creates factories that in turn create contexts. If the default - * {@link InitialContext} implementation was used, we'd never be able to lookup - * scheme-based names because the default implementation of the {@link InitialContext} - * always uses the default context of the builder if one is installed no matter - * the scheme in the name. - * <p> - * The {@link AccessCheckingInitialContextFactoryBuilder} wraps the context returned - * by the factory in an instance of this class and thus is restoring the original - * intended behavior of the {@link InitialContext}. It looks at the name being looked - * up (bound or whatever) and prefers to use the URL context factories if the name - * contains the scheme (as does the {@link InitialContext} if no builder is installed). - * If the name doesn't contain a scheme, the provided default context factory is used to - * look up the name. - * - * @author Lukas Krejci - */ -public class URLPreferringContextDecorator implements Context, ContextDecorator, Serializable { - - private static final long serialVersionUID = 1L; - - private Context original; - - public URLPreferringContextDecorator() { - - } - - public URLPreferringContextDecorator(Context ctx) { - original = ctx; - } - - public void init(Context context) { - original = context; - } - - protected Context getOriginal() throws NamingException { - return original; - } - - protected Context getURLOrDefaultInitCtx(Name name) throws NamingException { - @SuppressWarnings("unchecked") - Context urlContext = URLPreferringContextDecoratorHelper.getURLContext(name, (Hashtable<Object, Object>) getEnvironment()); - return urlContext == null ? getOriginal() : urlContext; - } - - protected Context getURLOrDefaultInitCtx(String name) throws NamingException { - @SuppressWarnings("unchecked") - Context urlContext = URLPreferringContextDecoratorHelper.getURLContext(name, (Hashtable<Object, Object>) getEnvironment()); - return urlContext == null ? getOriginal() : urlContext; - } - - public Object lookup(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).lookup(name); - } - - public Object lookup(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).lookup(name); - } - - public void bind(Name name, Object obj) throws NamingException { - getURLOrDefaultInitCtx(name).bind(name, obj); - } - - public void bind(String name, Object obj) throws NamingException { - getURLOrDefaultInitCtx(name).bind(name, obj); - } - - public void rebind(Name name, Object obj) throws NamingException { - getURLOrDefaultInitCtx(name).rebind(name, obj); - } - - public void rebind(String name, Object obj) throws NamingException { - getURLOrDefaultInitCtx(name).rebind(name, obj); - } - - public void unbind(Name name) throws NamingException { - getURLOrDefaultInitCtx(name).unbind(name); - } - - public void unbind(String name) throws NamingException { - getURLOrDefaultInitCtx(name).unbind(name); - } - - public void rename(Name oldName, Name newName) throws NamingException { - getURLOrDefaultInitCtx(oldName).rename(oldName, newName); - } - - public void rename(String oldName, String newName) throws NamingException { - getURLOrDefaultInitCtx(oldName).rename(oldName, newName); - } - - public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).list(name); - } - - public NamingEnumeration<NameClassPair> list(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).list(name); - } - - public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).listBindings(name); - } - - public NamingEnumeration<Binding> listBindings(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).listBindings(name); - } - - public void destroySubcontext(Name name) throws NamingException { - getURLOrDefaultInitCtx(name).destroySubcontext(name); - } - - public void destroySubcontext(String name) throws NamingException { - getURLOrDefaultInitCtx(name).destroySubcontext(name); - } - - public Context createSubcontext(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).createSubcontext(name); - } - - public Context createSubcontext(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).createSubcontext(name); - } - - public Object lookupLink(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).lookupLink(name); - } - - public Object lookupLink(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).lookupLink(name); - } - - public NameParser getNameParser(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).getNameParser(name); - } - - public NameParser getNameParser(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).getNameParser(name); - } - - public Name composeName(Name name, Name prefix) throws NamingException { - return getOriginal().composeName(name, prefix); - } - - public String composeName(String name, String prefix) throws NamingException { - return getOriginal().composeName(name, prefix); - } - - public Object addToEnvironment(String propName, Object propVal) throws NamingException { - return getOriginal().addToEnvironment(propName, propVal); - } - - public Object removeFromEnvironment(String propName) throws NamingException { - return getOriginal().removeFromEnvironment(propName); - } - - public Hashtable<?, ?> getEnvironment() throws NamingException { - return getOriginal().getEnvironment(); - } - - public void close() throws NamingException { - if (getOriginal() != null) { - getOriginal().close(); - original = null; - } - } - - public String getNameInNamespace() throws NamingException { - return getOriginal().getNameInNamespace(); - } - - @Override - public int hashCode() { - return original == null ? super.hashCode() : original.hashCode(); - } - - @Override - public boolean equals(Object o) { - return original == null ? super.equals(o) : original.equals(o); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorHelper.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorHelper.java deleted file mode 100644 index 6e7debc..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorHelper.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.util.Hashtable; - -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.spi.NamingManager; - -/** - * - * - * @author Lukas Krejci - */ -public class URLPreferringContextDecoratorHelper { - - private URLPreferringContextDecoratorHelper() { - - } - - public static Context getURLContext(String name, Hashtable<Object, Object> env) throws NamingException { - String scheme = getURLScheme(name); - if (scheme != null) { - Context ctx = NamingManager.getURLContext(scheme, env); - if (ctx != null) { - return ctx; - } - } - - return null; - } - - public static Context getURLContext(Name name, Hashtable<Object, Object> env) throws NamingException { - if (name.size() > 0) { - String first = name.get(0); - String scheme = getURLScheme(first); - if (scheme != null) { - Context ctx = NamingManager.getURLContext(scheme, env); - if (ctx != null) { - return ctx; - } - } - } - - return null; - } - - //copied from InitialContext - private static String getURLScheme(String str) { - int colon_posn = str.indexOf(':'); - int slash_posn = str.indexOf('/'); - - if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn)) - return str.substring(0, colon_posn); - return null; - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorSetContext.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorSetContext.java deleted file mode 100644 index 828cd74..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringContextDecoratorSetContext.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import javax.naming.Context; - -import org.rhq.jndi.util.DecoratorSetContext; - -/** - * - * - * @author Lukas Krejci - */ -public class URLPreferringContextDecoratorSetContext implements DecoratorSetContext<Context, ContextDecorator> { - - private static final Set<Class<? extends ContextDecorator>> DECORATOR_CLASSES; - static { - HashSet<Class<? extends ContextDecorator>> tmp = new HashSet<Class<? extends ContextDecorator>>(); - tmp.add(URLPreferringContextDecorator.class); - tmp.add(URLPreferringDirContextDecorator.class); - tmp.add(URLPreferringEventContextDecorator.class); - tmp.add(URLPreferringEventDirContextDecorator.class); - tmp.add(URLPreferringLdapContextDecorator.class); - - DECORATOR_CLASSES = Collections.unmodifiableSet(tmp); - } - - private Set<Class<? extends Context>> supportedInterfaces; - - public URLPreferringContextDecoratorSetContext(Set<Class<? extends Context>> supportedInterfaces) { - this.supportedInterfaces = supportedInterfaces; - } - - public Set<Class<? extends Context>> getSupportedInterfaces() { - return supportedInterfaces; - } - - public Set<Class<? extends ContextDecorator>> getDecoratorClasses() { - return DECORATOR_CLASSES; - } - - public ContextDecorator instantiate(Class<? extends ContextDecorator> decoratorClass) throws Exception { - return decoratorClass.newInstance(); - } - - public void init(ContextDecorator decorator, Context object) throws Exception { - decorator.init(object); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringDirContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringDirContextDecorator.java deleted file mode 100644 index 6a49942..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringDirContextDecorator.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.NoInitialContextException; -import javax.naming.NotContextException; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; - -/** - * Akin to {@link URLPreferringContextDecorator} this class implements the similar logic - * for {@link DirContext}s. - * - * @author Lukas Krejci - */ -public class URLPreferringDirContextDecorator extends URLPreferringContextDecorator implements DirContext { - - private static final long serialVersionUID = 1L; - - public URLPreferringDirContextDecorator() { - super(null); - } - - public URLPreferringDirContextDecorator(DirContext ctx) { - super(ctx); - } - - protected DirContext checkAndCast(Context ctx) throws NamingException { - if (!(ctx instanceof DirContext)) { - if (ctx == null) { - throw new NoInitialContextException(); - } else { - throw new NotContextException( - "Not an instance of DirContext"); - } - } - - return (DirContext) ctx; - } - - @Override - protected DirContext getURLOrDefaultInitCtx(Name name) throws NamingException { - Context ctx = super.getURLOrDefaultInitCtx(name); - return checkAndCast(ctx); - } - - @Override - protected DirContext getURLOrDefaultInitCtx(String name) throws NamingException { - Context ctx = super.getURLOrDefaultInitCtx(name); - return checkAndCast(ctx); - } - - public Attributes getAttributes(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).getAttributes(name); - } - - public Attributes getAttributes(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).getAttributes(name); - } - - public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { - return getURLOrDefaultInitCtx(name).getAttributes(name, attrIds); - } - - public Attributes getAttributes(String name, String[] attrIds) throws NamingException { - return getURLOrDefaultInitCtx(name).getAttributes(name, attrIds); - } - - public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).modifyAttributes(name, mod_op, attrs); - } - - public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).modifyAttributes(name, mod_op, attrs); - } - - public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { - getURLOrDefaultInitCtx(name).modifyAttributes(name, mods); - } - - public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { - getURLOrDefaultInitCtx(name).modifyAttributes(name, mods); - } - - public void bind(Name name, Object obj, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).bind(name, obj, attrs); - } - - public void bind(String name, Object obj, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).bind(name, obj, attrs); - } - - public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).rebind(name, obj, attrs); - } - - public void rebind(String name, Object obj, Attributes attrs) throws NamingException { - getURLOrDefaultInitCtx(name).rebind(name, obj, attrs); - } - - public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { - return getURLOrDefaultInitCtx(name).createSubcontext(name, attrs); - } - - public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { - return getURLOrDefaultInitCtx(name).createSubcontext(name, attrs); - } - - public DirContext getSchema(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).getSchema(name); - } - - public DirContext getSchema(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).getSchema(name); - } - - public DirContext getSchemaClassDefinition(Name name) throws NamingException { - return getURLOrDefaultInitCtx(name).getSchemaClassDefinition(name); - } - - public DirContext getSchemaClassDefinition(String name) throws NamingException { - return getURLOrDefaultInitCtx(name).getSchemaClassDefinition(name); - } - - public NamingEnumeration<SearchResult> - search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, matchingAttributes, attributesToReturn); - } - - public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, - String[] attributesToReturn) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, matchingAttributes, attributesToReturn); - } - - public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, matchingAttributes); - } - - public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, matchingAttributes); - } - - public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, filter, cons); - } - - public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) - throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, filter, cons); - } - - public NamingEnumeration<SearchResult> - search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, filterExpr, filterArgs, cons); - } - - public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, - SearchControls cons) throws NamingException { - return getURLOrDefaultInitCtx(name).search(name, filterExpr, filterArgs, cons); - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventContextDecorator.java deleted file mode 100644 index e3298a0..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventContextDecorator.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.NoInitialContextException; -import javax.naming.NotContextException; -import javax.naming.event.EventContext; -import javax.naming.event.NamingListener; - -/** - * - * - * @author Lukas Krejci - */ -public class URLPreferringEventContextDecorator extends URLPreferringContextDecorator implements EventContext { - - private static final long serialVersionUID = 1L; - - public URLPreferringEventContextDecorator() { - super(null); - } - - public URLPreferringEventContextDecorator(EventContext ctx) { - super(ctx); - } - - protected EventContext checkAndCast(Context ctx) throws NamingException { - if (!(ctx instanceof EventContext)) { - if (ctx == null) { - throw new NoInitialContextException(); - } else { - throw new NotContextException( - "Not an instance of EventContext"); - } - } - - return (EventContext) ctx; - } - - @Override - protected EventContext getOriginal() throws NamingException { - return checkAndCast(super.getOriginal()); - } - - public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { - getOriginal().addNamingListener(target, scope, l); - } - - public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { - getOriginal().addNamingListener(target, scope, l); - } - - public void removeNamingListener(NamingListener l) throws NamingException { - getOriginal().removeNamingListener(l); - } - - public boolean targetMustExist() throws NamingException { - return getOriginal().targetMustExist(); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventDirContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventDirContextDecorator.java deleted file mode 100644 index 4925297..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringEventDirContextDecorator.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.NoInitialContextException; -import javax.naming.NotContextException; -import javax.naming.directory.SearchControls; -import javax.naming.event.EventDirContext; -import javax.naming.event.NamingListener; - -/** - * - * - * @author Lukas Krejci - */ -public class URLPreferringEventDirContextDecorator extends URLPreferringDirContextDecorator implements EventDirContext { - - private static final long serialVersionUID = 1L; - - public URLPreferringEventDirContextDecorator() { - super(null); - } - - public URLPreferringEventDirContextDecorator(EventDirContext ctx) { - super(ctx); - } - - @Override - protected EventDirContext checkAndCast(Context ctx) throws NamingException { - if (!(ctx instanceof EventDirContext)) { - if (ctx == null) { - throw new NoInitialContextException(); - } else { - throw new NotContextException( - "Not an instance of EventDirContext"); - } - } - - return (EventDirContext) ctx; - } - - @Override - protected EventDirContext getOriginal() throws NamingException { - return checkAndCast(super.getOriginal()); - } - - public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { - getOriginal().addNamingListener(target, scope, l); - } - - public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { - getOriginal().addNamingListener(target, scope, l); - } - - public void removeNamingListener(NamingListener l) throws NamingException { - getOriginal().removeNamingListener(l); - } - - public boolean targetMustExist() throws NamingException { - return getOriginal().targetMustExist(); - } - - public void addNamingListener(Name target, String filter, SearchControls ctls, NamingListener l) - throws NamingException { - getOriginal().addNamingListener(target, filter, ctls, l); - } - - public void addNamingListener(String target, String filter, SearchControls ctls, NamingListener l) - throws NamingException { - getOriginal().addNamingListener(target, filter, ctls, l); - } - - public void - addNamingListener(Name target, String filter, Object[] filterArgs, SearchControls ctls, NamingListener l) - throws NamingException { - getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); - } - - public void addNamingListener(String target, String filter, Object[] filterArgs, SearchControls ctls, - NamingListener l) throws NamingException { - getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringLdapContextDecorator.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringLdapContextDecorator.java deleted file mode 100644 index c74df39..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/context/URLPreferringLdapContextDecorator.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.NoInitialContextException; -import javax.naming.NotContextException; -import javax.naming.ldap.Control; -import javax.naming.ldap.ExtendedRequest; -import javax.naming.ldap.ExtendedResponse; -import javax.naming.ldap.LdapContext; - -/** - * - * - * @author Lukas Krejci - */ -public class URLPreferringLdapContextDecorator extends URLPreferringDirContextDecorator implements LdapContext { - - private static final long serialVersionUID = 1L; - - public URLPreferringLdapContextDecorator() { - super(null); - } - - public URLPreferringLdapContextDecorator(LdapContext original) { - super(original); - } - - @Override - protected LdapContext checkAndCast(Context ctx) throws NamingException { - if (!(ctx instanceof LdapContext)) { - if (ctx == null) { - throw new NoInitialContextException(); - } else { - throw new NotContextException("Not an instance of LdapContext"); - } - } - - return (LdapContext) ctx; - } - - @Override - protected LdapContext getOriginal() throws NamingException { - return checkAndCast(super.getOriginal()); - } - - public ExtendedResponse extendedOperation(ExtendedRequest request) throws NamingException { - return getOriginal().extendedOperation(request); - } - - public LdapContext newInstance(Control[] requestControls) throws NamingException { - return new URLPreferringLdapContextDecorator(getOriginal().newInstance(requestControls)); - } - - public void reconnect(Control[] connCtls) throws NamingException { - getOriginal().reconnect(connCtls); - } - - public Control[] getConnectControls() throws NamingException { - return getOriginal().getConnectControls(); - } - - public void setRequestControls(Control[] requestControls) throws NamingException { - getOriginal().setRequestControls(requestControls); - } - - public Control[] getRequestControls() throws NamingException { - return getOriginal().getRequestControls(); - } - - public Control[] getResponseControls() throws NamingException { - return getOriginal().getResponseControls(); - } - -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstaller.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstaller.java deleted file mode 100644 index a1ccb4f..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstaller.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.mbean; - -import javax.naming.spi.NamingManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.rhq.jndi.AccessCheckingInitialContextFactoryBuilder; - -/** - * - * - * @author Lukas Krejci - */ -public class AccessCheckingInitialContextFactoryBuilderInstaller implements AccessCheckingInitialContextFactoryBuilderInstallerMBean { - private static final Log LOG = LogFactory.getLog(AccessCheckingInitialContextFactoryBuilderInstaller.class); - - public void start() throws Exception { - LOG.info("Installing RHQ's access permission checking initial context factory builder"); - - NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder()); - } - - public void stop() throws Exception { - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstallerMBean.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstallerMBean.java deleted file mode 100644 index 87d19ab..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/mbean/AccessCheckingInitialContextFactoryBuilderInstallerMBean.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.mbean; - -/** - * - * - * @author Lukas Krejci - */ -public interface AccessCheckingInitialContextFactoryBuilderInstallerMBean { - - void start() throws Exception; - - void stop() throws Exception; -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratingInvocationHandler.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratingInvocationHandler.java deleted file mode 100644 index 1bfa7ac..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratingInvocationHandler.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.util; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; - -public class DecoratingInvocationHandler<Type, Decorator extends Type> implements InvocationHandler { - - private final List<DecoratorPicker<Type, Decorator>> pickers; - private Type object; - - public DecoratingInvocationHandler(List<DecoratorPicker<Type, Decorator>> pickers, Type object) { - this.pickers = pickers; - this.object = object; - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Type target = object; - Class<?> methodClass = method.getDeclaringClass(); - - for(DecoratorPicker<Type, Decorator> picker : pickers) { - target = picker.decorate(target, methodClass); - } - - try { - return method.invoke(target, args); - } catch (InvocationTargetException e) { - if (e.getCause() != null) { - throw e.getCause(); - } else { - throw e; - } - } - } -} \ No newline at end of file diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorPicker.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorPicker.java deleted file mode 100644 index 017d29f..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorPicker.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.util; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Given as set of decorators extending given type, this class can pick - * the most appropriate set of decorators for a class or a method call. - * <p> - * To configure the decorator, one has to provide a {@link DecoratorSetContext} that - * is then used to obtain the list of - * {@link DecoratorSetContext#getSupportedInterfaces() supported interfaces}, which are - * all the interfaces that should be used for decorator resolution (i.e. all other interfaces - * that a class might implement are ignored during decorator resolution), the list of - * {@link DecoratorSetContext#getDecoratorClasses() decorator classes}, which is a list - * of decorators the picker can choose from and is also used to instantiate and initialize - * the decorators. - * - * @author Lukas Krejci - */ -public class DecoratorPicker<Type, Decorator extends Type> { - - private DecoratorSetContext<Type, Decorator> context; - - public DecoratorSetContext<Type, Decorator> getContext() { - return context; - } - - public void setContext(DecoratorSetContext<Type, Decorator> decoratorSetContext) { - this.context = decoratorSetContext; - } - - /** - * Returns a set of decorators applicable for given method. The set is established based - * on the declaring class of the method. - * - * @param method the method to inspect - * @return the set of decorators that can be used to wrap a method call - * @throws Exception - */ - public Set<Decorator> getDecoratorsForMethod(Method method) throws Exception { - return getDecoratorsForClass_Private(method.getDeclaringClass()); - } - - /** - * Returns a set of decorators that can be used on instances of given class. - * @param cls the class to inspect - * @return - * @throws Exception - */ - public Set<Decorator> getDecoratorsForClass(Class<? extends Type> cls) throws Exception { - return getDecoratorsForClass_Private(cls); - } - - /** - * This method first establishes the set of decorators to use based on the class of the supplied - * object and then chains the decorators (in arbitrary order) with the supplied object at the - * "root" of the chain. - * <p> - * If a method is then called on the returned object, the methods of all the decorators are called - * in chain (each supposedly calling the next) and finally, at the end of the chain, the method on - * the original object (the one supplied to this method) is called. - * <p> - * Note that the above is only an intended behavior and actually depends on the implementation of - * the decorators that are resposinble for the chaining. Each decorator is initialized - * (@{link {@link DecoratorSetContext#init(Object, Object)} which should set it up for such chaining. - * - * @param object - * @return - * @throws Exception - */ - public Type decorate(Type object) throws Exception { - Set<Decorator> decs = getDecoratorsForClass_Private(object.getClass()); - Type ret = object; - for(Decorator d : decs) { - context.init(d, ret); - ret = d; - } - - return ret; - } - - /** - * Similar to {@link #decorate(Object)} but instead of the class of the object itself, - * uses the significantSuperClass as the basis for the decorator resolution. - * <p> - * This is important, because if the object implements two mutually incompatible sub-interfaces of <code>Type</code>, - * the chained decorators might fail to execute a method later on if the decorator depends on the upper part - * of the chain to implement certain sub-interface of <code>Type</code>. - * - * @param object the object to wrap in decorators - * @param significantSuperClass the class to base the decorator resolution on - * @return - * @throws Exception - */ - public Type decorate(Type object, Class<?> significantSuperClass) throws Exception { - Set<Decorator> decs = getDecoratorsForClass_Private(significantSuperClass); - Type ret = object; - for(Decorator d : decs) { - context.init(d, ret); - ret = d; - } - - return ret; - } - - private Set<Decorator> getDecoratorsForClass_Private(Class<?> cls) throws Exception { - Set<Class<? extends Type>> ifaces = getNearestApplicableInterfaces(cls); - - HashSet<Decorator> ret = new HashSet<Decorator>(); - - for (Class<? extends Type> iface : ifaces) { - for (Class<? extends Decorator> decClass : getMatch(iface)) { - ret.add(context.instantiate(decClass)); - } - } - - return ret; - } - - private Set<Class<? extends Type>> getNearestApplicableInterfaces(Class<?> cls) { - List<Class<? extends Type>> ifaces = new ArrayList<Class<? extends Type>>(getAllApplicableInterfaces(cls)); - - //now compact the set to only contain the most concrete interfaces - - Iterator<Class<? extends Type>> it = ifaces.iterator(); - while (it.hasNext()) { - Class<? extends Type> c = it.next(); - - for (int i = 0; i < ifaces.size(); ++i) { - Class<? extends Type> nextC = ifaces.get(i); - if (!c.equals(nextC) && c.isAssignableFrom(nextC)) { - it.remove(); - break; - } - } - } - - return new HashSet<Class<? extends Type>>(ifaces); - } - - private Set<Class<? extends Type>> getAllApplicableInterfaces(Class<?> cls) { - Set<Class<? extends Type>> ifaces = new HashSet<Class<? extends Type>>(); - - for (Class<? extends Type> iface : context.getSupportedInterfaces()) { - if (iface.isAssignableFrom(cls)) { - ifaces.add(iface); - } - } - - if (ifaces.isEmpty()) { - throw new IllegalArgumentException("Class " + cls - + " doesn't implement any of the applicable interfaces. Cannot find decorators for it."); - } - - return ifaces; - } - - private Set<Class<? extends Decorator>> getMatch(Class<?> targetIface) { - - Set<Class<? extends Decorator>> ret = new HashSet<Class<? extends Decorator>>(); - - for (Class<? extends Decorator> cls : context.getDecoratorClasses()) { - if (Arrays.asList(cls.getInterfaces()).contains(targetIface)) { - ret.add(cls); - } - } - - return ret; - } -} diff --git a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorSetContext.java b/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorSetContext.java deleted file mode 100644 index d7b1676..0000000 --- a/modules/enterprise/server/container-lib/src/main/java/org/rhq/jndi/util/DecoratorSetContext.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.util; - -import java.util.Set; - -/** - * Implementations of this interface provide a context to the {@link DecoratorPicker}. - * - * @author Lukas Krejci - */ -public interface DecoratorSetContext<Type, Decorator> { - - /** - * @return the set of interfaces that the decorators are able support. - * Usually this should be just a union of all interfaces the decorators implement - * but can be trimmed down. - */ - Set<Class<? extends Type>> getSupportedInterfaces(); - - /** - * @return the set of all decorator classes in this set - */ - Set<Class<? extends Decorator>> getDecoratorClasses(); - - /** - * Instantiates a new decorator of given class. - * @param decoratorClass - * @return - * @throws Exception - */ - Decorator instantiate(Class<? extends Decorator> decoratorClass) throws Exception; - - /** - * Initializes the decorator to decorate given object. - * - * @param decorator - * @param object - * @throws Exception on error - */ - void init(Decorator decorator, Type object) throws Exception; -} diff --git a/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratingInvocationHandlerTest.java b/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratingInvocationHandlerTest.java deleted file mode 100644 index 45ba114..0000000 --- a/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratingInvocationHandlerTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Properties; -import java.util.Set; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.event.EventContext; -import javax.naming.event.NamingListener; -import javax.naming.spi.InitialContextFactory; -import javax.naming.spi.NamingManager; - -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import org.rhq.jndi.AccessCheckingInitialContextFactoryBuilder; - -/** - * - * - * @author Lukas Krejci - */ -@Test -public class DecoratingInvocationHandlerTest { - private static final Set<String> INVOKED_METHODS = new HashSet<String>(); - - private static final InvocationHandler NOTE_TAKING_HANDLER = new InvocationHandler() { - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - INVOKED_METHODS.add(method.getName()); - - if ("hashCode".equals(method.getName())) { - return 0; - } else if ("equals".equals(method.getName())) { - return false; - } - - return null; - } - }; - - private static Class<?>[] CONTEXT_INTERFACES; - - public static class Factory implements InitialContextFactory { - public Context getInitialContext(Hashtable<?, ?> environment) - throws NamingException { - - return (Context) Proxy.newProxyInstance(DecoratingInvocationHandlerTest.class.getClassLoader(), CONTEXT_INTERFACES, NOTE_TAKING_HANDLER); - } - } - - private static class DummyInitialEventContext extends InitialContext implements EventContext { - - /** - * @param environment - * @throws NamingException - */ - public DummyInitialEventContext(Hashtable<?, ?> environment) throws NamingException { - super(environment); - } - - public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { - ((EventContext)getURLOrDefaultInitCtx(target)).addNamingListener(target, scope, l); - } - - public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { - ((EventContext)getURLOrDefaultInitCtx(target)).addNamingListener(target, scope, l); - } - - public void removeNamingListener(NamingListener l) throws NamingException { - ((EventContext)getDefaultInitCtx()).removeNamingListener(l); - } - - public boolean targetMustExist() throws NamingException { - return ((EventContext)getDefaultInitCtx()).targetMustExist(); - } - - - } - - @BeforeClass - public void setBuilder() throws Exception { - NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder()); - } - - public void testSimpleDispatch() throws Exception { - INVOKED_METHODS.clear(); - Properties env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, Factory.class.getName()); - - CONTEXT_INTERFACES = new Class<?>[] { Context.class }; - - InitialContext ctx = new InitialContext(env); - - ctx.lookup("asdf"); - - assert INVOKED_METHODS.contains("lookup") : "The lookup doesn't seem to have propagated to the actual context to be used."; - } - - public void testMultiInterfaceDispatch() throws Exception { - INVOKED_METHODS.clear(); - Properties env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, Factory.class.getName()); - - CONTEXT_INTERFACES = new Class<?>[] { EventContext.class, DirContext.class }; - - InitialContext ctx = new InitialContext(env); - - ctx.lookup("asdf"); - - DummyInitialEventContext ectx = new DummyInitialEventContext(env); - - ectx.addNamingListener("hodiny", 0, null); - - assert INVOKED_METHODS.contains("lookup") : "The lookup doesn't seem to have propagated to the actual context to be used."; - assert INVOKED_METHODS.contains("addNamingListener") : "The addNamingListener doesn't seem to have propagated to the actual context to be used."; - } -} diff --git a/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratorPickerTest.java b/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratorPickerTest.java deleted file mode 100644 index e2d7429..0000000 --- a/modules/enterprise/server/container-lib/src/test/java/org/rhq/jndi/context/DecoratorPickerTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2012 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.jndi.context; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import javax.naming.Context; -import javax.naming.directory.DirContext; -import javax.naming.event.EventContext; -import javax.naming.ldap.LdapContext; - -import org.testng.annotations.Test; - -import org.rhq.jndi.util.DecoratorPicker; -import org.rhq.jndi.util.DecoratorSetContext; - -/** - * @author Lukas Krejci - */ -@Test -public class DecoratorPickerTest { - - private static final InvocationHandler DUMMY_HANDLER = new InvocationHandler() { - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if ("hashCode".equals(method.getName())) { - return 0; - } else if ("equals".equals(method.getName())) { - return false; - } - - return null; - } - }; - - private static final Class<?> TEST_OBJECT_CLASS1 = createProxyClass(Context.class); - private static final Class<?> TEST_OBJECT_CLASS2 = createProxyClass(DirContext.class); - private static final Class<?> TEST_OBJECT_CLASS3 = createProxyClass(LdapContext.class); - private static final Class<?> TEST_OBJECT_CLASS4 = createProxyClass(LdapContext.class, EventContext.class); - private static final Class<?> DECORATOR_CLASS1 = createProxyClass(Context.class); - private static final Class<?> DECORATOR_CLASS2 = createProxyClass(EventContext.class); - private static final Class<?> DECORATOR_CLASS3 = createProxyClass(LdapContext.class); - private static final Class<?> DECORATOR_CLASS4 = createProxyClass(DirContext.class); - - public void testSimpleDecoratorIdentifiedByClass() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS1); - assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for Context class"); - assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], Context.class); - } - - public void testSuperClassDecoratorHasPrecedenceOverSubClassDecorator() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - //this tests that the LdapContext isn't returned even though it subclasses the DirContext - Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS2); - assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for DirContext class"); - assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], DirContext.class); - } - - public void testSubClassDecoratorCorrectlyIdentified() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS3); - assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for LdapContext class"); - assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); - } - - public void testMultipleDecoratorsDetectable() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - Set<Object> decorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS4); - assertEquals(decorators.size(), 2, - "Exactly 2 decorators should have been found for a class implementing 2 interfaces."); - - boolean ldapContextDecoratorFound = false; - boolean eventContextDecoratorFound = false; - - for (Object d : decorators) { - if (LdapContext.class.isAssignableFrom(d.getClass())) { - ldapContextDecoratorFound = true; - continue; //just to make sure that somehow the decorator doesn't implement both - } - if (EventContext.class.isAssignableFrom(d.getClass())) { - eventContextDecoratorFound = true; - } - } - - assertTrue(ldapContextDecoratorFound && eventContextDecoratorFound, - "The found decorators don't implement the desired interfaces."); - } - - public void testDecoratorsIdentifiedByMethod() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - Set<Object> decorators = - picker.getDecoratorsForMethod(LdapContext.class.getMethod("getConnectControls", (Class<?>[]) null)); - assertEquals(decorators.size(), 1, - "Expected exactly one decorator for method 'getConnectControls()' from LdapContext class"); - assertEquals(decorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); - } - - public void testMethodFromSubclassMatchesSubclassDecorator() throws Exception { - DecoratorPicker<Object, Object> picker = createTestPicker(); - - //this is a method from the DirContext but we're asking for it from a class - //that implements also an LdapContext - //The LdapContext decorator also inherits from the DirContext decorator - //(by the virtue of LdapContext interface inheriting from the DirContext) - //The picker should therefore match the LdapContext decorator because its - //the "closest" one to the actual class. - Set<Object> decorators = - picker.getDecoratorsForMethod(TEST_OBJECT_CLASS3.getMethod("getSchemaClassDefinition", - new Class<?>[] { String.class })); - assertEquals(decorators.size(), 1, - "Expected exactly one decorator for method 'getSchemaClassDefinition(String)' from LdapContext class"); - assertEquals(decorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); - } - - private static Class<?> createProxyClass(Class<?>... ifaces) { - return Proxy.getProxyClass(DecoratorPickerTest.class.getClassLoader(), ifaces); - } - - private static DecoratorPicker<Object, Object> createTestPicker() { - DecoratorPicker<Object, Object> picker = new DecoratorPicker<Object, Object>(); - - DecoratorSetContext<Object, Object> decSet = new DecoratorSetContext<Object, Object>() { - - public Object instantiate(Class<? extends Object> decoratorClass) throws Exception { - Constructor<? extends Object> ctor = decoratorClass.getConstructor(InvocationHandler.class); - return ctor.newInstance(DUMMY_HANDLER); - } - - public void init(Object decorator, Object object) throws Exception { - } - - @SuppressWarnings("unchecked") - public Set<Class<? extends Object>> getSupportedInterfaces() { - return new HashSet<Class<? extends Object>>(Arrays.asList(Context.class, EventContext.class, - LdapContext.class, DirContext.class)); - } - - @SuppressWarnings("unchecked") - public Set<Class<? extends Object>> getDecoratorClasses() { - return new HashSet<Class<? extends Object>>(Arrays.asList(DECORATOR_CLASS1, DECORATOR_CLASS2, DECORATOR_CLASS3, DECORATOR_CLASS4)); - } - }; - - picker.setContext(decSet); - - return picker; - } -} diff --git a/modules/enterprise/server/ear/pom.xml b/modules/enterprise/server/ear/pom.xml index 596b91c..9f7df36 100644 --- a/modules/enterprise/server/ear/pom.xml +++ b/modules/enterprise/server/ear/pom.xml @@ -125,10 +125,6 @@ <exclusions> <exclusion> <groupId>${project.groupId}</groupId> - <artifactId>rhq-container-lib</artifactId> - </exclusion> - <exclusion> - <groupId>${project.groupId}</groupId> <artifactId>rhq-enterprise-server</artifactId> </exclusion> </exclusions> diff --git a/modules/enterprise/server/ear/src/main/application/META-INF/jboss-deployment-structure.xml b/modules/enterprise/server/ear/src/main/application/META-INF/jboss-deployment-structure.xml index 8c4ad54..f3d48d1 100644 --- a/modules/enterprise/server/ear/src/main/application/META-INF/jboss-deployment-structure.xml +++ b/modules/enterprise/server/ear/src/main/application/META-INF/jboss-deployment-structure.xml @@ -16,6 +16,7 @@ <module name="org.dom4j" export="true" /> <!-- rhq ejb jar module declares this with runtime/provided scope --> <module name="javax.mail.api" export="true" /> <!-- for sending email notifications --> <module name="org.picketbox" export="true" /> <!-- for obfuscating passwords --> + <module name="org.jboss.as.naming" export="true" /> </dependencies> </deployment>
@@ -37,6 +38,8 @@ <module name="org.jboss.msc" export="true" /> <module name="org.jboss.as.controller" export="true" /> <module name="org.jboss.as.server" export="true" /> + <module name="org.jboss.modules" export="true" /> + <module name="org.jboss.as.naming" export="true" /> </dependencies> </sub-deployment>
diff --git a/modules/enterprise/server/itests-2/pom.xml b/modules/enterprise/server/itests-2/pom.xml index 1b50266..cc9c941 100644 --- a/modules/enterprise/server/itests-2/pom.xml +++ b/modules/enterprise/server/itests-2/pom.xml @@ -23,7 +23,7 @@ <properties> <jboss.zip>${settings.localRepository}/org/jboss/as/jboss-as-dist/${jboss.version}/jboss-as-dist-${jboss.version}.zip</jboss.zip> <jboss.unzip.location>${basedir}/target/jboss-as-${jboss.version}</jboss.unzip.location> - <jboss.vm.args>-Xmx700m -XX:MaxPermSize=200m</jboss.vm.args> + <jboss.vm.args>-Xmx700m -XX:MaxPermSize=200m -Djava.security.manager -Djava.security.policy==${jboss.unzip.location}/security.policy</jboss.vm.args> <jboss.vm.args.debug></jboss.vm.args.debug> <!-- -Ditest.debug can override this, see below --> </properties>
@@ -223,7 +223,13 @@ <echo>Unzipping JBossAS ${jboss.version} found at ${jboss.zip}</echo> <unzip src="${jboss.zip}" dest="${jboss.unzip.location}/.." /> <echo>JBossAS ${jboss.version} should now be at: ${jboss.unzip.location}</echo> - <property name="jboss.conf" location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> + + <echo>Copying security policy to JBossAS</echo> + <copy file="${project.build.directory}/test-classes/security.policy" tofile="${jboss.unzip.location}/security.policy"/> + + <property + name="jboss.conf" + location="${jboss.unzip.location}/standalone/configuration/standalone.xml" /> <echo>Will now add test configuration to JBossAS config file: ${jboss.conf}</echo> <replace file="${jboss.conf}">
@@ -653,7 +659,6 @@ <skipTests>${skipTests}</skipTests> <excludes> <!-- NOTE: PERF GROUP AND SOME CLASSES EXCLUDED (SEE BZ 874696) --> - <exclude>**/JndiAccessTest.java</exclude> <exclude>**/LdapGroupManagerBeanTest.java</exclude> <exclude>**/SynchronizationManagerBeanTest.java</exclude> <exclude>org/rhq/**/performance/**/*.java</exclude> diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java index 274e94f..fabe6ae 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/client/security/test/JndiAccessTest.java @@ -24,6 +24,7 @@ import java.io.PrintWriter; import java.security.PermissionCollection; import java.util.Collections;
+import javax.naming.Context; import javax.script.ScriptEngine; import javax.script.ScriptException;
@@ -37,10 +38,9 @@ import org.rhq.bindings.util.PackageFinder; import org.rhq.core.domain.auth.Subject; import org.rhq.enterprise.client.LocalClient; import org.rhq.enterprise.server.RHQConstants; -import org.rhq.enterprise.server.auth.SubjectManagerBean; +import org.rhq.enterprise.server.system.SystemManagerBean; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil; -import org.rhq.jndi.AllowRhqServerInternalsAccessPermission;
/** * @@ -50,6 +50,21 @@ import org.rhq.jndi.AllowRhqServerInternalsAccessPermission; @Test public class JndiAccessTest extends AbstractEJB3Test {
+ public void testScriptCantOverrideSystemProperties() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); + + ScriptEngine engine = getEngine(overlord); + + try { + engine.eval("java.lang.System.setProperty('java.naming.factory.url.pkgs', 'counterfeit');"); + } catch (ScriptException e) { + Assert.assertTrue( + e.getMessage().contains( + "access denied ("java.util.PropertyPermission" "java.naming.factory.url.pkgs" "write")"), + "The script shouldn't have write access to the system properties."); + } + } + public void testEjbsAccessibleThroughPrivilegedCode() { LookupUtil.getSubjectManager().getOverlord(); } @@ -67,14 +82,18 @@ public class JndiAccessTest extends AbstractEJB3Test {
ScriptEngine engine = getEngine(overlord);
- String jndiName = "java:global/rhq/rhq-enterprise-server-ejb3/" + SubjectManagerBean.class.getSimpleName() - + "!" + SubjectManagerBean.class.getName().replace("Bean", "Local"); + String jndiName = "java:global/rhq/rhq-enterprise-server-ejb3/" + + SystemManagerBean.class.getSimpleName() + + "!" + + SystemManagerBean.class.getName().replace("Bean", "Local");
try { engine.eval("" + "var ctx = new javax.naming.InitialContext();\n" - + "var subjectManager = ctx.lookup('" + jndiName + "');\n" - + "subjectManager.getOverlord();"); + + "var systemManager = ctx.lookup('" + + jndiName + + "');\n" + + "systemManager.isDebugModeEnabled();");
Assert.fail("The script shouldn't have been able to call local SLSB method."); } catch (ScriptException e) { @@ -82,19 +101,51 @@ public class JndiAccessTest extends AbstractEJB3Test { } }
+ public void testLocalEjbsInaccessibleThroughJndiLookupWithCustomUrlPackages() throws ScriptException, IOException { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); + + ScriptEngine engine = getEngine(overlord); + + String jndiName = "java:global/rhq/rhq-enterprise-server-ejb3/" + + SystemManagerBean.class.getSimpleName() + + "!" + + SystemManagerBean.class.getName().replace("Bean", "Local"); + + try { + engine.eval("" + + "var env = new java.util.Hashtable();\n" + + "env.put('" + + Context.URL_PKG_PREFIXES + + "', 'org.jboss.as.naming.interfaces');\n" + + "var ctx = new javax.naming.InitialContext(env);\n" + + "var systemManager = ctx.lookup('" + + jndiName + + "');\n" + + "systemManager.isDebugModeEnabled();"); + + Assert.fail("The script shouldn't have been able to call local SLSB method."); + } catch (ScriptException e) { + checkIsDesiredSecurityException(e); + } + } + public void testRemoteEjbsInaccessibleThroughJndiLookup() throws ScriptException, IOException { Subject overlord = LookupUtil.getSubjectManager().getOverlord();
ScriptEngine engine = getEngine(overlord);
- String jndiName = "java:global/rhq/rhq-enterprise-server-ejb3/" + SubjectManagerBean.class.getSimpleName() - + "!" + SubjectManagerBean.class.getName().replace("Bean", "Remote"); + String jndiName = "java:global/rhq/rhq-enterprise-server-ejb3/" + + SystemManagerBean.class.getSimpleName() + + "!" + + SystemManagerBean.class.getName().replace("Bean", "Remote");
try { engine.eval("" + "var ctx = new javax.naming.InitialContext();\n" - + "var subjectManager = ctx.lookup('" + jndiName + "');\n" - + "subjectManager.getSubjectByName('rhqadmin');"); + + "var systemManager = ctx.lookup('" + + jndiName + + "');\n" + + "systemManager.getSystemSettings(subject);");
Assert.fail("The script shouldn't have been able to call remote SLSB method directly."); } catch (ScriptException e) { @@ -198,7 +249,29 @@ public class JndiAccessTest extends AbstractEJB3Test { checkIsNotASecurityException(e); } } - + + //THIS IS A NEW REQUIREMENT THAT DOESN'T CURRENTLY WORK... + // public void testInitialContextFactoryBuilderNotReplaceableUsingScripts() throws Exception { + // Subject overlord = LookupUtil.getSubjectManager().getOverlord(); + // + // ScriptEngine engine = getEngine(overlord); + // + // try { + // engine.eval("" + // + "var mgrCls = java.lang.Class.forName('javax.naming.spi.NamingManager');\n" + // + "var fld = mgrCls.getDeclaredField('initctx_factory_builder');\n" + // + "fld.setAccessible(true);\n" + // + "fld.set(null, null);\n"); + // + // Assert.fail("It should not be possible to use reflection to reset the initial context factory builder."); + // } catch (ScriptException e) { + // checkIsDesiredSecurityException(e); + // } finally { + // //restore the default behavior + // NamingHack.bruteForceInitialContextFactoryBuilder(); + // } + // } + private ScriptEngine getEngine(Subject subject) throws ScriptException, IOException { StandardBindings bindings = new StandardBindings(new PrintWriter(System.out), new LocalClient(subject));
@@ -210,15 +283,25 @@ public class JndiAccessTest extends AbstractEJB3Test {
private static void checkIsDesiredSecurityException(ScriptException e) { String message = e.getMessage(); - String permissionTrace = AllowRhqServerInternalsAccessPermission.class.getName(); + String permissionTrace = "org.rhq.allow.server.internals.access";
- Assert.assertTrue(message.contains(permissionTrace), "The script exception doesn't seem to be caused by the AllowRhqServerInternalsAccessPermission security exception. " + message); + if (!message.contains(permissionTrace)) { + Assert + .fail( + "The script exception doesn't seem to be caused by the AllowRhqServerInternalsAccessPermission security exception. ", + e); + } }
private static void checkIsNotASecurityException(ScriptException e) { String message = e.getMessage(); - String permissionTrace = AllowRhqServerInternalsAccessPermission.class.getName(); + String permissionTrace = "org.rhq.allow.server.internals.access";
- Assert.assertFalse(message.contains(permissionTrace), "The script exception does seem to be caused by the AllowRhqServerInternalsAccessPermission security exception although it shouldn't. " + message); + if (message.contains(permissionTrace)) { + Assert + .fail( + "The script exception does seem to be caused by the AllowRhqServerInternalsAccessPermission security exception although it shouldn't. ", + e); + } } } diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java index f1ba91f..f27a5ba 100644 --- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java @@ -39,6 +39,7 @@ import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.Filters; import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.ClassAsset; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; @@ -308,6 +309,13 @@ public abstract class AbstractEJB3Test extends Arquillian { testEar.delete(ArchivePaths .create("/rhq-enterprise-server-ejb3.jar/org/rhq/enterprise/server/core/ShutdownListener.class"));
+ //replace the above startup beans with stripped down versions + testEar.add(new ClassAsset(StrippedDownStartupBean.class), ArchivePaths + .create("/rhq-enterprise-server-ejb3.jar/org/rhq/enterprise/server/test/StrippedDownStartupBean.class")); + testEar.add(new ClassAsset(StrippedDownStartupBeanPreparation.class), ArchivePaths + .create("/rhq-enterprise-server-ejb3.jar/org/rhq/enterprise/server/test/" + + "StrippedDownStartupBeanPreparation.class")); + // add the test classes to the deployment testEar.addAsLibrary(testClassesJar);
diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBean.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBean.java new file mode 100644 index 0000000..bfe9f32 --- /dev/null +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBean.java @@ -0,0 +1,45 @@ +/* + * RHQ Management Platform + * Copyright 2012, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.test; + +import javax.ejb.Singleton; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; + +import org.rhq.enterprise.server.core.StartupBean; +import org.rhq.enterprise.server.naming.NamingHack; + +/** + * This is a replacement for the fullblown {@link StartupBean} of the actual RHQ server. + * @author Lukas Krejci + */ +@Singleton +public class StrippedDownStartupBean { + + @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) + public void secureNaming() { + NamingHack.bruteForceInitialContextFactoryBuilder(); + } + + public void init() { + secureNaming(); + } +} diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBeanPreparation.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBeanPreparation.java new file mode 100644 index 0000000..e32d8a4 --- /dev/null +++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/test/StrippedDownStartupBeanPreparation.java @@ -0,0 +1,75 @@ +/* + * RHQ Management Platform + * Copyright 2012, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.test; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.ejb.Singleton; +import javax.ejb.Startup; +import javax.ejb.Timeout; +import javax.ejb.TimerConfig; +import javax.ejb.TimerService; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * This startup singleton EJB is here to work around bug AS7-5530 and to + * schedule the real StartupBean's work in a delayed fashion (this is to allow + * AS7 to complete its deployment work before we do our work). + * + * See https://issues.jboss.org/browse/AS7-5530 + * + * This version is a replacement for the original code (identical) code that uses the StrippedDownStartupBean instead + * of the fullblown original. + */ +@Singleton +@Startup +public class StrippedDownStartupBeanPreparation { + private Log log = LogFactory.getLog(this.getClass()); + + @EJB + private StrippedDownStartupBean startupBean; + + @Resource + private TimerService timerService; // needed to schedule our startup bean init call + + @PostConstruct + public void initWithTransactionBecauseAS75530() throws RuntimeException { + log.info("Scheduling the initialization of the testing RHQ deployment"); + timerService.createSingleActionTimer(1, new TimerConfig(null, false)); // call StartupBean in 1ms + } + + @Timeout + public void initializeServer() throws RuntimeException { + try { + log.info("Initializing the testing RHQ deployment"); + this.startupBean.init(); + } catch (Throwable t) { + // do NOT allow exceptions to bubble out of our method because then + // the EJB container would simply re-trigger the timer and call us again + // and we don't want to keep failing over and over filling the logs + // in an infinite loop. + log.fatal("The server failed to start up properly", t); + } + } +} diff --git a/modules/enterprise/server/itests-2/src/test/resources/security.policy b/modules/enterprise/server/itests-2/src/test/resources/security.policy new file mode 100644 index 0000000..8860b47 --- /dev/null +++ b/modules/enterprise/server/itests-2/src/test/resources/security.policy @@ -0,0 +1,10 @@ +// We need the SecurityManager installed to enable sandboxing of CLI scripts +// but we don't define any other security measures on the RHQ server itself. +// +// Granting all permissions allows us to run the RHQ server as if no security +// manager was in place (which is assumed by default by JBoss AS) but be able +// to use it when we need it for our own purposes. + +grant { + permission java.security.AllPermission; +}; diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index 87674b0..f035ed6 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -88,12 +88,6 @@ </dependency>
<dependency> - <groupId>org.rhq</groupId> - <artifactId>rhq-container-lib</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> <groupId>com.googlecode.java-diff-utils</groupId> <artifactId>diffutils</artifactId> <version>1.2.1</version> @@ -108,10 +102,14 @@ <dependency> <groupId>org.jboss.as</groupId> <artifactId>jboss-as-server</artifactId> - <version>${jboss.version}</version> <scope>provided</scope> <!-- provided by AS7 --> </dependency>
+ <dependency> + <groupId>org.jboss.as</groupId> + <artifactId>jboss-as-naming</artifactId> + <scope>provided</scope> <!-- provided by AS7 --> + </dependency>
<!--================ Test Deps ================-->
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/AllowRhqServerInternalsAccessPermission.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/AllowRhqServerInternalsAccessPermission.java new file mode 100644 index 0000000..d448049 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/AllowRhqServerInternalsAccessPermission.java @@ -0,0 +1,36 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server; + +import java.security.BasicPermission; + +/** + * + * + * @author Lukas Krejci + */ +public class AllowRhqServerInternalsAccessPermission extends BasicPermission { + + private static final long serialVersionUID = 1L; + + public AllowRhqServerInternalsAccessPermission() { + super("org.rhq.allow.server.internals.access"); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java index ecf2f6f..8819cab 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SessionManager.java @@ -25,8 +25,8 @@ import java.util.Map; import java.util.Random;
import org.rhq.core.domain.auth.Subject; +import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; import org.rhq.enterprise.server.util.LookupUtil; -import org.rhq.jndi.AllowRhqServerInternalsAccessPermission;
/** * This is the JON Server's own session ID generator. It is outside any container-provided session mechanism. Its sole diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/StartupBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/StartupBean.java index a5a38d3..f48c228 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/StartupBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/StartupBean.java @@ -69,6 +69,7 @@ import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal; import org.rhq.enterprise.server.cloud.instance.SyncEndpointAddressException; import org.rhq.enterprise.server.core.comm.ServerCommunicationsServiceUtil; import org.rhq.enterprise.server.core.plugin.PluginDeploymentScannerMBean; +import org.rhq.enterprise.server.naming.NamingHack; import org.rhq.enterprise.server.plugin.pc.MasterServerPluginContainer; import org.rhq.enterprise.server.plugin.pc.ServerPluginServiceMBean; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; @@ -138,6 +139,16 @@ public class StartupBean { private DataSource dataSource;
/** + * Modifies the naming subsystem to be able to check for Java security permissions on JNDI lookup. + * <p> + * Made public so that this can be reused in tests. + */ + @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) + public void secureNaming() { + NamingHack.bruteForceInitialContextFactoryBuilder(); + } + + /** * Performs the final RHQ Server initialization work that needs to talk place. EJBs are available in this method. * * @throws RuntimeException @@ -145,6 +156,8 @@ public class StartupBean { //@PostConstruct // when AS7-5530 is fixed, uncomment this and remove class StartupBeanToWorkaroundAS7_5530 @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void init() throws RuntimeException { + secureNaming(); + initialized = false;
log.info("All business tier deployments are complete - finishing the startup..."); @@ -824,5 +837,4 @@ public class StartupBean { + ") Server started."); log.info("--------------------------------------------------"); // 50 dashes } - } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java new file mode 100644 index 0000000..9681014 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/AccessCheckingInitialContextFactoryBuilder.java @@ -0,0 +1,295 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.server.naming; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.event.EventContext; +import javax.naming.event.EventDirContext; +import javax.naming.ldap.LdapContext; +import javax.naming.spi.InitialContextFactory; +import javax.naming.spi.InitialContextFactoryBuilder; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; +import org.rhq.enterprise.server.naming.context.AccessCheckingContextDecorator; +import org.rhq.enterprise.server.naming.context.AccessCheckingContextDecoratorSetContext; +import org.rhq.enterprise.server.naming.context.ContextDecorator; +import org.rhq.enterprise.server.naming.context.URLPreferringContextDecoratorSetContext; +import org.rhq.enterprise.server.naming.util.DecoratorPicker; + +/** + * This initial context factory builder is installed early on during the RHQ server startup + * and is later on used for obtaining the {@link Context}s for all JNDI lookups in the + * RHQ server. + * <p> + * We use a custom initial context factory builder to prevent the potential malicious 3rd party + * code (like CLI alert scripts) from supplying custom environment variables to {@link InitialContext} + * that would modify the JNDI lookup to skip our security access checks. + * <p> + * By using a builder we effectively take control of the initial context creation process + * and are free to ignore whatever the script is trying to supply. + * <p> + * This builder makes sure to install the RHQ server's security access checks to whatever + * initial context that is configured by the standard environment variables + * ({@link Context#INITIAL_CONTEXT_FACTORY}, etc.) + * + * @see AllowRhqServerInternalsAccessPermission + * + * @author Lukas Krejci + */ +public class AccessCheckingInitialContextFactoryBuilder implements InitialContextFactoryBuilder { + private static final Log LOG = LogFactory.getLog(AccessCheckingInitialContextFactoryBuilder.class); + + /** + * The list of JNDI name schemes that should be checked for security permissions + * (in addition to the names with no scheme). + * + * @see AccessCheckingContextDecorator + */ + private static final String[] CHECKED_SCHEMES = { "java" }; + + private static final Set<Class<? extends Context>> SUPPORTED_CONTEXT_INTERFACES; + + static { + SUPPORTED_CONTEXT_INTERFACES = new HashSet<Class<? extends Context>>(); + SUPPORTED_CONTEXT_INTERFACES.add(Context.class); + SUPPORTED_CONTEXT_INTERFACES.add(DirContext.class); + SUPPORTED_CONTEXT_INTERFACES.add(EventContext.class); + SUPPORTED_CONTEXT_INTERFACES.add(EventDirContext.class); + SUPPORTED_CONTEXT_INTERFACES.add(LdapContext.class); + } + + private static final Set<InetAddress> SERVER_BIND_IPS; + static { + SERVER_BIND_IPS = new HashSet<InetAddress>(); + + try { + String bindingAddressString = System.getProperty("jboss.bind.address"); + InetAddress bindingAddress = InetAddress.getByName(bindingAddressString); + + if (bindingAddress.isAnyLocalAddress()) { + Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); + while (ifaces.hasMoreElements()) { + NetworkInterface iface = ifaces.nextElement(); + SERVER_BIND_IPS.addAll(Collections.list(iface.getInetAddresses())); + } + } else { + SERVER_BIND_IPS.add(bindingAddress); + } + } catch (SocketException e) { + LOG.error("Could not obtain the list of local IPs", e); + } catch (UnknownHostException e) { + LOG.error("Failed to get the binding address of the RHQ server.", e); + } + } + + //TODO this most probably no longer applies because AS7 doesn't use JNP for JNDI + private static final int JNP_PORT = Integer.parseInt(System.getProperty("rhq.server.startup.namingservice.port", + "2099")); + + private static InitialContextFactory getJbossDefaultInitialContextFactory() throws NamingException { + try { + Class<?> cls = Class.forName("org.jboss.as.naming.InitialContextFactory"); + return (InitialContextFactory) cls.newInstance(); + } catch (Exception e) { + NamingException ne = new NamingException( + "Failed to obtain the default initial context factory from JBoss AS."); + ne.initCause(e); + + throw ne; + } + } + + private enum FactoryType { + ACCESS_CHECKING { + + @Override + public InitialContextFactory wrap(InitialContextFactory factory) { + ArrayList<DecoratorPicker<Context, ContextDecorator>> pickers = new ArrayList<DecoratorPicker<Context, ContextDecorator>>(); + pickers.add(getURLPreferringDecoratorPicker()); + pickers.add(getAccessCheckingDecoratorPicker()); + + return new DecoratingInitialContextFactory(factory, pickers); + } + }, + URL_PREFERRING { + + @Override + public InitialContextFactory wrap(InitialContextFactory factory) { + ArrayList<DecoratorPicker<Context, ContextDecorator>> pickers = new ArrayList<DecoratorPicker<Context, ContextDecorator>>(); + pickers.add(getURLPreferringDecoratorPicker()); + + return new DecoratingInitialContextFactory(factory, pickers); + } + }; + + public abstract InitialContextFactory wrap(InitialContextFactory factory); + + public static FactoryType detect(Hashtable<?, ?> environment) { + String providerUrl = (String) environment.get(Context.PROVIDER_URL); + + if (providerUrl == null) { + return ACCESS_CHECKING; + } else { + try { + URI uri = new URI(providerUrl); + InetAddress providerHost = InetAddress.getByName(uri.getHost()); + + //check if we are accessing the RHQ server through some remoting + //interface. + if (uri.getPort() == JNP_PORT && SERVER_BIND_IPS.contains(providerHost)) { + return ACCESS_CHECKING; + } else { + return URL_PREFERRING; + } + } catch (URISyntaxException e) { + if (LOG.isDebugEnabled()) { + LOG.debug("The " + + Context.PROVIDER_URL + + " is not a valid URI. Falling back to using the access checking wrapper.", e); + } + return ACCESS_CHECKING; + } catch (UnknownHostException e) { + //let the factory deal with the unknown host... + //this most probably shouldn't be secured because localhost addresses + //should be resolvable. + if (LOG.isDebugEnabled()) { + LOG.debug("The " + + Context.PROVIDER_URL + + " is not resolvable. Falling back to using the URL preferring wrapper.", e); + } + return URL_PREFERRING; + } + } + } + + private static DecoratorPicker<Context, ContextDecorator> getAccessCheckingDecoratorPicker() { + DecoratorPicker<Context, ContextDecorator> ret = new DecoratorPicker<Context, ContextDecorator>(); + ret.setContext(new AccessCheckingContextDecoratorSetContext(SUPPORTED_CONTEXT_INTERFACES, CHECKED_SCHEMES)); + + return ret; + } + + private static DecoratorPicker<Context, ContextDecorator> getURLPreferringDecoratorPicker() { + DecoratorPicker<Context, ContextDecorator> ret = new DecoratorPicker<Context, ContextDecorator>(); + ret.setContext(new URLPreferringContextDecoratorSetContext(SUPPORTED_CONTEXT_INTERFACES)); + + return ret; + } + } + + private final EnumMap<FactoryType, InitialContextFactory> typeDefaults = new EnumMap<FactoryType, InitialContextFactory>( + FactoryType.class); + + private final String defaultFactoryClassName; + + /** + * @param defaultFactory the default factory to use if none can be deduced from the environment. If null, an attempt + * is made to obtain the default InitialContextFactory of JBoss AS (which may fail depending on the classloading + * "situation"). + * + * @throws NamingException + */ + public AccessCheckingInitialContextFactoryBuilder(InitialContextFactory defaultFactory) throws NamingException { + if (defaultFactory == null) { + defaultFactory = getJbossDefaultInitialContextFactory(); + } + + defaultFactoryClassName = defaultFactory.getClass().getName(); + + for (FactoryType ft : FactoryType.values()) { + typeDefaults.put(ft, ft.wrap(defaultFactory)); + } + } + + /** + * This is the default initial context factory that is returned when no other is + * configured using the environment variables. + * <p> + * It uses {@link NamingContextFactory} as the underlying mechanism - the same + * as the default configuration in JBoss 4. + */ + private final InitialContextFactory defaultFactory = new InitialContextFactory() { + public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { + return typeDefaults.get(FactoryType.detect(environment)).getInitialContext( + environment); + } + }; + + /** + * Create a InitialContext factory. If the environment does not override the factory class it will use the + * default context factory. + * + * @param environment The environment + * @return An initial context factory + * @throws NamingException If an error occurs loading the factory class. + */ + public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException { + final String factoryClassName = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY); + if (factoryClassName == null || factoryClassName.equals(defaultFactoryClassName)) { + if (LOG.isDebugEnabled()) { + LOG.debug("No " + Context.INITIAL_CONTEXT_FACTORY + " set. Using the default factory."); + } + return defaultFactory; + } + final ClassLoader classLoader = getContextClassLoader(); + try { + final Class<?> factoryClass = Class.forName(factoryClassName, true, classLoader); + InitialContextFactory configuredFactory = (InitialContextFactory) factoryClass.newInstance(); + return FactoryType.detect(environment).wrap(configuredFactory); + } catch (Exception e) { + NamingException ne = new NamingException("Failed instantiate InitialContextFactory " + + factoryClassName + + " from classloader " + + classLoader); + ne.initCause(e); + + throw ne; + } + } + + private ClassLoader getContextClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } + }); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/DecoratingInitialContextFactory.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/DecoratingInitialContextFactory.java new file mode 100644 index 0000000..602a68c --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/DecoratingInitialContextFactory.java @@ -0,0 +1,110 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming; + +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +import org.rhq.enterprise.server.naming.context.ContextDecorator; +import org.rhq.enterprise.server.naming.util.DecoratingInvocationHandler; +import org.rhq.enterprise.server.naming.util.DecoratorPicker; + +/** + * This class implements an initial context factory that decorates the contexts + * returned from a "wrapped" initial factory passed to this class in the constructor. + * <p> + * The contexts returned from the wrapped initial factory are hidden behind a proxy + * that implements the intersection of interfaces from the <code>supportedContextInterfaces</code> + * constructor parameter and the actual interfaces the wrapped context implements. + * <p> + * The proxy method calls are handled using the {@link DecoratingInvocationHandler} which is initialized + * with the list of {@link DecoratorPicker pickers} that are used to intercept the method + * calls on the wrapped context. + * + * @see DecoratorPicker + * @see DecoratingInvocationHandler + * + * @author Lukas Krejci + */ +public class DecoratingInitialContextFactory implements InitialContextFactory { + + List<DecoratorPicker<Context, ContextDecorator>> pickers; + private InitialContextFactory factory; + private Set<Class<? extends Context>> supportedContextInterfaces; + + public DecoratingInitialContextFactory(InitialContextFactory factory, List<DecoratorPicker<Context, ContextDecorator>> decoratorPickers) { + this.factory = factory; + this.pickers = decoratorPickers; + this.supportedContextInterfaces = new HashSet<Class<? extends Context>>(); + for(DecoratorPicker<Context, ContextDecorator> picker : pickers) { + supportedContextInterfaces.addAll(picker.getContext().getSupportedInterfaces()); + } + } + + public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { + Context ctx = factory.getInitialContext(environment); + + Set<Class<?>> implementedIfaces = getAllImplementedInterfaces(ctx.getClass()); + Class<?>[] ii = new Class<?>[implementedIfaces.size()]; + implementedIfaces.toArray(ii); + + return (Context) Proxy.newProxyInstance(ctx.getClass().getClassLoader(), ii, new DecoratingInvocationHandler<Context, ContextDecorator>(pickers, ctx)); + } + + private Set<Class<?>> getAllImplementedInterfaces(Class<?> cls) { + HashSet<Class<?>> ret = new HashSet<Class<?>>(); + getAllImplementedInterfaces(cls, ret); + + ret.retainAll(supportedContextInterfaces); + + return ret; + } + + private static void getAllImplementedInterfaces(Class<?> cls, Set<Class<?>> output) { + Class<?>[] ifaces = cls.getInterfaces(); + + for (Class<?> iface : Arrays.asList(ifaces)) { + output.add(iface); + getAllImplementedInterfaces(iface, output); + } + + if (cls.getSuperclass() != null) { + getAllImplementedInterfaces(cls.getSuperclass(), output); + } + } + + @Override + public int hashCode() { + return factory.hashCode(); + } + + @Override + public boolean equals(Object o) { + return factory.equals(o); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java new file mode 100644 index 0000000..f21322f --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/NamingHack.java @@ -0,0 +1,103 @@ +/* + * RHQ Management Platform + * Copyright 2012, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming; + +import java.lang.reflect.Field; +import java.util.Hashtable; + +import javax.naming.spi.InitialContextFactory; +import javax.naming.spi.InitialContextFactoryBuilder; +import javax.naming.spi.NamingManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * @author Lukas Krejci + */ +public class NamingHack { + + private static final Log LOG = LogFactory.getLog(NamingHack.class); + + //in case this method is called multiple times, which can happen during the tests, + //remember the builder encountered the first time... + private static InitialContextFactoryBuilder originalBuilder; + + public static void bruteForceInitialContextFactoryBuilder() { + LOG.info("Modifying the naming subsystem to enable secure execution of scripts inside the server..."); + + //it is important to synchronize on the NamingManager class because the get/setInitialContextFactoryBuilder + //methods in that class are static synchronized. By holding the lock on the NamingManager class we prevent + //any other thread to check for the initial context factory builder (and therefore de-facto do any JNDI lookup). + synchronized (NamingManager.class) { + + if (NamingManager.hasInitialContextFactoryBuilder()) { + //if anyone ever changes the implementation of the NamingManager, we will break here... + //but as of now, we have no other option but to do this and wait for + //https://issues.jboss.org/browse/AS7-6109 to be resolved and incorporated into our underlying container + + try { + Field f = NamingManager.class.getDeclaredField("initctx_factory_builder"); + f.setAccessible(true); + + if (originalBuilder == null) { + originalBuilder = (InitialContextFactoryBuilder) f.get(null); + } + + f.set(null, null); + } catch (Exception e) { + LOG.error( + "Failed to install a custom initial context factory builder. RHQ installation is unsecure!", e); + + return; + } + } + + try { + InitialContextFactory defaultFactory = null; + if (originalBuilder != null) { + defaultFactory = originalBuilder + .createInitialContextFactory(new Hashtable<String, String>()); + } + + NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder( + defaultFactory)); + } catch (Exception e) { + LOG.error("Failed to install a custom initial context factory builder. RHQ installation is unsecure!", + e); + + if (originalBuilder != null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Trying to restore the original initial context factory builder: " + originalBuilder); + } + + try { + NamingManager.setInitialContextFactoryBuilder(originalBuilder); + } catch (Exception e2) { + LOG.error("Failed to restore the original initial context factory builder. The JNDI lookup may" + + " not function properly from this point on...", e2); + } + } + } + } + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecorator.java new file mode 100644 index 0000000..0697003 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecorator.java @@ -0,0 +1,264 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Hashtable; +import java.util.List; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; + +/** + * This is the "meat" of the RHQ's secured JNDI access. This {@link Context} decorator + * applied security checks in each method (lookups, (un)bindings, etc). + * <p> + * The security check consists of checking if the current callstack has the {@link AllowRhqServerInternalsAccessPermission}. + * <p> + * This decorator applies the security check on any JNDI name without a scheme and + * on any name that has a scheme listed in the {@link #checkedSchemes} list supplied + * in the constructor. + * + * @author Lukas Krejci + */ +public class AccessCheckingContextDecorator implements Context, ContextDecorator, Serializable { + + private static final long serialVersionUID = 1L; + + private static final AllowRhqServerInternalsAccessPermission PERM = new AllowRhqServerInternalsAccessPermission(); + private Context original; + private List<String> checkedSchemes; + + public AccessCheckingContextDecorator(String... checkedSchemes) { + this.checkedSchemes = Arrays.asList(checkedSchemes); + } + + public AccessCheckingContextDecorator(Context original, String... checkedSchemes) { + this.original = original; + this.checkedSchemes = Arrays.asList(checkedSchemes); + } + + public void init(Context ctx) { + this.original = ctx; + } + + protected Context getOriginal() { + return original; + } + + protected static void check() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) sm.checkPermission(PERM); + } + + private void checkScheme(String scheme) { + if (scheme == null || checkedSchemes.contains(scheme)) { + check(); + } + } + + protected void check(String name) { + checkScheme(getURLScheme(name)); + } + + protected void check(Name name) { + if (name.size() == 0) { + check(); + } else { + String first = name.get(0); + checkScheme(getURLScheme(first)); + } + } + + public Object lookup(Name name) throws NamingException { + check(name); + return original.lookup(name); + } + + public Object lookup(String name) throws NamingException { + check(name); + return original.lookup(name); + } + + public void bind(Name name, Object obj) throws NamingException { + check(name); + original.bind(name, obj); + } + + public void bind(String name, Object obj) throws NamingException { + check(name); + original.bind(name, obj); + } + + public void rebind(Name name, Object obj) throws NamingException { + check(name); + original.rebind(name, obj); + } + + public void rebind(String name, Object obj) throws NamingException { + check(name); + original.rebind(name, obj); + } + + public void unbind(Name name) throws NamingException { + check(name); + original.unbind(name); + } + + public void unbind(String name) throws NamingException { + check(name); + original.unbind(name); + } + + public void rename(Name oldName, Name newName) throws NamingException { + check(oldName); + check(newName); + original.rename(oldName, newName); + } + + public void rename(String oldName, String newName) throws NamingException { + check(oldName); + check(newName); + original.rename(oldName, newName); + } + + public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { + check(name); + return original.list(name); + } + + public NamingEnumeration<NameClassPair> list(String name) throws NamingException { + check(name); + return original.list(name); + } + + public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { + check(name); + return original.listBindings(name); + } + + public NamingEnumeration<Binding> listBindings(String name) throws NamingException { + check(name); + return original.listBindings(name); + } + + public void destroySubcontext(Name name) throws NamingException { + check(name); + original.destroySubcontext(name); + } + + public void destroySubcontext(String name) throws NamingException { + check(name); + original.destroySubcontext(name); + } + + public Context createSubcontext(Name name) throws NamingException { + check(name); + return original.createSubcontext(name); + } + + public Context createSubcontext(String name) throws NamingException { + check(name); + return original.createSubcontext(name); + } + + public Object lookupLink(Name name) throws NamingException { + check(name); + return original.lookupLink(name); + } + + public Object lookupLink(String name) throws NamingException { + check(name); + return original.lookupLink(name); + } + + public NameParser getNameParser(Name name) throws NamingException { + check(name); + return original.getNameParser(name); + } + + public NameParser getNameParser(String name) throws NamingException { + check(name); + return original.getNameParser(name); + } + + public Name composeName(Name name, Name prefix) throws NamingException { + check(name); + return original.composeName(name, prefix); + } + + public String composeName(String name, String prefix) throws NamingException { + check(name); + return original.composeName(name, prefix); + } + + public Object addToEnvironment(String propName, Object propVal) throws NamingException { + check(); + return original.addToEnvironment(propName, propVal); + } + + public Object removeFromEnvironment(String propName) throws NamingException { + check(); + return original.removeFromEnvironment(propName); + } + + public Hashtable<?, ?> getEnvironment() throws NamingException { + check(); + return original.getEnvironment(); + } + + public void close() throws NamingException { + check(); + original.close(); + } + + public String getNameInNamespace() throws NamingException { + check(); + return original.getNameInNamespace(); + } + + //copied from InitialContext + private static String getURLScheme(String str) { + int colon_posn = str.indexOf(':'); + int slash_posn = str.indexOf('/'); + + if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn)) + return str.substring(0, colon_posn); + return null; + } + + @Override + public int hashCode() { + return getOriginal() == null ? super.hashCode() : getOriginal().hashCode(); + } + + @Override + public boolean equals(Object o) { + return getOriginal() == null ? super.equals(o) : getOriginal().equals(o); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecoratorSetContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecoratorSetContext.java new file mode 100644 index 0000000..2e0e790 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingContextDecoratorSetContext.java @@ -0,0 +1,75 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import java.lang.reflect.Constructor; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.naming.Context; + +import org.rhq.enterprise.server.naming.util.DecoratorSetContext; + +/** + * + * + * @author Lukas Krejci + */ +public class AccessCheckingContextDecoratorSetContext implements DecoratorSetContext<Context, ContextDecorator> { + + private static final Set<Class<? extends ContextDecorator>> DECORATOR_CLASSES; + static { + HashSet<Class<? extends ContextDecorator>> tmp = new HashSet<Class<? extends ContextDecorator>>(); + tmp.add(AccessCheckingContextDecorator.class); + tmp.add(AccessCheckingDirContextDecorator.class); + tmp.add(AccessCheckingEventContextDecorator.class); + tmp.add(AccessCheckingEventDirContextDecorator.class); + tmp.add(AccessCheckingLdapContextDecorator.class); + + DECORATOR_CLASSES = Collections.unmodifiableSet(tmp); + } + + private Set<Class<? extends Context>> supportedInterfaces; + private String[] checkedSchemes; + + public AccessCheckingContextDecoratorSetContext(Set<Class<? extends Context>> supportedInterfaces, String... checkedSchemes) { + this.supportedInterfaces = supportedInterfaces; + this.checkedSchemes = checkedSchemes; + } + + public ContextDecorator instantiate(Class<? extends ContextDecorator> decoratorClass) throws Exception { + Constructor<? extends ContextDecorator> ctor = decoratorClass.getConstructor(String[].class); + + return ctor.newInstance((Object)checkedSchemes); + } + + public Set<Class<? extends Context>> getSupportedInterfaces() { + return supportedInterfaces; + } + + public Set<Class<? extends ContextDecorator>> getDecoratorClasses() { + return DECORATOR_CLASSES; + } + + public void init(ContextDecorator decorator, Context object) throws Exception { + decorator.init(object); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingDirContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingDirContextDecorator.java new file mode 100644 index 0000000..602cc02 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingDirContextDecorator.java @@ -0,0 +1,187 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Name; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; + +/** + * A decorator of {@link DirContext}. + * + * @author Lukas Krejci + */ +public class AccessCheckingDirContextDecorator extends AccessCheckingContextDecorator implements DirContext { + + private static final long serialVersionUID = 1L; + + public AccessCheckingDirContextDecorator(String... checkedSchemes) { + super(checkedSchemes); + } + + public AccessCheckingDirContextDecorator(DirContext original, String... checkedSchemes) { + super(original, checkedSchemes); + } + + @Override + protected DirContext getOriginal() { + return (DirContext) super.getOriginal(); + } + + public Attributes getAttributes(Name name) throws NamingException { + check(name); + return getOriginal().getAttributes(name); + } + + public Attributes getAttributes(String name) throws NamingException { + check(name); + return getOriginal().getAttributes(name); + } + + public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { + check(name); + return getOriginal().getAttributes(name, attrIds); + } + + public Attributes getAttributes(String name, String[] attrIds) throws NamingException { + check(name); + return getOriginal().getAttributes(name, attrIds); + } + + public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { + check(name); + getOriginal().modifyAttributes(name, mod_op, attrs); + } + + public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { + check(name); + getOriginal().modifyAttributes(name, mod_op, attrs); + } + + public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { + check(name); + getOriginal().modifyAttributes(name, mods); + } + + public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { + check(name); + getOriginal().modifyAttributes(name, mods); + } + + public void bind(Name name, Object obj, Attributes attrs) throws NamingException { + check(name); + getOriginal().bind(name, obj, attrs); + } + + public void bind(String name, Object obj, Attributes attrs) throws NamingException { + check(name); + getOriginal().bind(name, obj, attrs); + } + + public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { + check(name); + getOriginal().rebind(name, obj, attrs); + } + + public void rebind(String name, Object obj, Attributes attrs) throws NamingException { + check(name); + getOriginal().rebind(name, obj, attrs); + } + + public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { + check(name); + return getOriginal().createSubcontext(name, attrs); + } + + public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { + check(name); + return getOriginal().createSubcontext(name, attrs); + } + + public DirContext getSchema(Name name) throws NamingException { + check(name); + return getOriginal().getSchema(name); + } + + public DirContext getSchema(String name) throws NamingException { + check(name); + return getOriginal().getSchema(name); + } + + public DirContext getSchemaClassDefinition(Name name) throws NamingException { + check(name); + return getOriginal().getSchemaClassDefinition(name); + } + + public DirContext getSchemaClassDefinition(String name) throws NamingException { + check(name); + return getOriginal().getSchema(name); + } + + public NamingEnumeration<SearchResult> + search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + check(name); + return getOriginal().search(name, matchingAttributes, attributesToReturn); + } + + public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, + String[] attributesToReturn) throws NamingException { + check(name); + return getOriginal().search(name, matchingAttributes, attributesToReturn); + } + + public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { + check(name); + return getOriginal().search(name, matchingAttributes); + } + + public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { + check(name); + return getOriginal().search(name, matchingAttributes); + } + + public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { + check(name); + return getOriginal().search(name, filter, cons); + } + + public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) + throws NamingException { + check(name); + return getOriginal().search(name, filter, cons); + } + + public NamingEnumeration<SearchResult> + search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + check(name); + return getOriginal().search(name, filterExpr, filterArgs, cons); + } + + public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { + check(name); + return getOriginal().search(name, filterExpr, filterArgs, cons); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventContextDecorator.java new file mode 100644 index 0000000..b6f314d --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventContextDecorator.java @@ -0,0 +1,69 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.event.EventContext; +import javax.naming.event.NamingListener; + +/** + * + * + * @author Lukas Krejci + */ +public class AccessCheckingEventContextDecorator extends AccessCheckingContextDecorator implements EventContext { + + private static final long serialVersionUID = 1L; + + public AccessCheckingEventContextDecorator(String... checkedSchemes) { + super(checkedSchemes); + } + + public AccessCheckingEventContextDecorator(EventContext original, String... checkedSchemes) { + super(original, checkedSchemes); + } + + @Override + protected EventContext getOriginal() { + return (EventContext) super.getOriginal(); + } + + public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { + check(target); + getOriginal().addNamingListener(target, scope, l); + } + + public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { + check(target); + getOriginal().addNamingListener(target, scope, l); + } + + public void removeNamingListener(NamingListener l) throws NamingException { + check(); + getOriginal().removeNamingListener(l); + } + + public boolean targetMustExist() throws NamingException { + check(); + return getOriginal().targetMustExist(); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventDirContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventDirContextDecorator.java new file mode 100644 index 0000000..f28c29c --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingEventDirContextDecorator.java @@ -0,0 +1,96 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.directory.SearchControls; +import javax.naming.event.EventDirContext; +import javax.naming.event.NamingListener; + +/** + * + * + * @author Lukas Krejci + */ +public class AccessCheckingEventDirContextDecorator extends AccessCheckingDirContextDecorator implements + EventDirContext { + + private static final long serialVersionUID = 1L; + + public AccessCheckingEventDirContextDecorator(String... checkedSchemes) { + super(checkedSchemes); + } + + public AccessCheckingEventDirContextDecorator(EventDirContext original, String... checkedSchemes) { + super(original, checkedSchemes); + } + + @Override + protected EventDirContext getOriginal() { + return (EventDirContext) super.getOriginal(); + } + + public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { + check(target); + getOriginal().addNamingListener(target, scope, l); + } + + public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { + check(target); + getOriginal().addNamingListener(target, scope, l); + } + + public void removeNamingListener(NamingListener l) throws NamingException { + check(); + getOriginal().removeNamingListener(l); + } + + public boolean targetMustExist() throws NamingException { + check(); + return getOriginal().targetMustExist(); + } + + public void addNamingListener(Name target, String filter, SearchControls ctls, NamingListener l) + throws NamingException { + check(target); + getOriginal().addNamingListener(target, filter, ctls, l); + } + + public void addNamingListener(String target, String filter, SearchControls ctls, NamingListener l) + throws NamingException { + check(target); + getOriginal().addNamingListener(target, filter, ctls, l); + } + + public void + addNamingListener(Name target, String filter, Object[] filterArgs, SearchControls ctls, NamingListener l) + throws NamingException { + check(target); + getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); + } + + public void addNamingListener(String target, String filter, Object[] filterArgs, SearchControls ctls, + NamingListener l) throws NamingException { + check(target); + getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingLdapContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingLdapContextDecorator.java new file mode 100644 index 0000000..2c6036f --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/AccessCheckingLdapContextDecorator.java @@ -0,0 +1,85 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.NamingException; +import javax.naming.ldap.Control; +import javax.naming.ldap.ExtendedRequest; +import javax.naming.ldap.ExtendedResponse; +import javax.naming.ldap.LdapContext; + +/** + * + * + * @author Lukas Krejci + */ +public class AccessCheckingLdapContextDecorator extends AccessCheckingDirContextDecorator implements LdapContext { + + private static final long serialVersionUID = 1L; + + public AccessCheckingLdapContextDecorator(String... checkedSchemes) { + super(checkedSchemes); + } + + public AccessCheckingLdapContextDecorator(LdapContext original, String... checkedSchemes) { + super(original, checkedSchemes); + } + + @Override + protected LdapContext getOriginal() { + return (LdapContext) super.getOriginal(); + } + + public ExtendedResponse extendedOperation(ExtendedRequest request) throws NamingException { + check(); + return getOriginal().extendedOperation(request); + } + + public LdapContext newInstance(Control[] requestControls) throws NamingException { + check(); + return getOriginal().newInstance(requestControls); + } + + public void reconnect(Control[] connCtls) throws NamingException { + check(); + getOriginal().reconnect(connCtls); + } + + public Control[] getConnectControls() throws NamingException { + check(); + return getOriginal().getConnectControls(); + } + + public void setRequestControls(Control[] requestControls) throws NamingException { + check(); + getOriginal().setRequestControls(requestControls); + } + + public Control[] getRequestControls() throws NamingException { + check(); + return getOriginal().getRequestControls(); + } + + public Control[] getResponseControls() throws NamingException { + check(); + return getOriginal().getResponseControls(); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/ContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/ContextDecorator.java new file mode 100644 index 0000000..0781b9b --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/ContextDecorator.java @@ -0,0 +1,33 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Context; +import javax.naming.NamingException; + +/** + * + * + * @author Lukas Krejci + */ +public interface ContextDecorator extends Context { + + void init(Context context) throws NamingException; +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecorator.java new file mode 100644 index 0000000..62fc86b --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecorator.java @@ -0,0 +1,222 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import java.io.Serializable; +import java.util.Hashtable; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.rhq.enterprise.server.naming.AccessCheckingInitialContextFactoryBuilder; + +/** + * This is a wrapper class around another {@link Context} implementation that + * prefers to use an URL context for some operation if the JNDI name contains + * a scheme rather than the original. This is the behavior of {@link InitialContext} + * which we need to restore in the contexts created by the {@link AccessCheckingInitialContextFactoryBuilder} + * (which an {@link InitialContext} uses exclusively if the builder is set). + * <p> + * This is important because RHQ server has its own initial context factory + * builder that creates factories that in turn create contexts. If the default + * {@link InitialContext} implementation was used, we'd never be able to lookup + * scheme-based names because the default implementation of the {@link InitialContext} + * always uses the default context of the builder if one is installed no matter + * the scheme in the name. + * <p> + * The {@link AccessCheckingInitialContextFactoryBuilder} wraps the context returned + * by the factory in an instance of this class and thus is restoring the original + * intended behavior of the {@link InitialContext}. It looks at the name being looked + * up (bound or whatever) and prefers to use the URL context factories if the name + * contains the scheme (as does the {@link InitialContext} if no builder is installed). + * If the name doesn't contain a scheme, the provided default context factory is used to + * look up the name. + * + * @author Lukas Krejci + */ +public class URLPreferringContextDecorator implements Context, ContextDecorator, Serializable { + + private static final long serialVersionUID = 1L; + + private Context original; + + public URLPreferringContextDecorator() { + + } + + public URLPreferringContextDecorator(Context ctx) { + original = ctx; + } + + public void init(Context context) { + original = context; + } + + protected Context getOriginal() throws NamingException { + return original; + } + + protected Context getURLOrDefaultInitCtx(Name name) throws NamingException { + @SuppressWarnings("unchecked") + Context urlContext = URLPreferringContextDecoratorHelper.getURLContext(name, (Hashtable<Object, Object>) getEnvironment()); + return urlContext == null ? getOriginal() : urlContext; + } + + protected Context getURLOrDefaultInitCtx(String name) throws NamingException { + @SuppressWarnings("unchecked") + Context urlContext = URLPreferringContextDecoratorHelper.getURLContext(name, (Hashtable<Object, Object>) getEnvironment()); + return urlContext == null ? getOriginal() : urlContext; + } + + public Object lookup(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).lookup(name); + } + + public Object lookup(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).lookup(name); + } + + public void bind(Name name, Object obj) throws NamingException { + getURLOrDefaultInitCtx(name).bind(name, obj); + } + + public void bind(String name, Object obj) throws NamingException { + getURLOrDefaultInitCtx(name).bind(name, obj); + } + + public void rebind(Name name, Object obj) throws NamingException { + getURLOrDefaultInitCtx(name).rebind(name, obj); + } + + public void rebind(String name, Object obj) throws NamingException { + getURLOrDefaultInitCtx(name).rebind(name, obj); + } + + public void unbind(Name name) throws NamingException { + getURLOrDefaultInitCtx(name).unbind(name); + } + + public void unbind(String name) throws NamingException { + getURLOrDefaultInitCtx(name).unbind(name); + } + + public void rename(Name oldName, Name newName) throws NamingException { + getURLOrDefaultInitCtx(oldName).rename(oldName, newName); + } + + public void rename(String oldName, String newName) throws NamingException { + getURLOrDefaultInitCtx(oldName).rename(oldName, newName); + } + + public NamingEnumeration<NameClassPair> list(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).list(name); + } + + public NamingEnumeration<NameClassPair> list(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).list(name); + } + + public NamingEnumeration<Binding> listBindings(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).listBindings(name); + } + + public NamingEnumeration<Binding> listBindings(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).listBindings(name); + } + + public void destroySubcontext(Name name) throws NamingException { + getURLOrDefaultInitCtx(name).destroySubcontext(name); + } + + public void destroySubcontext(String name) throws NamingException { + getURLOrDefaultInitCtx(name).destroySubcontext(name); + } + + public Context createSubcontext(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).createSubcontext(name); + } + + public Context createSubcontext(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).createSubcontext(name); + } + + public Object lookupLink(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).lookupLink(name); + } + + public Object lookupLink(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).lookupLink(name); + } + + public NameParser getNameParser(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).getNameParser(name); + } + + public NameParser getNameParser(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).getNameParser(name); + } + + public Name composeName(Name name, Name prefix) throws NamingException { + return getOriginal().composeName(name, prefix); + } + + public String composeName(String name, String prefix) throws NamingException { + return getOriginal().composeName(name, prefix); + } + + public Object addToEnvironment(String propName, Object propVal) throws NamingException { + return getOriginal().addToEnvironment(propName, propVal); + } + + public Object removeFromEnvironment(String propName) throws NamingException { + return getOriginal().removeFromEnvironment(propName); + } + + public Hashtable<?, ?> getEnvironment() throws NamingException { + return getOriginal().getEnvironment(); + } + + public void close() throws NamingException { + if (getOriginal() != null) { + getOriginal().close(); + original = null; + } + } + + public String getNameInNamespace() throws NamingException { + return getOriginal().getNameInNamespace(); + } + + @Override + public int hashCode() { + return original == null ? super.hashCode() : original.hashCode(); + } + + @Override + public boolean equals(Object o) { + return original == null ? super.equals(o) : original.equals(o); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorHelper.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorHelper.java new file mode 100644 index 0000000..306446d --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorHelper.java @@ -0,0 +1,76 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.spi.NamingManager; + +/** + * + * + * @author Lukas Krejci + */ +public class URLPreferringContextDecoratorHelper { + + private URLPreferringContextDecoratorHelper() { + + } + + public static Context getURLContext(String name, Hashtable<Object, Object> env) throws NamingException { + String scheme = getURLScheme(name); + if (scheme != null) { + Context ctx = NamingManager.getURLContext(scheme, env); + if (ctx != null) { + return ctx; + } + } + + return null; + } + + public static Context getURLContext(Name name, Hashtable<Object, Object> env) throws NamingException { + if (name.size() > 0) { + String first = name.get(0); + String scheme = getURLScheme(first); + if (scheme != null) { + Context ctx = NamingManager.getURLContext(scheme, env); + if (ctx != null) { + return ctx; + } + } + } + + return null; + } + + //copied from InitialContext + private static String getURLScheme(String str) { + int colon_posn = str.indexOf(':'); + int slash_posn = str.indexOf('/'); + + if (colon_posn > 0 && (slash_posn == -1 || colon_posn < slash_posn)) + return str.substring(0, colon_posn); + return null; + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorSetContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorSetContext.java new file mode 100644 index 0000000..ded552c --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringContextDecoratorSetContext.java @@ -0,0 +1,71 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.naming.Context; + +import org.rhq.enterprise.server.naming.util.DecoratorSetContext; + +/** + * + * + * @author Lukas Krejci + */ +public class URLPreferringContextDecoratorSetContext implements DecoratorSetContext<Context, ContextDecorator> { + + private static final Set<Class<? extends ContextDecorator>> DECORATOR_CLASSES; + static { + HashSet<Class<? extends ContextDecorator>> tmp = new HashSet<Class<? extends ContextDecorator>>(); + tmp.add(URLPreferringContextDecorator.class); + tmp.add(URLPreferringDirContextDecorator.class); + tmp.add(URLPreferringEventContextDecorator.class); + tmp.add(URLPreferringEventDirContextDecorator.class); + tmp.add(URLPreferringLdapContextDecorator.class); + + DECORATOR_CLASSES = Collections.unmodifiableSet(tmp); + } + + private Set<Class<? extends Context>> supportedInterfaces; + + public URLPreferringContextDecoratorSetContext(Set<Class<? extends Context>> supportedInterfaces) { + this.supportedInterfaces = supportedInterfaces; + } + + public Set<Class<? extends Context>> getSupportedInterfaces() { + return supportedInterfaces; + } + + public Set<Class<? extends ContextDecorator>> getDecoratorClasses() { + return DECORATOR_CLASSES; + } + + public ContextDecorator instantiate(Class<? extends ContextDecorator> decoratorClass) throws Exception { + return decoratorClass.newInstance(); + } + + public void init(ContextDecorator decorator, Context object) throws Exception { + decorator.init(object); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringDirContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringDirContextDecorator.java new file mode 100644 index 0000000..6c695f4 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringDirContextDecorator.java @@ -0,0 +1,185 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.NoInitialContextException; +import javax.naming.NotContextException; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; + +/** + * Akin to {@link URLPreferringContextDecorator} this class implements the similar logic + * for {@link DirContext}s. + * + * @author Lukas Krejci + */ +public class URLPreferringDirContextDecorator extends URLPreferringContextDecorator implements DirContext { + + private static final long serialVersionUID = 1L; + + public URLPreferringDirContextDecorator() { + super(null); + } + + public URLPreferringDirContextDecorator(DirContext ctx) { + super(ctx); + } + + protected DirContext checkAndCast(Context ctx) throws NamingException { + if (!(ctx instanceof DirContext)) { + if (ctx == null) { + throw new NoInitialContextException(); + } else { + throw new NotContextException( + "Not an instance of DirContext"); + } + } + + return (DirContext) ctx; + } + + @Override + protected DirContext getURLOrDefaultInitCtx(Name name) throws NamingException { + Context ctx = super.getURLOrDefaultInitCtx(name); + return checkAndCast(ctx); + } + + @Override + protected DirContext getURLOrDefaultInitCtx(String name) throws NamingException { + Context ctx = super.getURLOrDefaultInitCtx(name); + return checkAndCast(ctx); + } + + public Attributes getAttributes(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).getAttributes(name); + } + + public Attributes getAttributes(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).getAttributes(name); + } + + public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { + return getURLOrDefaultInitCtx(name).getAttributes(name, attrIds); + } + + public Attributes getAttributes(String name, String[] attrIds) throws NamingException { + return getURLOrDefaultInitCtx(name).getAttributes(name, attrIds); + } + + public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).modifyAttributes(name, mod_op, attrs); + } + + public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).modifyAttributes(name, mod_op, attrs); + } + + public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { + getURLOrDefaultInitCtx(name).modifyAttributes(name, mods); + } + + public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { + getURLOrDefaultInitCtx(name).modifyAttributes(name, mods); + } + + public void bind(Name name, Object obj, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).bind(name, obj, attrs); + } + + public void bind(String name, Object obj, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).bind(name, obj, attrs); + } + + public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).rebind(name, obj, attrs); + } + + public void rebind(String name, Object obj, Attributes attrs) throws NamingException { + getURLOrDefaultInitCtx(name).rebind(name, obj, attrs); + } + + public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { + return getURLOrDefaultInitCtx(name).createSubcontext(name, attrs); + } + + public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { + return getURLOrDefaultInitCtx(name).createSubcontext(name, attrs); + } + + public DirContext getSchema(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).getSchema(name); + } + + public DirContext getSchema(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).getSchema(name); + } + + public DirContext getSchemaClassDefinition(Name name) throws NamingException { + return getURLOrDefaultInitCtx(name).getSchemaClassDefinition(name); + } + + public DirContext getSchemaClassDefinition(String name) throws NamingException { + return getURLOrDefaultInitCtx(name).getSchemaClassDefinition(name); + } + + public NamingEnumeration<SearchResult> + search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, matchingAttributes, attributesToReturn); + } + + public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, + String[] attributesToReturn) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, matchingAttributes, attributesToReturn); + } + + public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, matchingAttributes); + } + + public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, matchingAttributes); + } + + public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, filter, cons); + } + + public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) + throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, filter, cons); + } + + public NamingEnumeration<SearchResult> + search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, filterExpr, filterArgs, cons); + } + + public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { + return getURLOrDefaultInitCtx(name).search(name, filterExpr, filterArgs, cons); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventContextDecorator.java new file mode 100644 index 0000000..30e9ed2 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventContextDecorator.java @@ -0,0 +1,81 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.NoInitialContextException; +import javax.naming.NotContextException; +import javax.naming.event.EventContext; +import javax.naming.event.NamingListener; + +/** + * + * + * @author Lukas Krejci + */ +public class URLPreferringEventContextDecorator extends URLPreferringContextDecorator implements EventContext { + + private static final long serialVersionUID = 1L; + + public URLPreferringEventContextDecorator() { + super(null); + } + + public URLPreferringEventContextDecorator(EventContext ctx) { + super(ctx); + } + + protected EventContext checkAndCast(Context ctx) throws NamingException { + if (!(ctx instanceof EventContext)) { + if (ctx == null) { + throw new NoInitialContextException(); + } else { + throw new NotContextException( + "Not an instance of EventContext"); + } + } + + return (EventContext) ctx; + } + + @Override + protected EventContext getOriginal() throws NamingException { + return checkAndCast(super.getOriginal()); + } + + public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { + getOriginal().addNamingListener(target, scope, l); + } + + public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { + getOriginal().addNamingListener(target, scope, l); + } + + public void removeNamingListener(NamingListener l) throws NamingException { + getOriginal().removeNamingListener(l); + } + + public boolean targetMustExist() throws NamingException { + return getOriginal().targetMustExist(); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventDirContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventDirContextDecorator.java new file mode 100644 index 0000000..e9a3614 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringEventDirContextDecorator.java @@ -0,0 +1,104 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.NoInitialContextException; +import javax.naming.NotContextException; +import javax.naming.directory.SearchControls; +import javax.naming.event.EventDirContext; +import javax.naming.event.NamingListener; + +/** + * + * + * @author Lukas Krejci + */ +public class URLPreferringEventDirContextDecorator extends URLPreferringDirContextDecorator implements EventDirContext { + + private static final long serialVersionUID = 1L; + + public URLPreferringEventDirContextDecorator() { + super(null); + } + + public URLPreferringEventDirContextDecorator(EventDirContext ctx) { + super(ctx); + } + + @Override + protected EventDirContext checkAndCast(Context ctx) throws NamingException { + if (!(ctx instanceof EventDirContext)) { + if (ctx == null) { + throw new NoInitialContextException(); + } else { + throw new NotContextException( + "Not an instance of EventDirContext"); + } + } + + return (EventDirContext) ctx; + } + + @Override + protected EventDirContext getOriginal() throws NamingException { + return checkAndCast(super.getOriginal()); + } + + public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { + getOriginal().addNamingListener(target, scope, l); + } + + public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { + getOriginal().addNamingListener(target, scope, l); + } + + public void removeNamingListener(NamingListener l) throws NamingException { + getOriginal().removeNamingListener(l); + } + + public boolean targetMustExist() throws NamingException { + return getOriginal().targetMustExist(); + } + + public void addNamingListener(Name target, String filter, SearchControls ctls, NamingListener l) + throws NamingException { + getOriginal().addNamingListener(target, filter, ctls, l); + } + + public void addNamingListener(String target, String filter, SearchControls ctls, NamingListener l) + throws NamingException { + getOriginal().addNamingListener(target, filter, ctls, l); + } + + public void + addNamingListener(Name target, String filter, Object[] filterArgs, SearchControls ctls, NamingListener l) + throws NamingException { + getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); + } + + public void addNamingListener(String target, String filter, Object[] filterArgs, SearchControls ctls, + NamingListener l) throws NamingException { + getOriginal().addNamingListener(target, filter, filterArgs, ctls, l); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringLdapContextDecorator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringLdapContextDecorator.java new file mode 100644 index 0000000..93965df --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/context/URLPreferringLdapContextDecorator.java @@ -0,0 +1,94 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.context; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.NoInitialContextException; +import javax.naming.NotContextException; +import javax.naming.ldap.Control; +import javax.naming.ldap.ExtendedRequest; +import javax.naming.ldap.ExtendedResponse; +import javax.naming.ldap.LdapContext; + +/** + * + * + * @author Lukas Krejci + */ +public class URLPreferringLdapContextDecorator extends URLPreferringDirContextDecorator implements LdapContext { + + private static final long serialVersionUID = 1L; + + public URLPreferringLdapContextDecorator() { + super(null); + } + + public URLPreferringLdapContextDecorator(LdapContext original) { + super(original); + } + + @Override + protected LdapContext checkAndCast(Context ctx) throws NamingException { + if (!(ctx instanceof LdapContext)) { + if (ctx == null) { + throw new NoInitialContextException(); + } else { + throw new NotContextException("Not an instance of LdapContext"); + } + } + + return (LdapContext) ctx; + } + + @Override + protected LdapContext getOriginal() throws NamingException { + return checkAndCast(super.getOriginal()); + } + + public ExtendedResponse extendedOperation(ExtendedRequest request) throws NamingException { + return getOriginal().extendedOperation(request); + } + + public LdapContext newInstance(Control[] requestControls) throws NamingException { + return new URLPreferringLdapContextDecorator(getOriginal().newInstance(requestControls)); + } + + public void reconnect(Control[] connCtls) throws NamingException { + getOriginal().reconnect(connCtls); + } + + public Control[] getConnectControls() throws NamingException { + return getOriginal().getConnectControls(); + } + + public void setRequestControls(Control[] requestControls) throws NamingException { + getOriginal().setRequestControls(requestControls); + } + + public Control[] getRequestControls() throws NamingException { + return getOriginal().getRequestControls(); + } + + public Control[] getResponseControls() throws NamingException { + return getOriginal().getResponseControls(); + } + +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java new file mode 100644 index 0000000..fc4d02b --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/interfaces/java/javaURLContextFactory.java @@ -0,0 +1,32 @@ +package org.rhq.enterprise.server.naming.interfaces.java; + +import java.util.Hashtable; + +import javax.naming.CompositeName; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.spi.ObjectFactory; + +import org.jboss.as.naming.NamingContext; + +import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; + +/** @deprecated this is not used after all */ +@Deprecated +public class javaURLContextFactory implements ObjectFactory { + + private static final AllowRhqServerInternalsAccessPermission PERM = new AllowRhqServerInternalsAccessPermission(); + + @Override + @SuppressWarnings("unchecked") + public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) + throws Exception { + + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(PERM); + } + + return new NamingContext(name != null ? name : new CompositeName(""), (Hashtable<String, Object>) environment); + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratingInvocationHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratingInvocationHandler.java new file mode 100644 index 0000000..cda3a98 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratingInvocationHandler.java @@ -0,0 +1,55 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.util; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +public class DecoratingInvocationHandler<Type, Decorator extends Type> implements InvocationHandler { + + private final List<DecoratorPicker<Type, Decorator>> pickers; + private Type object; + + public DecoratingInvocationHandler(List<DecoratorPicker<Type, Decorator>> pickers, Type object) { + this.pickers = pickers; + this.object = object; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Type target = object; + Class<?> methodClass = method.getDeclaringClass(); + + for(DecoratorPicker<Type, Decorator> picker : pickers) { + target = picker.decorate(target, methodClass); + } + + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + if (e.getCause() != null) { + throw e.getCause(); + } else { + throw e; + } + } + } +} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorPicker.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorPicker.java new file mode 100644 index 0000000..12add1c --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorPicker.java @@ -0,0 +1,195 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.util; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +/** + * Given as set of decorators extending given type, this class can pick + * the most appropriate set of decorators for a class or a method call. + * <p> + * To configure the decorator, one has to provide a {@link DecoratorSetContext} that + * is then used to obtain the list of + * {@link DecoratorSetContext#getSupportedInterfaces() supported interfaces}, which are + * all the interfaces that should be used for decorator resolution (i.e. all other interfaces + * that a class might implement are ignored during decorator resolution), the list of + * {@link DecoratorSetContext#getDecoratorClasses() decorator classes}, which is a list + * of decorators the picker can choose from and is also used to instantiate and initialize + * the decorators. + * + * @author Lukas Krejci + */ +public class DecoratorPicker<Type, Decorator extends Type> { + + private DecoratorSetContext<Type, Decorator> context; + + public DecoratorSetContext<Type, Decorator> getContext() { + return context; + } + + public void setContext(DecoratorSetContext<Type, Decorator> decoratorSetContext) { + this.context = decoratorSetContext; + } + + /** + * Returns a set of decorators applicable for given method. The set is established based + * on the declaring class of the method. + * + * @param method the method to inspect + * @return the set of decorators that can be used to wrap a method call + * @throws Exception + */ + public Set<Decorator> getDecoratorsForMethod(Method method) throws Exception { + return getDecoratorsForClass_Private(method.getDeclaringClass()); + } + + /** + * Returns a set of decorators that can be used on instances of given class. + * @param cls the class to inspect + * @return + * @throws Exception + */ + public Set<Decorator> getDecoratorsForClass(Class<? extends Type> cls) throws Exception { + return getDecoratorsForClass_Private(cls); + } + + /** + * This method first establishes the set of decorators to use based on the class of the supplied + * object and then chains the decorators (in arbitrary order) with the supplied object at the + * "root" of the chain. + * <p> + * If a method is then called on the returned object, the methods of all the decorators are called + * in chain (each supposedly calling the next) and finally, at the end of the chain, the method on + * the original object (the one supplied to this method) is called. + * <p> + * Note that the above is only an intended behavior and actually depends on the implementation of + * the decorators that are resposinble for the chaining. Each decorator is initialized + * (@{link {@link DecoratorSetContext#init(Object, Object)} which should set it up for such chaining. + * + * @param object + * @return + * @throws Exception + */ + public Type decorate(Type object) throws Exception { + Set<Decorator> decs = getDecoratorsForClass_Private(object.getClass()); + Type ret = object; + for(Decorator d : decs) { + context.init(d, ret); + ret = d; + } + + return ret; + } + + /** + * Similar to {@link #decorate(Object)} but instead of the class of the object itself, + * uses the significantSuperClass as the basis for the decorator resolution. + * <p> + * This is important, because if the object implements two mutually incompatible sub-interfaces of <code>Type</code>, + * the chained decorators might fail to execute a method later on if the decorator depends on the upper part + * of the chain to implement certain sub-interface of <code>Type</code>. + * + * @param object the object to wrap in decorators + * @param significantSuperClass the class to base the decorator resolution on + * @return + * @throws Exception + */ + public Type decorate(Type object, Class<?> significantSuperClass) throws Exception { + Set<Decorator> decs = getDecoratorsForClass_Private(significantSuperClass); + Type ret = object; + for(Decorator d : decs) { + context.init(d, ret); + ret = d; + } + + return ret; + } + + private Set<Decorator> getDecoratorsForClass_Private(Class<?> cls) throws Exception { + Set<Class<? extends Type>> ifaces = getNearestApplicableInterfaces(cls); + + HashSet<Decorator> ret = new HashSet<Decorator>(); + + for (Class<? extends Type> iface : ifaces) { + for (Class<? extends Decorator> decClass : getMatch(iface)) { + ret.add(context.instantiate(decClass)); + } + } + + return ret; + } + + private Set<Class<? extends Type>> getNearestApplicableInterfaces(Class<?> cls) { + List<Class<? extends Type>> ifaces = new ArrayList<Class<? extends Type>>(getAllApplicableInterfaces(cls)); + + //now compact the set to only contain the most concrete interfaces + + Iterator<Class<? extends Type>> it = ifaces.iterator(); + while (it.hasNext()) { + Class<? extends Type> c = it.next(); + + for (int i = 0; i < ifaces.size(); ++i) { + Class<? extends Type> nextC = ifaces.get(i); + if (!c.equals(nextC) && c.isAssignableFrom(nextC)) { + it.remove(); + break; + } + } + } + + return new HashSet<Class<? extends Type>>(ifaces); + } + + private Set<Class<? extends Type>> getAllApplicableInterfaces(Class<?> cls) { + Set<Class<? extends Type>> ifaces = new HashSet<Class<? extends Type>>(); + + for (Class<? extends Type> iface : context.getSupportedInterfaces()) { + if (iface.isAssignableFrom(cls)) { + ifaces.add(iface); + } + } + + if (ifaces.isEmpty()) { + throw new IllegalArgumentException("Class " + cls + + " doesn't implement any of the applicable interfaces. Cannot find decorators for it."); + } + + return ifaces; + } + + private Set<Class<? extends Decorator>> getMatch(Class<?> targetIface) { + + Set<Class<? extends Decorator>> ret = new HashSet<Class<? extends Decorator>>(); + + for (Class<? extends Decorator> cls : context.getDecoratorClasses()) { + if (Arrays.asList(cls.getInterfaces()).contains(targetIface)) { + ret.add(cls); + } + } + + return ret; + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorSetContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorSetContext.java new file mode 100644 index 0000000..4916a2d --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/naming/util/DecoratorSetContext.java @@ -0,0 +1,59 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming.util; + +import java.util.Set; + +/** + * Implementations of this interface provide a context to the {@link DecoratorPicker}. + * + * @author Lukas Krejci + */ +public interface DecoratorSetContext<Type, Decorator> { + + /** + * @return the set of interfaces that the decorators are able support. + * Usually this should be just a union of all interfaces the decorators implement + * but can be trimmed down. + */ + Set<Class<? extends Type>> getSupportedInterfaces(); + + /** + * @return the set of all decorator classes in this set + */ + Set<Class<? extends Decorator>> getDecoratorClasses(); + + /** + * Instantiates a new decorator of given class. + * @param decoratorClass + * @return + * @throws Exception + */ + Decorator instantiate(Class<? extends Decorator> decoratorClass) throws Exception; + + /** + * Initializes the decorator to decorate given object. + * + * @param decorator + * @param object + * @throws Exception on error + */ + void init(Decorator decorator, Type object) throws Exception; +} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java new file mode 100644 index 0000000..c92cc42 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratingInvocationHandlerTest.java @@ -0,0 +1,144 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Properties; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.event.EventContext; +import javax.naming.event.NamingListener; +import javax.naming.spi.InitialContextFactory; +import javax.naming.spi.NamingManager; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * + * + * @author Lukas Krejci + */ +@Test +public class DecoratingInvocationHandlerTest { + private static final Set<String> INVOKED_METHODS = new HashSet<String>(); + + private static final InvocationHandler NOTE_TAKING_HANDLER = new InvocationHandler() { + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + INVOKED_METHODS.add(method.getName()); + + if ("hashCode".equals(method.getName())) { + return 0; + } else if ("equals".equals(method.getName())) { + return false; + } + + return null; + } + }; + + private static Class<?>[] CONTEXT_INTERFACES; + + public static class Factory implements InitialContextFactory { + public Context getInitialContext(Hashtable<?, ?> environment) + throws NamingException { + + return (Context) Proxy.newProxyInstance(DecoratingInvocationHandlerTest.class.getClassLoader(), CONTEXT_INTERFACES, NOTE_TAKING_HANDLER); + } + } + + private static class DummyInitialEventContext extends InitialContext implements EventContext { + + /** + * @param environment + * @throws NamingException + */ + public DummyInitialEventContext(Hashtable<?, ?> environment) throws NamingException { + super(environment); + } + + public void addNamingListener(Name target, int scope, NamingListener l) throws NamingException { + ((EventContext)getURLOrDefaultInitCtx(target)).addNamingListener(target, scope, l); + } + + public void addNamingListener(String target, int scope, NamingListener l) throws NamingException { + ((EventContext)getURLOrDefaultInitCtx(target)).addNamingListener(target, scope, l); + } + + public void removeNamingListener(NamingListener l) throws NamingException { + ((EventContext)getDefaultInitCtx()).removeNamingListener(l); + } + + public boolean targetMustExist() throws NamingException { + return ((EventContext)getDefaultInitCtx()).targetMustExist(); + } + + + } + + @BeforeClass + public void setBuilder() throws Exception { + NamingManager.setInitialContextFactoryBuilder(new AccessCheckingInitialContextFactoryBuilder( + new org.jboss.as.naming.InitialContextFactory())); + } + + public void testSimpleDispatch() throws Exception { + INVOKED_METHODS.clear(); + Properties env = new Properties(); + env.put(Context.INITIAL_CONTEXT_FACTORY, Factory.class.getName()); + + CONTEXT_INTERFACES = new Class<?>[] { Context.class }; + + InitialContext ctx = new InitialContext(env); + + ctx.lookup("asdf"); + + assert INVOKED_METHODS.contains("lookup") : "The lookup doesn't seem to have propagated to the actual context to be used."; + } + + public void testMultiInterfaceDispatch() throws Exception { + INVOKED_METHODS.clear(); + Properties env = new Properties(); + env.put(Context.INITIAL_CONTEXT_FACTORY, Factory.class.getName()); + + CONTEXT_INTERFACES = new Class<?>[] { EventContext.class, DirContext.class }; + + InitialContext ctx = new InitialContext(env); + + ctx.lookup("asdf"); + + DummyInitialEventContext ectx = new DummyInitialEventContext(env); + + ectx.addNamingListener("hodiny", 0, null); + + assert INVOKED_METHODS.contains("lookup") : "The lookup doesn't seem to have propagated to the actual context to be used."; + assert INVOKED_METHODS.contains("addNamingListener") : "The addNamingListener doesn't seem to have propagated to the actual context to be used."; + } +} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratorPickerTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratorPickerTest.java new file mode 100644 index 0000000..6a0892f --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/naming/DecoratorPickerTest.java @@ -0,0 +1,180 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2012 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.naming; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.directory.DirContext; +import javax.naming.event.EventContext; +import javax.naming.ldap.LdapContext; + +import org.testng.annotations.Test; + +import org.rhq.enterprise.server.naming.util.DecoratorPicker; +import org.rhq.enterprise.server.naming.util.DecoratorSetContext; + +/** + * @author Lukas Krejci + */ +@Test +public class DecoratorPickerTest { + + private static final InvocationHandler DUMMY_HANDLER = new InvocationHandler() { + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if ("hashCode".equals(method.getName())) { + return 0; + } else if ("equals".equals(method.getName())) { + return false; + } + + return null; + } + }; + + private static final Class<?> TEST_OBJECT_CLASS1 = createProxyClass(Context.class); + private static final Class<?> TEST_OBJECT_CLASS2 = createProxyClass(DirContext.class); + private static final Class<?> TEST_OBJECT_CLASS3 = createProxyClass(LdapContext.class); + private static final Class<?> TEST_OBJECT_CLASS4 = createProxyClass(LdapContext.class, EventContext.class); + private static final Class<?> DECORATOR_CLASS1 = createProxyClass(Context.class); + private static final Class<?> DECORATOR_CLASS2 = createProxyClass(EventContext.class); + private static final Class<?> DECORATOR_CLASS3 = createProxyClass(LdapContext.class); + private static final Class<?> DECORATOR_CLASS4 = createProxyClass(DirContext.class); + + public void testSimpleDecoratorIdentifiedByClass() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS1); + assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for Context class"); + assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], Context.class); + } + + public void testSuperClassDecoratorHasPrecedenceOverSubClassDecorator() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + //this tests that the LdapContext isn't returned even though it subclasses the DirContext + Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS2); + assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for DirContext class"); + assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], DirContext.class); + } + + public void testSubClassDecoratorCorrectlyIdentified() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + Set<Object> contextDecorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS3); + assertEquals(contextDecorators.size(), 1, "Expected exactly one decorator for LdapContext class"); + assertEquals(contextDecorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); + } + + public void testMultipleDecoratorsDetectable() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + Set<Object> decorators = picker.getDecoratorsForClass(TEST_OBJECT_CLASS4); + assertEquals(decorators.size(), 2, + "Exactly 2 decorators should have been found for a class implementing 2 interfaces."); + + boolean ldapContextDecoratorFound = false; + boolean eventContextDecoratorFound = false; + + for (Object d : decorators) { + if (LdapContext.class.isAssignableFrom(d.getClass())) { + ldapContextDecoratorFound = true; + continue; //just to make sure that somehow the decorator doesn't implement both + } + if (EventContext.class.isAssignableFrom(d.getClass())) { + eventContextDecoratorFound = true; + } + } + + assertTrue(ldapContextDecoratorFound && eventContextDecoratorFound, + "The found decorators don't implement the desired interfaces."); + } + + public void testDecoratorsIdentifiedByMethod() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + Set<Object> decorators = + picker.getDecoratorsForMethod(LdapContext.class.getMethod("getConnectControls", (Class<?>[]) null)); + assertEquals(decorators.size(), 1, + "Expected exactly one decorator for method 'getConnectControls()' from LdapContext class"); + assertEquals(decorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); + } + + public void testMethodFromSubclassMatchesSubclassDecorator() throws Exception { + DecoratorPicker<Object, Object> picker = createTestPicker(); + + //this is a method from the DirContext but we're asking for it from a class + //that implements also an LdapContext + //The LdapContext decorator also inherits from the DirContext decorator + //(by the virtue of LdapContext interface inheriting from the DirContext) + //The picker should therefore match the LdapContext decorator because its + //the "closest" one to the actual class. + Set<Object> decorators = + picker.getDecoratorsForMethod(TEST_OBJECT_CLASS3.getMethod("getSchemaClassDefinition", + new Class<?>[] { String.class })); + assertEquals(decorators.size(), 1, + "Expected exactly one decorator for method 'getSchemaClassDefinition(String)' from LdapContext class"); + assertEquals(decorators.iterator().next().getClass().getInterfaces()[0], LdapContext.class); + } + + private static Class<?> createProxyClass(Class<?>... ifaces) { + return Proxy.getProxyClass(DecoratorPickerTest.class.getClassLoader(), ifaces); + } + + private static DecoratorPicker<Object, Object> createTestPicker() { + DecoratorPicker<Object, Object> picker = new DecoratorPicker<Object, Object>(); + + DecoratorSetContext<Object, Object> decSet = new DecoratorSetContext<Object, Object>() { + + public Object instantiate(Class<? extends Object> decoratorClass) throws Exception { + Constructor<? extends Object> ctor = decoratorClass.getConstructor(InvocationHandler.class); + return ctor.newInstance(DUMMY_HANDLER); + } + + public void init(Object decorator, Object object) throws Exception { + } + + @SuppressWarnings("unchecked") + public Set<Class<? extends Object>> getSupportedInterfaces() { + return new HashSet<Class<? extends Object>>(Arrays.asList(Context.class, EventContext.class, + LdapContext.class, DirContext.class)); + } + + @SuppressWarnings("unchecked") + public Set<Class<? extends Object>> getDecoratorClasses() { + return new HashSet<Class<? extends Object>>(Arrays.asList(DECORATOR_CLASS1, DECORATOR_CLASS2, DECORATOR_CLASS3, DECORATOR_CLASS4)); + } + }; + + picker.setContext(decSet); + + return picker; + } +} diff --git a/modules/enterprise/server/pom.xml b/modules/enterprise/server/pom.xml index db001bd..614647b 100644 --- a/modules/enterprise/server/pom.xml +++ b/modules/enterprise/server/pom.xml @@ -25,7 +25,6 @@ </activation> <modules> <module>xml-schemas</module> - <module>container-lib</module> <module>jar</module> <module>sars</module> <module>plugins</module> @@ -46,7 +45,6 @@ </activation> <modules> <module>xml-schemas</module> - <module>container-lib</module> <module>jar</module> <module>safe-invoker</module> </modules> diff --git a/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java b/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java index 05c59b6..46d211c 100644 --- a/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java +++ b/modules/integration-tests/jndi-access/jndi-access-test/src/test/java/org/rhq/jndi/test/JndiAccessTest.java @@ -45,9 +45,9 @@ import org.rhq.bindings.StandardScriptPermissions; import org.rhq.bindings.util.PackageFinder; import org.rhq.core.domain.auth.Subject; import org.rhq.enterprise.client.LocalClient; +import org.rhq.enterprise.server.AllowRhqServerInternalsAccessPermission; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil; -import org.rhq.jndi.AllowRhqServerInternalsAccessPermission; import org.rhq.test.PortScout;
/** diff --git a/modules/pom.xml b/modules/pom.xml index e40d89a..d1745b2 100644 --- a/modules/pom.xml +++ b/modules/pom.xml @@ -163,7 +163,6 @@ <module>enterprise/comm</module>
<!-- These are needed for the JNDI intergration tests --> - <module>enterprise/server/container-lib</module> <module>enterprise/server/xml-schemas</module> <module>enterprise/server/safe-invoker</module> <module>enterprise/server/jar</module>
commit 4a0fb0b560f1ab18a3860baff457c3369b694568 Author: Stefan Negrea snegrea@redhat.com Date: Fri Dec 7 10:19:02 2012 -0600
Add back Cassandra plugin specific .classpath updates.
diff --git a/.classpath b/.classpath index 996b0fc..33fd1d0 100644 --- a/.classpath +++ b/.classpath @@ -179,6 +179,8 @@ <classpathentry kind="src" path="etc/samples/custom-serverplugin/src/main/java"/> <classpathentry kind="src" path="etc/samples/simplereport-serverplugin/src/main/java"/> <classpathentry kind="src" path="etc/agentspawn/src/main/java"/> + <classpathentry kind="src" path="modules/plugins/cassandra/src/main/java"/> + <classpathentry kind="src" path="modules/plugins/cassandra/src/test/java"/> <classpathentry excluding="**" kind="src" path="modules/enterprise/comm/src/test/resources"/> <classpathentry excluding="**" kind="src" path="modules/enterprise/agent/src/main/resources"/> <classpathentry excluding="**" kind="src" path="modules/enterprise/agent/src/test/resources"/> @@ -334,5 +336,7 @@ <classpathentry exported="true" kind="var" path="M2_REPO/com/wordnik/swagger-annotations_2.9.1/1.1.1-SNAPSHOT/swagger-annotations_2.9.1-1.1.1-20121031.024335-6.jar"/> <classpathentry exported="true" kind="var" path="JDK_HOME/lib/tools.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/joda-time/joda-time/2.1/joda-time-2.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/cassandra/cassandra-thrift/1.1.5/cassandra-thrift-1.1.5.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hectorclient/hector-core/1.1-1/hector-core-1.1-1.jar"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath>
commit e73273e9c1ef2b902ccc4e967d6ae96343088405 Merge: 6239ffc 471c4af Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 09:30:09 2012 -0500
Merge remote-tracking branch 'origin/master' into rhq-on-as7
Conflicts: .classpath modules/enterprise/server/ear/pom.xml
commit 471c4af38dd02a614acd06881e2b40e7a4b3829a Author: John Mazzitelli mazz@redhat.com Date: Fri Dec 7 09:23:32 2012 -0500
revert to the last known copy that is correct - stefan, put back your cassandra stuff in here
diff --git a/.classpath b/.classpath index 029ef7c..996b0fc 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,15 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="modules/common/ant-bundle/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/server/jar/src/test/java"/> + <classpathentry kind="src" path="modules/enterprise/server/itests-2/src/test/java"/> + <classpathentry kind="src" path="modules/enterprise/scripting/javascript/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/scripting/python/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/scripting/python/src/test/java"/> + <classpathentry kind="src" path="modules/enterprise/scripting/javascript/src/test/java"/> + <classpathentry kind="src" path="modules/enterprise/gui/installer/src/test/java"/> + <classpathentry kind="src" path="modules/common/jboss-as-dmr-client/src/test/java"/> + <classpathentry kind="src" path="modules/common/jboss-as-dmr-client/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/scripting/api/src/main/java"/> <classpathentry kind="src" path="modules/cli-tests/src/main/java"/> <classpathentry kind="src" path="modules/helpers/jeeGen/src/main/java"/> @@ -40,8 +49,6 @@ <classpathentry kind="src" path="modules/enterprise/server/xml-schemas/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/xml-schemas/target/generated-sources/xjc"/> <classpathentry kind="src" path="modules/enterprise/server/jar/src/main/java"/> - <classpathentry kind="src" path="modules/enterprise/server/jar/src/test/java"/> - <classpathentry kind="src" path="modules/enterprise/server/jar/src/main/filtered-sources/java"/> <classpathentry kind="src" path="modules/enterprise/server/jar/target/generated-sources/antlr3"/> <classpathentry kind="src" path="modules/enterprise/binding/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/binding/src/test/java"/> @@ -49,8 +56,8 @@ <classpathentry kind="src" path="modules/enterprise/gui/coregui/target/generated-sources/gwt"/> <classpathentry kind="src" path="modules/enterprise/gui/portal-war/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/gui/portal-war/src/test/java"/> - <classpathentry kind="src" path="modules/enterprise/gui/installer-war/src/main/java"/> - <classpathentry kind="src" path="modules/enterprise/gui/base-perspective-jar/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/gui/installer/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/gui/installer/target/generated-sources/gwt"/> <classpathentry kind="src" path="modules/enterprise/gui/content_http-war/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/client-api/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/remoting/client-api/src/main/java"/> @@ -59,6 +66,8 @@ <classpathentry kind="src" path="modules/enterprise/server/sars/agent-sar/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/safe-invoker/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/safe-invoker/src/test/java"/> + <classpathentry kind="src" path="modules/enterprise/server/startup-subsystem/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/server/startup-subsystem/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/container-lib/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/ant-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/filetemplate-bundle/src/main/java"/> @@ -164,7 +173,6 @@ <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/test/java"/> <classpathentry kind="src" path="modules/core/arquillian-integration/archive/src/main/java"/> <classpathentry kind="src" path="modules/core/arquillian-integration/container/src/main/java"/> - <classpathentry kind="src" path="modules/enterprise/server/itests/src/test/java"/> <classpathentry kind="src" path="modules/test-utils/src/main/java"/> <classpathentry kind="src" path="modules/integration-tests/mod_cluster-plugin-test/src/test/java"/> <classpathentry kind="src" path="etc/samples/skeleton-plugin/src/main/java"/> @@ -174,14 +182,11 @@ <classpathentry excluding="**" kind="src" path="modules/enterprise/comm/src/test/resources"/> <classpathentry excluding="**" kind="src" path="modules/enterprise/agent/src/main/resources"/> <classpathentry excluding="**" kind="src" path="modules/enterprise/agent/src/test/resources"/> - <classpathentry kind="src" path="modules/plugins/cassandra/src/main/java"/> - <classpathentry kind="src" path="modules/plugins/cassandra/src/test/java"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/integration/jboss-profileservice-spi/5.1.0.SP1/jboss-profileservice-spi-5.1.0.SP1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/man/jboss-managed/2.1.1.GA/jboss-managed-2.1.1.GA.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/man/jboss-metatype/2.1.1.GA/jboss-metatype-2.1.1.GA.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.jar" sourcepath="/M2_REPO/commons-io/commons-io/1.3.1/commons-io-1.3.1-sources.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/sun/xml/bind/jaxb-impl/2.1.9/jaxb-impl-2.1.9.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/sun/xml/bind/jaxb-impl/2.2.4/jaxb-impl-2.2.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/i18nlog/i18nlog/1.0.10/i18nlog-1.0.10.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/gnu-getopt/getopt/1.0.13/getopt-1.0.13.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-httpclient/commons-httpclient/3.0.1/commons-httpclient-3.0.1.jar"/> @@ -205,17 +210,14 @@ <classpathentry exported="true" kind="var" path="M2_REPO/tomcat/catalina/5.5.20/catalina-5.5.20.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/taglibs/standard/1.1.2/standard-1.1.2.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/jboss/jboss-common/1.2.1.GA/jboss-common-1.2.1.GA.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/jboss-common-core/2.2.17.GA/jboss-common-core-2.2.17.GA.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/javax/servlet/jstl/1.1.2/jstl-1.1.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/struts-menu/struts-menu/2.3/struts-menu-2.3.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/junit/junit/3.8.2/junit-3.8.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/velocity/velocity/1.5/velocity-1.5.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/xalan/xalan/2.5.1/xalan-2.5.1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/javax/xml/bind/jaxb-api/2.1/jaxb-api-2.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/javax/xml/bind/jaxb-api/2.2.3/jaxb-api-2.2.3.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/javax/xml/bind/jsr173_api/1.0/jsr173_api-1.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/jboss/jboss-embeddable-ejb3/jboss-ejb3-all/1.0.0.Alpha9/jboss-ejb3-all-1.0.0.Alpha9.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/jboss/jbpm/3.1.1/jbpm-3.1.1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/jboss/jboss-embeddable-ejb3/hibernate-all/1.0.0.Alpha9/hibernate-all-1.0.0.Alpha9.jar" sourcepath="/M2_REPO/hibernate/hibernate3/3.2.r14201-2/hibernate3-3.2.r14201-2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jetbrains/annotations/7.0.2/annotations-7.0.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/ant/ant-launcher/1.8.0/ant-launcher-1.8.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/cglib/cglib-nodep/2.1_3/cglib-nodep-2.1_3.jar"/> @@ -227,31 +229,25 @@ <classpathentry exported="true" kind="var" path="M2_REPO/com/sun/facelets/jsf-facelets/1.1.15.B1/jsf-facelets-1.1.15.B1.jar" sourcepath="/M2_REPO/com/sun/facelets/jsf-facelets/1.1.15.B1/jsf-facelets-1.1.15.B1-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/mc4j/org-mc4j-ems/1.3/org-mc4j-ems-1.3.jar" sourcepath="/M2_REPO/mc4j/org-mc4j-ems/1.3/org-mc4j-ems-1.3-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/opensymphony/quartz/quartz/1.6.5/quartz-1.6.5.jar" sourcepath="/M2_REPO/org/opensymphony/quartz/quartz/1.6.5/quartz-1.6.5-sources.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/javax/mail/mail/1.4/mail-1.4.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/javax/mail/mail/1.4.4/mail-1.4.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-fileupload/commons-fileupload/1.2/commons-fileupload-1.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/richfaces/framework/richfaces-api/3.3.3.Final/richfaces-api-3.3.3.Final.jar" sourcepath="/M2_REPO/org/richfaces/framework/richfaces-api/3.1.3.GA/richfaces-api-3.1.3.GA-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/richfaces/framework/richfaces-impl/3.3.3.Final/richfaces-impl-3.3.3.Final.jar" sourcepath="/M2_REPO/org/richfaces/framework/richfaces-impl/3.3.0.GA/richfaces-impl-3.3.0.GA-sources.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/richfaces/ui/richfaces-ui/3.3.3.Final/richfaces-ui-3.3.3.Final.jar" sourcepath="/M2_REPO/org/richfaces/ui/richfaces-ui/3.3.0.GA/richfaces-ui-3.3.0.GA-sources.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/postgresql/postgresql/9.1-901.jdbc4/postgresql-9.1-901.jdbc4.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/postgresql/postgresql/9.1-902.jdbc4/postgresql-9.1-902.jdbc4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/jboss/jboss-cache/1.4.1.SP9/jboss-cache-1.4.1.SP9.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/hyperic/sigar/1.6.5.132-3/sigar-1.6.5.132-3.jar" sourcepath="/M2_REPO/org/hyperic/sigar/1.6.5.132-3/sigar-1.6.5.132-3-sources.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/transaction/jboss-jta/4.2.3.SP5/jboss-jta-4.2.3.SP5.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/transaction/jboss-jts-common/4.2.3.SP5/jboss-jts-common-4.2.3.SP5.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/jbossws-spi/1.1.1.GA/jbossws-spi-1.1.1.GA.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/jbossws/jbossws-native-core/3.1.1.GA/jbossws-native-core-3.1.1.GA.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hyperic/sigar/1.6.5.132-3/sigar-1.6.5.132-3.jar" sourcepath="/M2_REPO/org/hyperic/sigar/1.6.3.82/sigar-1.6.3.82-sources.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/jbossts/jbossjts/4.16.2.Final/jbossjts-4.16.2.Final.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/maven/maven-project/2.0.8/maven-project-2.0.8.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/apache/maven/maven-plugin-api/2.0.8/maven-plugin-api-2.0.8.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/swizzle/swizzle-confluence/1.6.1/swizzle-confluence-1.6.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jvnet/inflector/0.7.0/inflector-0.7.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/net/augeas/augeas/0.0.2/augeas-0.0.2.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/json/json/20080701/json-20080701.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/json/json/20090211/json-20090211.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/net/java/dev/jna/jna/3.2.5/jna-3.2.5.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/freemarker/freemarker/2.3.11/freemarker-2.3.11.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/seam/jboss-seam/2.1.0.SP1/jboss-seam-2.1.0.SP1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/seam/jboss-seam-ui/2.1.0.SP1/jboss-seam-ui-2.1.0.SP1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/hibernate/hibernate3/3.2.r14201-2/hibernate3-3.2.r14201-2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/jline/jline/0.9.94/jline-0.9.94.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/javassist/javassist/3.9.0.GA/javassist-3.9.0.GA.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/javassist/javassist/3.12.1.GA/javassist-3.12.1.GA.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/net/sf/opencsv/opencsv/1.8/opencsv-1.8.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-digester/commons-digester/1.8.1/commons-digester-1.8.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-codec/commons-codec/1.4/commons-codec-1.4.jar"/> @@ -264,8 +260,8 @@ <classpathentry exported="true" kind="var" path="M2_REPO/jboss/web/jbossweb/2.0.1.GA/jbossweb-2.0.1.GA.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/libvirt/libvirt/0.4.1/libvirt-0.4.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/fedorahosted/cobbler/cobbler4j/0.1/cobbler4j-0.1.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-user/2.4.0/gwt-user-2.4.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-dev/2.4.0/gwt-dev-2.4.0.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-user/2.5.0/gwt-user-2.5.0.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-dev/2.5.0/gwt-dev-2.5.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/smartgwt/smartgwt/3.0/smartgwt-3.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/googlecode/gflot/gflot/2.4.2/gflot-2.4.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar"/> @@ -282,35 +278,61 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.5/mongo-java-driver-2.6.5.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/googlecode/java-diff-utils/diffutils/1.2.1/diffutils-1.2.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/morphia/morphia/0.99/morphia-0.99.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-links/2.3.3.Final/resteasy-links-2.3.3.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-jaxrs/2.3.3.Final/resteasy-jaxrs-2.3.3.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-jackson-provider/2.3.3.Final/resteasy-jackson-provider-2.3.3.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/jaxrs-api/2.3.3.Final/jaxrs-api-2.3.3.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hibernate/hibernate-annotations/3.5.6-Final/hibernate-annotations-3.5.6-Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hibernate/hibernate-core/4.0.1.Final/hibernate-core-4.0.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hibernate/hibernate-entitymanager/4.0.1.Final/hibernate-entitymanager-4.0.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hibernate/hibernate-validator/4.2.0.Final/hibernate-validator-4.2.0.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/infinispan/infinispan-core/5.1.2.FINAL/infinispan-core-5.1.2.FINAL.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/spec/javax/servlet/jboss-servlet-api_3.0_spec/1.0.1.Final/jboss-servlet-api_3.0_spec-1.0.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/msc/jboss-msc/1.0.2.GA/jboss-msc-1.0.2.GA.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/jboss-dmr/1.1.1.Final/jboss-dmr-1.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/as/jboss-as-naming/7.1.1.Final/jboss-as-naming-7.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/as/jboss-as-server/7.1.1.Final/jboss-as-server-7.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/staxmapper/1.1.0.Final/staxmapper-1.1.0.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/modules/jboss-modules/1.1.1.GA/jboss-modules-1.1.1.GA.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/as/jboss-as-subsystem-test/7.1.1.Final/jboss-as-subsystem-test-7.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/as/jboss-as-controller/7.1.1.Final/jboss-as-controller-7.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/as/jboss-as-controller-client/7.1.1.Final/jboss-as-controller-client-7.1.1.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-links/2.3.4.Final/resteasy-links-2.3.4.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-jaxrs/2.3.4.Final/resteasy-jaxrs-2.3.4.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/resteasy-jackson-provider/2.3.4.Final/resteasy-jackson-provider-2.3.4.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/resteasy/jaxrs-api/2.3.4.Final/jaxrs-api-2.3.4.Final.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/sasl/jboss-sasl/1.0.0.Final/jboss-sasl-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="JDK_HOME/lib/tools.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/mockito/mockito-all/1.9.0/mockito-all-1.9.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-api-mockito/1.4.11/powermock-api-mockito-1.4.11.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-core/1.4.11/powermock-core-1.4.11.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-api-support/1.4.11/powermock-api-support-1.4.11.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-module-testng-common/1.4.11/powermock-module-testng-common-1.4.11.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-module-testng/1.4.11/powermock-module-testng-1.4.11.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-api-mockito/1.4.12/powermock-api-mockito-1.4.12.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-core/1.4.12/powermock-core-1.4.12.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-api-support/1.4.12/powermock-api-support-1.4.12.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-module-testng-common/1.4.12/powermock-module-testng-common-1.4.12.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/powermock/powermock-module-testng/1.4.12/powermock-module-testng-1.4.12.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/liquibase/liquibase-core/2.0.3/liquibase-core-2.0.3.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-impl-base/1.0.0/shrinkwrap-impl-base-1.0.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-api/1.0.0/shrinkwrap-api-1.0.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-spi/1.0.0/shrinkwrap-spi-1.0.0.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/descriptors/shrinkwrap-descriptors-api-base/2.0.0-alpha-2/shrinkwrap-descriptors-api-base-2.0.0-alpha-2.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/resolver/shrinkwrap-resolver-api/1.0.0-beta-6/shrinkwrap-resolver-api-1.0.0-beta-6.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/resolver/shrinkwrap-resolver-api-maven/1.0.0-beta-6/shrinkwrap-resolver-api-maven-1.0.0-beta-6.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/test/arquillian-test-spi/1.0.0.Final/arquillian-test-spi-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/test/arquillian-test-api/1.0.0.Final/arquillian-test-api-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/core/arquillian-core-spi/1.0.0.Final/arquillian-core-spi-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/core/arquillian-core-api/1.0.0.Final/arquillian-core-api-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/container/arquillian-container-spi/1.0.0.Final/arquillian-container-spi-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/container/arquillian-container-test-api/1.0.0.Final/arquillian-container-test-api-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/testng/arquillian-testng-core/1.0.0.Final/arquillian-testng-core-1.0.0.Final.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/wordnik/swagger-annotations_2.9.1/1.1-SNAPSHOT/swagger-annotations_2.9.1-1.1-20120531.064118-1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-impl-base/1.0.1/shrinkwrap-impl-base-1.0.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-api/1.0.1/shrinkwrap-api-1.0.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/shrinkwrap-spi/1.0.1/shrinkwrap-spi-1.0.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/descriptors/shrinkwrap-descriptors-api-base/2.0.0-alpha-3/shrinkwrap-descriptors-api-base-2.0.0-alpha-3.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/resolver/shrinkwrap-resolver-api/1.0.0-beta-7/shrinkwrap-resolver-api-1.0.0-beta-7.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/shrinkwrap/resolver/shrinkwrap-resolver-api-maven/1.0.0-beta-7/shrinkwrap-resolver-api-maven-1.0.0-beta-7.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/test/arquillian-test-spi/1.0.2.Final/arquillian-test-spi-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/test/arquillian-test-api/1.0.2.Final/arquillian-test-api-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/core/arquillian-core-spi/1.0.2.Final/arquillian-core-spi-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/core/arquillian-core-api/1.0.2.Final/arquillian-core-api-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/container/arquillian-container-spi/1.0.2.Final/arquillian-container-spi-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/container/arquillian-container-test-api/1.0.2.Final/arquillian-container-test-api-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/config/arquillian-config-api/1.0.2.Final/arquillian-config-api-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/container/arquillian-container-test-impl-base/1.0.2.Final/arquillian-container-test-impl-base-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/arquillian/testng/arquillian-testng-core/1.0.2.Final/arquillian-testng-core-1.0.2.Final.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/byteman/byteman/1.2.1/byteman-1.2.1.jar"/> - <classpathentry kind="var" path="M2_REPO/org/apache/cassandra/cassandra-thrift/1.1.5/cassandra-thrift-1.1.5.jar"/> - <classpathentry kind="var" path="M2_REPO/org/hectorclient/hector-core/1.1-1/hector-core-1.1-1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/ejb3/jboss-ejb3-ext-api/2.0.0/jboss-ejb3-ext-api-2.0.0.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/spec/javax/ejb/jboss-ejb-api_3.1_spec/1.0.2.Final/jboss-ejb-api_3.1_spec-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/spec/javax/jms/jboss-jms-api_1.1_spec/1.0.0.Final/jboss-jms-api_1.1_spec-1.0.0.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/spec/javax/interceptor/jboss-interceptors-api_1.1_spec/1.0.0.Final/jboss-interceptors-api_1.1_spec-1.0.0.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/spec/javax/transaction/jboss-transaction-api_1.1_spec/1.0.0.Final/jboss-transaction-api_1.1_spec-1.0.0.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/jboss/remotingjmx/remoting-jmx/1.0.2.Final/remoting-jmx-1.0.2.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/mozilla/rhino/1.7R4/rhino-1.7R4.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/picketbox/picketbox/4.0.7.Final/picketbox-4.0.7.Final.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/python/jython-standalone/2.5.2/jython-standalone-2.5.2.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/wordnik/swagger-annotations_2.9.1/1.1.1-SNAPSHOT/swagger-annotations_2.9.1-1.1.1-20121031.024335-6.jar"/> + <classpathentry exported="true" kind="var" path="JDK_HOME/lib/tools.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/joda-time/joda-time/2.1/joda-time-2.1.jar"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath>
commit 7c1d4d80cf05b33754df033f3e4ada89896f65c0 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Dec 7 10:25:34 2012 +0100
Refactor the REST API to drop the /1/ in the URI. * move to EJB 3.1 local SLSB * separate the examples into their own war file
diff --git a/modules/enterprise/gui/pom.xml b/modules/enterprise/gui/pom.xml index e6e5807..8e0c2c4 100644 --- a/modules/enterprise/gui/pom.xml +++ b/modules/enterprise/gui/pom.xml @@ -32,6 +32,7 @@ <module>content_http-war</module> <module>coregui</module> <module>rest-war</module> + <module>rest-examples-war</module> </modules> </profile>
diff --git a/modules/enterprise/gui/rest-examples-war/pom.xml b/modules/enterprise/gui/rest-examples-war/pom.xml new file mode 100644 index 0000000..e0d801f --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/pom.xml @@ -0,0 +1,133 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd%22%3E + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.rhq</groupId> + <artifactId>rhq-parent</artifactId> + <version>4.6.0-SNAPSHOT</version> + <relativePath>../../../../pom.xml</relativePath> + </parent> + + <groupId>org.rhq</groupId> + <artifactId>rhq-rest-examples</artifactId> + <packaging>war</packaging> + + <name>RHQ REST interface examples</name> + <description>RHQ Rest interface for the RHQ server (Examples)</description> + + <build> + <finalName>rhq-rest-examples</finalName> + + <plugins> + + <plugin> + <artifactId>maven-war-plugin</artifactId> + <version>2.1-alpha-1</version> + <configuration> + <archive> + <manifest> + <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> + <addDefaultImplementationEntries>true</addDefaultImplementationEntries> + </manifest> + <manifestEntries> + <Build-Number>${buildNumber}</Build-Number> + </manifestEntries> + </archive> + <webResources> + <resource> + <filtering>false</filtering> + <directory>${basedir}/src/main/webapp</directory> + </resource> + </webResources> + </configuration> + </plugin> + + </plugins> + + </build> + + + <profiles> + + <profile> + <id>dev</id> + + <properties> + <rhq.rootDir>../../../..</rhq.rootDir> + <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> + <rhq.deploymentName>${project.build.finalName}.war</rhq.deploymentName> + <rhq.deploymentDir>${rhq.containerDir}/jbossas/standalone/deployments/${rhq.earName}/${rhq.deploymentName}</rhq.deploymentDir> + </properties> + + <build> + <plugins> + + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + + <execution> + <id>deploy-classes</id> + <phase>compile</phase> + <configuration> + <target> + <property name="classes.dir" location="${rhq.deploymentDir}/WEB-INF/classes" /> + <echo>*** Copying updated files from target/classes to ${classes.dir}...</echo> + <copy todir="${classes.dir}" verbose="${rhq.verbose}"> + <fileset dir="target/classes" /> + </copy> + <property name="deployment.dir" location="${rhq.deploymentDir}" /> + <echo>*** Copying updated files from src${file.separator}main${file.separator}webapp${file.separator} to ${deployment.dir}${file.separator}...</echo> + <copy todir="${deployment.dir}" verbose="${rhq.verbose}"> + <fileset dir="${basedir}/src/main/webapp" /> + </copy> + <!-- TODO: Also copy the files from src/main/webapp-filtered/, and then filter them ourselves. --> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + <execution> + <id>deploy</id> + <phase>package</phase> + <configuration> + <target> + <property name="deployment.dir" location="${rhq.deploymentDir}" /> + <echo>*** Copying updated files from target${file.separator}${project.build.finalName}${file.separator} to ${deployment.dir}${file.separator}...</echo> + <copy todir="${deployment.dir}" verbose="${rhq.verbose}"> + <fileset dir="${basedir}/target/${project.build.finalName}" /> + </copy> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + <execution> + <id>undeploy</id> + <phase>clean</phase> + <configuration> + <target> + <property name="deployment.dir" location="${rhq.deploymentDir}" /> + <echo>*** Deleting ${deployment.dir}${file.separator}...</echo> + <delete dir="${deployment.dir}" /> + </target> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + + </executions> + </plugin> + + </plugins> + </build> + </profile> + </profiles> + +</project> diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/jboss-web.xml b/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000..319b990 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,5 @@ +<?xml version="1.0"?> + +<jboss-web> + <security-domain>RHQRESTSecurityDomain</security-domain> +</jboss-web> diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/web.xml b/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..fb75d94 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ +<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd%22%3E + + <display-name>RHQ Rest interface examples</display-name> + + <security-constraint> + <web-resource-collection> + <web-resource-name>REST</web-resource-name> + <url-pattern>/*</url-pattern> + </web-resource-collection> + <auth-constraint> + <role-name>all</role-name> + </auth-constraint> + </security-constraint> + + <login-config> + <auth-method>BASIC</auth-method> + <realm-name>RHQ REST</realm-name> + </login-config> + + <security-role> + <description>This is valid for all principals, as we do internal checks</description> + <role-name>all</role-name> + </security-role> + +</web-app> diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/bars_simple.html b/modules/enterprise/gui/rest-examples-war/src/main/webapp/bars_simple.html new file mode 100644 index 0000000..ba6f1de --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/bars_simple.html @@ -0,0 +1,131 @@ +<!DOCTYPE html> +<html> + <head> + <title>Bar Chart</title> + <script type="text/javascript" src="js/d3.js"></script> + <script type="text/javascript" src="js/jquery.js"></script> + <style type="text/css"> + +body { + font: 10px sans-serif; +} + +svg { + shape-rendering: crispEdges; +} + + </style> + </head> + <body> + <h1 id="resId">Resource</h1> + <h2 id="header">Schedule</h2> + <script type="text/javascript"> + + // Get the platforms and then the first one + $.getJSON('/rest/resource/platforms.json', function (json) { + var res = json[0]; + var rid = res.resourceId; + $("#resId").text("Resource " + rid + " (" + res.resourceName + ")"); + + // Now get the metrical schedules of the platform + $.getJSON("/rest/resource/"+rid+"/schedules.json?type=metric", function (json2) { + + // Take the first + var schId = json2[0].scheduleId; + $("#header").text("Schedule " + schId + " (" + json2[0].scheduleName + ")"); + + // And call d3 graphing on it + d3.json( + '/rest/metric/data/'+schId+'.json', + function (jsondata) { + + // create the chart here with + // the returned data + + var points = jsondata.dataPoints; + var min = jsondata.min; + var max = jsondata.max; + + var data = points.map(function(d) { + var t = d.value - min; + if (t<0) + t=0; + return t; + }); + + var w = 430, + h = 630, + x = d3.scale.linear().domain([0, max-min]).range([0, w]), + y = d3.scale.ordinal().domain(d3.range(data.length)).rangeBands([0, h], .2); + + var vis = d3.select("body") + .append("svg:svg") + .attr("width", w + 40) + .attr("height", h + 20) + .append("svg:g") + .attr("transform", "translate(20,0)"); + + var bars = vis.selectAll("g.bar") + .data(data) + .enter().append("svg:g") + .attr("class", "bar") + .attr("transform", function(d, i) { return "translate(0," + y(i) + ")"; }); + + bars.append("svg:rect") + .attr("fill", "steelblue") + .attr("width", x) + .attr("height", y.rangeBand()); + + bars.append("svg:text") + .attr("x", x) + .attr("y", y.rangeBand() / 2) + .attr("dx", -6) + .attr("dy", ".35em") + .attr("fill", "white") + .attr("text-anchor", "end") + .text(x.tickFormat(100)); + + bars.append("svg:text") + .attr("x", 0) + .attr("y", y.rangeBand() / 2) + .attr("dx", -6) + .attr("dy", ".35em") + .attr("text-anchor", "end") + .text(function(d, i) { return String.fromCharCode(65 + i); }); + + var rules = vis.selectAll("g.rule") + .data(x.ticks(10)) + .enter().append("svg:g") + .attr("class", "rule") + .attr("transform", function(d) { return "translate(" + x(d) + ",0)"; }); + + rules.append("svg:line") + .attr("y1", h) + .attr("y2", h + 6) + .attr("stroke", "black"); + + rules.append("svg:line") + .attr("y1", 0) + .attr("y2", h) + .attr("stroke", "white") + .attr("stroke-opacity", .3); + + rules.append("svg:text") + .attr("y", h + 9) + .attr("dy", ".71em") + .attr("text-anchor", "middle") + .text(x.tickFormat(10)); + + vis.append("svg:line") + .attr("y1", 0) + .attr("y2", h) + .attr("stroke", "black"); + + }); + + }) + }) + + </script> + </body> +</html> diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/index.html b/modules/enterprise/gui/rest-examples-war/src/main/webapp/index.html new file mode 100644 index 0000000..e42628a --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/index.html @@ -0,0 +1,40 @@ +<html> +<body> +<h2>RHQ Rest API</h2> +<strong>Please note: the API is not stable at this point. Do not rely on it.</strong><br/> + +Join us in making it great by providing feedback and contributions of code and examples +that use the api. +See also <a href="http://rhq-project.org/display/RHQ/Design-REST">the RHQ wiki</a> on REST. +Check out the <a href="https://github.com/rhq-project/samples/tree/master/rest-api">RHQ samples project</a> +for samples in various programming languages and +<a href="https://github.com/pilhuhn/RHQpocket">RHQpocket</a> as an example of a +mobile client (Android) of the API. +<ul> + <li><a href="resource/platforms.html">Platforms</a></li> + <li><a href="group/">Groups</a></li> + <li><a href="group/definitions">Group Definitions</a></li> + <li><a href="alert/">Alerts</a></li> + <li><a href="status.html">System status</a> </li> + <li><a href="user/favorites/resource">Favorite resources</a></li> + <li><a href="operation/history">Operation histories</a></li> +</ul> +<hr/> +<h2>Misc examples (using <a href="https://github.com/mbostock/d3">D3.js</a>)</h2> +Those examples use the powerful D3 library and are rendering the graphs in SVG. +They expect some resources and schedules being present from an initial import with +an empty database (meaning resource ids and schedule ids starting at 10001). +<ul> + <li><a href="/rest-examples/bars_simple.html">Display avg metrics as bars</a></li> + <li><a href="/rest-examples/stacked1.html">Metrics as stacked bars</a> in SVG</li> + <li><a href="/rest-examples/stacked3.html">Metrics as stacked bars</a> in pure HTML + (a little) CSS</li> + <li><a href="/rest-examples/stacked2.html">Metrics as rects using stacked bars from above</a></li> + <li><a href="/rest-examples/whisker.html">Whisker chart 1</a></li> + <li><a href="/rest-examples/whisker2.html">Multiple Whisker charts</a></li> + <li><a href="/rest-examples/tree.html">Resource tree</a></li> + <li><a href="/rest-examples/raw_graph.html">7 days of raw metrics as dot- or line- chart</a></li> + <li><a href="/rest-examples/raw_graph7.html">7 days of raw metrics as dot- or line- chart - comparing daily values</a></li> + +</ul> +</body> +</html> diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.behavior.js b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.behavior.js new file mode 100755 index 0000000..8c67949 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.behavior.js @@ -0,0 +1,198 @@ +(function(){d3.behavior = {}; +// TODO unbind zoom behavior? +// TODO unbind listener? +d3.behavior.zoom = function() { + var xyz = [0, 0, 0], + event = d3.dispatch("zoom"); + + function zoom() { + this + .on("mousedown.zoom", mousedown) + .on("mousewheel.zoom", mousewheel) + .on("DOMMouseScroll.zoom", dblclick) + .on("dblclick.zoom", dblclick) + .on("touchstart.zoom", touchstart); + + d3.select(window) + .on("mousemove.zoom", d3_behavior_zoomMousemove) + .on("mouseup.zoom", d3_behavior_zoomMouseup) + .on("touchmove.zoom", d3_behavior_zoomTouchmove) + .on("touchend.zoom", d3_behavior_zoomTouchup); + } + + // snapshot the local context for subsequent dispatch + function start() { + d3_behavior_zoomXyz = xyz; + d3_behavior_zoomDispatch = event.zoom.dispatch; + d3_behavior_zoomTarget = this; + d3_behavior_zoomArguments = arguments; + } + + function mousedown() { + start.apply(this, arguments); + d3_behavior_zoomPanning = d3_behavior_zoomLocation(d3.svg.mouse(d3_behavior_zoomTarget)); + d3.event.preventDefault(); + window.focus(); + } + + // store starting mouse location + function mousewheel() { + start.apply(this, arguments); + if (!d3_behavior_zoomZooming) d3_behavior_zoomZooming = d3_behavior_zoomLocation(d3.svg.mouse(d3_behavior_zoomTarget)); + d3_behavior_zoomTo(d3_behavior_zoomDelta() + xyz[2], d3.svg.mouse(d3_behavior_zoomTarget), d3_behavior_zoomZooming); + } + + function dblclick() { + start.apply(this, arguments); + var mouse = d3.svg.mouse(d3_behavior_zoomTarget); + d3_behavior_zoomTo(d3.event.shiftKey ? Math.ceil(xyz[2] - 1) : Math.floor(xyz[2] + 1), mouse, d3_behavior_zoomLocation(mouse)); + } + + // doubletap detection + function touchstart() { + start.apply(this, arguments); + var touches = d3_behavior_zoomTouchup(), + touch, + now = Date.now(); + if ((touches.length === 1) && (now - d3_behavior_zoomLast < 300)) { + d3_behavior_zoomTo(1 + Math.floor(xyz[2]), touch = touches[0], d3_behavior_zoomLocations[touch.identifier]); + } + d3_behavior_zoomLast = now; + } + + zoom.on = function(type, listener) { + event[type].add(listener); + return zoom; + }; + + return zoom; +}; + +var d3_behavior_zoomDiv, + d3_behavior_zoomPanning, + d3_behavior_zoomZooming, + d3_behavior_zoomLocations = {}, // identifier -> location + d3_behavior_zoomLast = 0, + d3_behavior_zoomXyz, + d3_behavior_zoomDispatch, + d3_behavior_zoomTarget, + d3_behavior_zoomArguments; + +function d3_behavior_zoomLocation(point) { + return [ + point[0] - d3_behavior_zoomXyz[0], + point[1] - d3_behavior_zoomXyz[1], + d3_behavior_zoomXyz[2] + ]; +} + +// detect the pixels that would be scrolled by this wheel event +function d3_behavior_zoomDelta() { + + // mousewheel events are totally broken! + // https://bugs.webkit.org/show_bug.cgi?id=40441 + // not only that, but Chrome and Safari differ in re. to acceleration! + if (!d3_behavior_zoomDiv) { + d3_behavior_zoomDiv = d3.select("body").append("div") + .style("visibility", "hidden") + .style("top", 0) + .style("height", 0) + .style("width", 0) + .style("overflow-y", "scroll") + .append("div") + .style("height", "2000px") + .node().parentNode; + } + + var e = d3.event, delta; + try { + d3_behavior_zoomDiv.scrollTop = 1000; + d3_behavior_zoomDiv.dispatchEvent(e); + delta = 1000 - d3_behavior_zoomDiv.scrollTop; + } catch (error) { + delta = e.wheelDelta || -e.detail; + } + + return delta * .005; +} + +// Note: Since we don't rotate, it's possible for the touches to become +// slightly detached from their original positions. Thus, we recompute the +// touch points on touchend as well as touchstart! +function d3_behavior_zoomTouchup() { + var touches = d3.svg.touches(d3_behavior_zoomTarget), + i = -1, + n = touches.length, + touch; + while (++i < n) d3_behavior_zoomLocations[(touch = touches[i]).identifier] = d3_behavior_zoomLocation(touch); + return touches; +} + +function d3_behavior_zoomTouchmove() { + var touches = d3.svg.touches(d3_behavior_zoomTarget); + switch (touches.length) { + + // single-touch pan + case 1: { + var touch = touches[0]; + d3_behavior_zoomTo(d3_behavior_zoomXyz[2], touch, d3_behavior_zoomLocations[touch.identifier]); + break; + } + + // double-touch pan + zoom + case 2: { + var p0 = touches[0], + p1 = touches[1], + p2 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2], + l0 = d3_behavior_zoomLocations[p0.identifier], + l1 = d3_behavior_zoomLocations[p1.identifier], + l2 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2, l0[2]]; + d3_behavior_zoomTo(Math.log(d3.event.scale) / Math.LN2 + l0[2], p2, l2); + break; + } + } +} + +function d3_behavior_zoomMousemove() { + d3_behavior_zoomZooming = null; + if (d3_behavior_zoomPanning) d3_behavior_zoomTo(d3_behavior_zoomXyz[2], d3.svg.mouse(d3_behavior_zoomTarget), d3_behavior_zoomPanning); +} + +function d3_behavior_zoomMouseup() { + if (d3_behavior_zoomPanning) { + d3_behavior_zoomMousemove(); + d3_behavior_zoomPanning = null; + } +} + +function d3_behavior_zoomTo(z, x0, x1) { + var K = Math.pow(2, (d3_behavior_zoomXyz[2] = z) - x1[2]), + x = d3_behavior_zoomXyz[0] = x0[0] - K * x1[0], + y = d3_behavior_zoomXyz[1] = x0[1] - K * x1[1], + o = d3.event, // Events can be reentrant (e.g., focus). + k = Math.pow(2, z); + + d3.event = { + scale: k, + translate: [x, y], + transform: function(sx, sy) { + if (sx) transform(sx, x); + if (sy) transform(sy, y); + } + }; + + function transform(scale, o) { + var domain = scale.__domain || (scale.__domain = scale.domain()), + range = scale.range().map(function(v) { return (v - o) / k; }); + scale.domain(domain).domain(range.map(scale.invert)); + } + + try { + d3_behavior_zoomDispatch.apply(d3_behavior_zoomTarget, d3_behavior_zoomArguments); + } finally { + d3.event = o; + } + + o.preventDefault(); +} +})(); diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.chart.js b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.chart.js new file mode 100755 index 0000000..281d007 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.chart.js @@ -0,0 +1,984 @@ +(function(){d3.chart = {}; +// Inspired by http://informationandvisualization.de/blog/box-plot +d3.chart.box = function() { + var width = 1, + height = 1, + duration = 0, + domain = null, + value = Number, + whiskers = d3_chart_boxWhiskers, + quartiles = d3_chart_boxQuartiles, + tickFormat = null; + + // For each small multiple… + function box(g) { + g.each(function(d, i) { + d = d.map(value).sort(d3.ascending); + var g = d3.select(this), + n = d.length, + min = d[0], + max = d[n - 1]; + + // Compute quartiles. Must return exactly 3 elements. + var quartileData = d.quartiles = quartiles(d); + + // Compute whiskers. Must return exactly 2 elements, or null. + var whiskerIndices = whiskers && whiskers.call(this, d, i), + whiskerData = whiskerIndices && whiskerIndices.map(function(i) { return d[i]; }); + + // Compute outliers. If no whiskers are specified, all data are "outliers". + // We compute the outliers as indices, so that we can join across transitions! + var outlierIndices = whiskerIndices + ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) + : d3.range(n); + + // Compute the new x-scale. + var x1 = d3.scale.linear() + .domain(domain && domain.call(this, d, i) || [min, max]) + .range([height, 0]); + + // Retrieve the old x-scale, if this is an update. + var x0 = this.__chart__ || d3.scale.linear() + .domain([0, Infinity]) + .range(x1.range()); + + // Stash the new scale. + this.__chart__ = x1; + + // Note: the box, median, and box tick elements are fixed in number, + // so we only have to handle enter and update. In contrast, the outliers + // and other elements are variable, so we need to exit them! Variable + // elements also fade in and out. + + // Update center line: the vertical line spanning the whiskers. + var center = g.selectAll("line.center") + .data(whiskerData ? [whiskerData] : []); + + center.enter().insert("svg:line", "rect") + .attr("class", "center") + .attr("x1", width / 2) + .attr("y1", function(d) { return x0(d[0]); }) + .attr("x2", width / 2) + .attr("y2", function(d) { return x0(d[1]); }) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .style("opacity", 1) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }); + + center.transition() + .duration(duration) + .style("opacity", 1) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }); + + center.exit().transition() + .duration(duration) + .style("opacity", 1e-6) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }) + .remove(); + + // Update innerquartile box. + var box = g.selectAll("rect.box") + .data([quartileData]); + + box.enter().append("svg:rect") + .attr("class", "box") + .attr("x", 0) + .attr("y", function(d) { return x0(d[2]); }) + .attr("width", width) + .attr("height", function(d) { return x0(d[0]) - x0(d[2]); }) + .transition() + .duration(duration) + .attr("y", function(d) { return x1(d[2]); }) + .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); + + box.transition() + .duration(duration) + .attr("y", function(d) { return x1(d[2]); }) + .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); + + // Update median line. + var medianLine = g.selectAll("line.median") + .data([quartileData[1]]); + + medianLine.enter().append("svg:line") + .attr("class", "median") + .attr("x1", 0) + .attr("y1", x0) + .attr("x2", width) + .attr("y2", x0) + .transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1); + + medianLine.transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1); + + // Update whiskers. + var whisker = g.selectAll("line.whisker") + .data(whiskerData || []); + + whisker.enter().insert("svg:line", "circle, text") + .attr("class", "whisker") + .attr("x1", 0) + .attr("y1", x0) + .attr("x2", width) + .attr("y2", x0) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1); + + whisker.transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1); + + whisker.exit().transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1e-6) + .remove(); + + // Update outliers. + var outlier = g.selectAll("circle.outlier") + .data(outlierIndices, Number); + + outlier.enter().insert("svg:circle", "text") + .attr("class", "outlier") + .attr("r", 5) + .attr("cx", width / 2) + .attr("cy", function(i) { return x0(d[i]); }) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1); + + outlier.transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1); + + outlier.exit().transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1e-6) + .remove(); + + // Compute the tick format. + var format = tickFormat || x1.tickFormat(8); + + // Update box ticks. + var boxTick = g.selectAll("text.box") + .data(quartileData); + + boxTick.enter().append("svg:text") + .attr("class", "box") + .attr("dy", ".3em") + .attr("dx", function(d, i) { return i & 1 ? 6 : -6 }) + .attr("x", function(d, i) { return i & 1 ? width : 0 }) + .attr("y", x0) + .attr("text-anchor", function(d, i) { return i & 1 ? "start" : "end"; }) + .text(format) + .transition() + .duration(duration) + .attr("y", x1); + + boxTick.transition() + .duration(duration) + .text(format) + .attr("y", x1); + + // Update whisker ticks. These are handled separately from the box + // ticks because they may or may not exist, and we want don't want + // to join box ticks pre-transition with whisker ticks post-. + var whiskerTick = g.selectAll("text.whisker") + .data(whiskerData || []); + + whiskerTick.enter().append("svg:text") + .attr("class", "whisker") + .attr("dy", ".3em") + .attr("dx", 6) + .attr("x", width) + .attr("y", x0) + .text(format) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("y", x1) + .style("opacity", 1); + + whiskerTick.transition() + .duration(duration) + .text(format) + .attr("y", x1) + .style("opacity", 1); + + whiskerTick.exit().transition() + .duration(duration) + .attr("y", x1) + .style("opacity", 1e-6) + .remove(); + }); + d3.timer.flush(); + } + + box.width = function(x) { + if (!arguments.length) return width; + width = x; + return box; + }; + + box.height = function(x) { + if (!arguments.length) return height; + height = x; + return box; + }; + + box.tickFormat = function(x) { + if (!arguments.length) return tickFormat; + tickFormat = x; + return box; + }; + + box.duration = function(x) { + if (!arguments.length) return duration; + duration = x; + return box; + }; + + box.domain = function(x) { + if (!arguments.length) return domain; + domain = x == null ? x : d3.functor(x); + return box; + }; + + box.value = function(x) { + if (!arguments.length) return value; + value = x; + return box; + }; + + box.whiskers = function(x) { + if (!arguments.length) return whiskers; + whiskers = x; + return box; + }; + + box.quartiles = function(x) { + if (!arguments.length) return quartiles; + quartiles = x; + return box; + }; + + return box; +}; + +function d3_chart_boxWhiskers(d) { + return [0, d.length - 1]; +} + +function d3_chart_boxQuartiles(d) { + return [ + d3.quantile(d, .25), + d3.quantile(d, .5), + d3.quantile(d, .75) + ]; +} +// Chart design based on the recommendations of Stephen Few. Implementation +// based on the work of Clint Ivy, Jamie Love, and Jason Davies. +// http://projects.instantcognition.com/protovis/bulletchart/ +d3.chart.bullet = function() { + var orient = "left", // TODO top & bottom + reverse = false, + duration = 0, + ranges = d3_chart_bulletRanges, + markers = d3_chart_bulletMarkers, + measures = d3_chart_bulletMeasures, + width = 380, + height = 30, + tickFormat = null; + + // For each small multiple… + function bullet(g) { + g.each(function(d, i) { + var rangez = ranges.call(this, d, i).slice().sort(d3.descending), + markerz = markers.call(this, d, i).slice().sort(d3.descending), + measurez = measures.call(this, d, i).slice().sort(d3.descending), + g = d3.select(this); + + // Compute the new x-scale. + var x1 = d3.scale.linear() + .domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) + .range(reverse ? [width, 0] : [0, width]); + + // Retrieve the old x-scale, if this is an update. + var x0 = this.__chart__ || d3.scale.linear() + .domain([0, Infinity]) + .range(x1.range()); + + // Stash the new scale. + this.__chart__ = x1; + + // Derive width-scales from the x-scales. + var w0 = d3_chart_bulletWidth(x0), + w1 = d3_chart_bulletWidth(x1); + + // Update the range rects. + var range = g.selectAll("rect.range") + .data(rangez); + + range.enter().append("svg:rect") + .attr("class", function(d, i) { return "range s" + i; }) + .attr("width", w0) + .attr("height", height) + .attr("x", reverse ? x0 : 0) + .transition() + .duration(duration) + .attr("width", w1) + .attr("x", reverse ? x1 : 0); + + range.transition() + .duration(duration) + .attr("x", reverse ? x1 : 0) + .attr("width", w1) + .attr("height", height); + + // Update the measure rects. + var measure = g.selectAll("rect.measure") + .data(measurez); + + measure.enter().append("svg:rect") + .attr("class", function(d, i) { return "measure s" + i; }) + .attr("width", w0) + .attr("height", height / 3) + .attr("x", reverse ? x0 : 0) + .attr("y", height / 3) + .transition() + .duration(duration) + .attr("width", w1) + .attr("x", reverse ? x1 : 0); + + measure.transition() + .duration(duration) + .attr("width", w1) + .attr("height", height / 3) + .attr("x", reverse ? x1 : 0) + .attr("y", height / 3); + + // Update the marker lines. + var marker = g.selectAll("line.marker") + .data(markerz); + + marker.enter().append("svg:line") + .attr("class", "marker") + .attr("x1", x0) + .attr("x2", x0) + .attr("y1", height / 6) + .attr("y2", height * 5 / 6) + .transition() + .duration(duration) + .attr("x1", x1) + .attr("x2", x1); + + marker.transition() + .duration(duration) + .attr("x1", x1) + .attr("x2", x1) + .attr("y1", height / 6) + .attr("y2", height * 5 / 6); + + // Compute the tick format. + var format = tickFormat || x1.tickFormat(8); + + // Update the tick groups. + var tick = g.selectAll("g.tick") + .data(x1.ticks(8), function(d) { + return this.textContent || format(d); + }); + + // Initialize the ticks with the old scale, x0. + var tickEnter = tick.enter().append("svg:g") + .attr("class", "tick") + .attr("transform", d3_chart_bulletTranslate(x0)) + .style("opacity", 1e-6); + + tickEnter.append("svg:line") + .attr("y1", height) + .attr("y2", height * 7 / 6); + + tickEnter.append("svg:text") + .attr("text-anchor", "middle") + .attr("dy", "1em") + .attr("y", height * 7 / 6) + .text(format); + + // Transition the entering ticks to the new scale, x1. + tickEnter.transition() + .duration(duration) + .attr("transform", d3_chart_bulletTranslate(x1)) + .style("opacity", 1); + + // Transition the updating ticks to the new scale, x1. + var tickUpdate = tick.transition() + .duration(duration) + .attr("transform", d3_chart_bulletTranslate(x1)) + .style("opacity", 1); + + tickUpdate.select("line") + .attr("y1", height) + .attr("y2", height * 7 / 6); + + tickUpdate.select("text") + .attr("y", height * 7 / 6); + + // Transition the exiting ticks to the new scale, x1. + tick.exit().transition() + .duration(duration) + .attr("transform", d3_chart_bulletTranslate(x1)) + .style("opacity", 1e-6) + .remove(); + }); + d3.timer.flush(); + } + + // left, right, top, bottom + bullet.orient = function(x) { + if (!arguments.length) return orient; + orient = x; + reverse = orient == "right" || orient == "bottom"; + return bullet; + }; + + // ranges (bad, satisfactory, good) + bullet.ranges = function(x) { + if (!arguments.length) return ranges; + ranges = x; + return bullet; + }; + + // markers (previous, goal) + bullet.markers = function(x) { + if (!arguments.length) return markers; + markers = x; + return bullet; + }; + + // measures (actual, forecast) + bullet.measures = function(x) { + if (!arguments.length) return measures; + measures = x; + return bullet; + }; + + bullet.width = function(x) { + if (!arguments.length) return width; + width = x; + return bullet; + }; + + bullet.height = function(x) { + if (!arguments.length) return height; + height = x; + return bullet; + }; + + bullet.tickFormat = function(x) { + if (!arguments.length) return tickFormat; + tickFormat = x; + return bullet; + }; + + bullet.duration = function(x) { + if (!arguments.length) return duration; + duration = x; + return bullet; + }; + + return bullet; +}; + +function d3_chart_bulletRanges(d) { + return d.ranges; +} + +function d3_chart_bulletMarkers(d) { + return d.markers; +} + +function d3_chart_bulletMeasures(d) { + return d.measures; +} + +function d3_chart_bulletTranslate(x) { + return function(d) { + return "translate(" + x(d) + ",0)"; + }; +} + +function d3_chart_bulletWidth(x) { + var x0 = x(0); + return function(d) { + return Math.abs(x(d) - x0); + }; +} +// Implements a horizon layout, which is a variation of a single-series +// area chart where the area is folded into multiple bands. Color is used to +// encode band, allowing the size of the chart to be reduced significantly +// without impeding readability. This layout algorithm is based on the work of +// J. Heer, N. Kong and M. Agrawala in "Sizing the Horizon: The Effects of Chart +// Size and Layering on the Graphical Perception of Time Series Visualizations", +// CHI 2009. http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf +d3.chart.horizon = function() { + var bands = 1, // between 1 and 5, typically + mode = "offset", // or mirror + interpolate = "linear", // or basis, monotone, step-before, etc. + x = d3_chart_horizonX, + y = d3_chart_horizonY, + w = 960, + h = 40, + duration = 0; + + var color = d3.scale.linear() + .domain([-1, 0, 1]) + .range(["#d62728", "#fff", "#1f77b4"]); + + // For each small multiple… + function horizon(g) { + g.each(function(d, i) { + var g = d3.select(this), + n = 2 * bands + 1, + xMin = Infinity, + xMax = -Infinity, + yMax = -Infinity, + x0, // old x-scale + y0, // old y-scale + id; // unique id for paths + + // Compute x- and y-values along with extents. + var data = d.map(function(d, i) { + var xv = x.call(this, d, i), + yv = y.call(this, d, i); + if (xv < xMin) xMin = xv; + if (xv > xMax) xMax = xv; + if (-yv > yMax) yMax = -yv; + if (yv > yMax) yMax = yv; + return [xv, yv]; + }); + + // Compute the new x- and y-scales. + var x1 = d3.scale.linear().domain([xMin, xMax]).range([0, w]), + y1 = d3.scale.linear().domain([0, yMax]).range([0, h * bands]); + + // Retrieve the old scales, if this is an update. + if (this.__chart__) { + x0 = this.__chart__.x; + y0 = this.__chart__.y; + id = this.__chart__.id; + } else { + x0 = d3.scale.linear().domain([0, Infinity]).range(x1.range()); + y0 = d3.scale.linear().domain([0, Infinity]).range(y1.range()); + id = ++d3_chart_horizonId; + } + + // We'll use a defs to store the area path and the clip path. + var defs = g.selectAll("defs") + .data([data]); + + var defsEnter = defs.enter().append("svg:defs"); + + // The clip path is a simple rect. + defsEnter.append("svg:clipPath") + .attr("id", "d3_chart_horizon_clip" + id) + .append("svg:rect") + .attr("width", w) + .attr("height", h); + + defs.select("rect").transition() + .duration(duration) + .attr("width", w) + .attr("height", h); + + // The area path is rendered with our resuable d3.svg.area. + defsEnter.append("svg:path") + .attr("id", "d3_chart_horizon_path" + id) + .attr("d", d3_chart_horizonArea + .interpolate(interpolate) + .x(function(d) { return x0(d[0]); }) + .y0(h * bands) + .y1(function(d) { return h * bands - y0(d[1]); })) + .transition() + .duration(duration) + .attr("d", d3_chart_horizonArea + .x(function(d) { return x1(d[0]); }) + .y1(function(d) { return h * bands - y1(d[1]); })); + + defs.select("path").transition() + .duration(duration) + .attr("d", d3_chart_horizonArea); + + // We'll use a container to clip all horizon layers at once. + g.selectAll("g") + .data([null]) + .enter().append("svg:g") + .attr("clip-path", "url(#d3_chart_horizon_clip" + id + ")"); + + // Define the transform function based on the mode. + var transform = mode == "offset" + ? function(d) { return "translate(0," + (d + (d < 0) - bands) * h + ")"; } + : function(d) { return (d < 0 ? "scale(1,-1)" : "") + "translate(0," + (d - bands) * h + ")"; }; + + // Instantiate each copy of the path with different transforms. + var u = g.select("g").selectAll("use") + .data(d3.range(-1, -bands - 1, -1).concat(d3.range(1, bands + 1)), Number); + + // TODO don't fudge the enter transition + u.enter().append("svg:use") + .attr("xlink:href", "#d3_chart_horizon_path" + id) + .attr("transform", function(d) { return transform(d + (d > 0 ? 1 : -1)); }) + .style("fill", color) + .transition() + .duration(duration) + .attr("transform", transform); + + u.transition() + .duration(duration) + .attr("transform", transform) + .style("fill", color); + + u.exit().transition() + .duration(duration) + .attr("transform", transform) + .remove(); + + // Stash the new scales. + this.__chart__ = {x: x1, y: y1, id: id}; + }); + d3.timer.flush(); + } + + horizon.duration = function(x) { + if (!arguments.length) return duration; + duration = +x; + return horizon; + }; + + horizon.bands = function(x) { + if (!arguments.length) return bands; + bands = +x; + color.domain([-bands, 0, bands]); + return horizon; + }; + + horizon.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return horizon; + }; + + horizon.colors = function(x) { + if (!arguments.length) return color.range(); + color.range(x); + return horizon; + }; + + horizon.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x + ""; + return horizon; + }; + + horizon.x = function(z) { + if (!arguments.length) return x; + x = z; + return horizon; + }; + + horizon.y = function(z) { + if (!arguments.length) return y; + y = z; + return horizon; + }; + + horizon.width = function(x) { + if (!arguments.length) return w; + w = +x; + return horizon; + }; + + horizon.height = function(x) { + if (!arguments.length) return h; + h = +x; + return horizon; + }; + + return horizon; +}; + +var d3_chart_horizonArea = d3.svg.area(), + d3_chart_horizonId = 0; + +function d3_chart_horizonX(d) { + return d[0]; +} + +function d3_chart_horizonY(d) { + return d[1]; +} +// Based on http://vis.stanford.edu/protovis/ex/qqplot.html +d3.chart.qq = function() { + var width = 1, + height = 1, + duration = 0, + domain = null, + tickFormat = null, + n = 100, + x = d3_chart_qqX, + y = d3_chart_qqY; + + // For each small multiple… + function qq(g) { + g.each(function(d, i) { + var g = d3.select(this), + qx = d3_chart_qqQuantiles(n, x.call(this, d, i)), + qy = d3_chart_qqQuantiles(n, y.call(this, d, i)), + xd = domain && domain.call(this, d, i) || [d3.min(qx), d3.max(qx)], // new x-domain + yd = domain && domain.call(this, d, i) || [d3.min(qy), d3.max(qy)], // new y-domain + x0, // old x-scale + y0; // old y-scale + + // Compute the new x-scale. + var x1 = d3.scale.linear() + .domain(xd) + .range([0, width]); + + // Compute the new y-scale. + var y1 = d3.scale.linear() + .domain(yd) + .range([height, 0]); + + // Retrieve the old scales, if this is an update. + if (this.__chart__) { + x0 = this.__chart__.x; + y0 = this.__chart__.y; + } else { + x0 = d3.scale.linear().domain([0, Infinity]).range(x1.range()); + y0 = d3.scale.linear().domain([0, Infinity]).range(y1.range()); + } + + // Stash the new scales. + this.__chart__ = {x: x1, y: y1}; + + // Update diagonal line. + var diagonal = g.selectAll("line.diagonal") + .data([null]); + + diagonal.enter().append("svg:line") + .attr("class", "diagonal") + .attr("x1", x1(yd[0])) + .attr("y1", y1(xd[0])) + .attr("x2", x1(yd[1])) + .attr("y2", y1(xd[1])); + + diagonal.transition() + .duration(duration) + .attr("x1", x1(yd[0])) + .attr("y1", y1(xd[0])) + .attr("x2", x1(yd[1])) + .attr("y2", y1(xd[1])); + + // Update quantile plots. + var circle = g.selectAll("circle") + .data(d3.range(n).map(function(i) { + return {x: qx[i], y: qy[i]}; + })); + + circle.enter().append("svg:circle") + .attr("class", "quantile") + .attr("r", 4.5) + .attr("cx", function(d) { return x0(d.x); }) + .attr("cy", function(d) { return y0(d.y); }) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("cx", function(d) { return x1(d.x); }) + .attr("cy", function(d) { return y1(d.y); }) + .style("opacity", 1); + + circle.transition() + .duration(duration) + .attr("cx", function(d) { return x1(d.x); }) + .attr("cy", function(d) { return y1(d.y); }) + .style("opacity", 1); + + circle.exit().transition() + .duration(duration) + .attr("cx", function(d) { return x1(d.x); }) + .attr("cy", function(d) { return y1(d.y); }) + .style("opacity", 1e-6) + .remove(); + + var xformat = tickFormat || x1.tickFormat(4), + yformat = tickFormat || y1.tickFormat(4), + tx = function(d) { return "translate(" + x1(d) + "," + height + ")"; }, + ty = function(d) { return "translate(0," + y1(d) + ")"; }; + + // Update x-ticks. + var xtick = g.selectAll("g.x.tick") + .data(x1.ticks(4), function(d) { + return this.textContent || xformat(d); + }); + + var xtickEnter = xtick.enter().append("svg:g") + .attr("class", "x tick") + .attr("transform", function(d) { return "translate(" + x0(d) + "," + height + ")"; }) + .style("opacity", 1e-6); + + xtickEnter.append("svg:line") + .attr("y1", 0) + .attr("y2", -6); + + xtickEnter.append("svg:text") + .attr("text-anchor", "middle") + .attr("dy", "1em") + .text(xformat); + + // Transition the entering ticks to the new scale, x1. + xtickEnter.transition() + .duration(duration) + .attr("transform", tx) + .style("opacity", 1); + + // Transition the updating ticks to the new scale, x1. + xtick.transition() + .duration(duration) + .attr("transform", tx) + .style("opacity", 1); + + // Transition the exiting ticks to the new scale, x1. + xtick.exit().transition() + .duration(duration) + .attr("transform", tx) + .style("opacity", 1e-6) + .remove(); + + // Update ticks. + var ytick = g.selectAll("g.y.tick") + .data(y1.ticks(4), function(d) { + return this.textContent || yformat(d); + }); + + var ytickEnter = ytick.enter().append("svg:g") + .attr("class", "y tick") + .attr("transform", function(d) { return "translate(0," + y0(d) + ")"; }) + .style("opacity", 1e-6); + + ytickEnter.append("svg:line") + .attr("x1", 0) + .attr("x2", 6); + + ytickEnter.append("svg:text") + .attr("text-anchor", "end") + .attr("dx", "-.5em") + .attr("dy", ".3em") + .text(yformat); + + // Transition the entering ticks to the new scale, y1. + ytickEnter.transition() + .duration(duration) + .attr("transform", ty) + .style("opacity", 1); + + // Transition the updating ticks to the new scale, y1. + ytick.transition() + .duration(duration) + .attr("transform", ty) + .style("opacity", 1); + + // Transition the exiting ticks to the new scale, y1. + ytick.exit().transition() + .duration(duration) + .attr("transform", ty) + .style("opacity", 1e-6) + .remove(); + }); + } + + qq.width = function(x) { + if (!arguments.length) return width; + width = x; + return qq; + }; + + qq.height = function(x) { + if (!arguments.length) return height; + height = x; + return qq; + }; + + qq.duration = function(x) { + if (!arguments.length) return duration; + duration = x; + return qq; + }; + + qq.domain = function(x) { + if (!arguments.length) return domain; + domain = x == null ? x : d3.functor(x); + return qq; + }; + + qq.count = function(z) { + if (!arguments.length) return n; + n = z; + return qq; + }; + + qq.x = function(z) { + if (!arguments.length) return x; + x = z; + return qq; + }; + + qq.y = function(z) { + if (!arguments.length) return y; + y = z; + return qq; + }; + + qq.tickFormat = function(x) { + if (!arguments.length) return tickFormat; + tickFormat = x; + return qq; + }; + + return qq; +}; + +function d3_chart_qqQuantiles(n, values) { + var m = values.length - 1; + values = values.slice().sort(d3.ascending); + return d3.range(n).map(function(i) { + return values[~~(i * m / n)]; + }); +} + +function d3_chart_qqX(d) { + return d.x; +} + +function d3_chart_qqY(d) { + return d.y; +} +})(); diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.csv.js b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.csv.js new file mode 100644 index 0000000..7565b83 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.csv.js @@ -0,0 +1,92 @@ +(function(){d3.csv = function(url, callback) { + d3.text(url, "text/csv", function(text) { + callback(text && d3.csv.parse(text)); + }); +}; +d3.csv.parse = function(text) { + var header; + return d3.csv.parseRows(text, function(row, i) { + if (i) { + var o = {}, j = -1, m = header.length; + while (++j < m) o[header[j]] = row[j]; + return o; + } else { + header = row; + return null; + } + }); +}; + +d3.csv.parseRows = function(text, f) { + var EOL = {}, // sentinel value for end-of-line + EOF = {}, // sentinel value for end-of-file + rows = [], // output rows + re = /\r\n|[,\r\n]/g, // field separator regex + n = 0, // the current line number + t, // the current token + eol; // is the current token followed by EOL? + + re.lastIndex = 0; // work-around bug in FF 3.6 + + /** @private Returns the next token. */ + function token() { + if (re.lastIndex >= text.length) return EOF; // special case: end of file + if (eol) { eol = false; return EOL; } // special case: end of line + + // special case: quotes + var j = re.lastIndex; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < text.length) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + i++; + } + } + re.lastIndex = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) re.lastIndex++; + } else if (c === 10) { + eol = true; + } + return text.substring(j + 1, i).replace(/""/g, """); + } + + // common case + var m = re.exec(text); + if (m) { + eol = m[0].charCodeAt(0) !== 44; + return text.substring(j, m.index); + } + re.lastIndex = text.length; + return text.substring(j); + } + + while ((t = token()) !== EOF) { + var a = []; + while ((t !== EOL) && (t !== EOF)) { + a.push(t); + t = token(); + } + if (f && !(a = f(a, n++))) continue; + rows.push(a); + } + + return rows; +}; +d3.csv.format = function(rows) { + return rows.map(d3_csv_formatRow).join("\n"); +}; + +function d3_csv_formatRow(row) { + return row.map(d3_csv_formatValue).join(","); +} + +function d3_csv_formatValue(text) { + return /[",\n]/.test(text) + ? """ + text.replace(/"/g, """") + """ + : text; +} +})(); diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geo.js b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geo.js new file mode 100644 index 0000000..2b40252 --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geo.js @@ -0,0 +1,938 @@ +(function(){d3.geo = {}; + +var d3_geo_radians = Math.PI / 180; +// TODO clip input coordinates on opposite hemisphere +d3.geo.azimuthal = function() { + var mode = "orthographic", // or stereographic, gnomonic, equidistant or equalarea + origin, + scale = 200, + translate = [480, 250], + x0, + y0, + cy0, + sy0; + + function azimuthal(coordinates) { + var x1 = coordinates[0] * d3_geo_radians - x0, + y1 = coordinates[1] * d3_geo_radians, + cx1 = Math.cos(x1), + sx1 = Math.sin(x1), + cy1 = Math.cos(y1), + sy1 = Math.sin(y1), + cc = mode !== "orthographic" ? sy0 * sy1 + cy0 * cy1 * cx1 : null, + c, + k = mode === "stereographic" ? 1 / (1 + cc) + : mode === "gnomonic" ? 1 / cc + : mode === "equidistant" ? (c = Math.acos(cc), c ? c / Math.sin(c) : 0) + : mode === "equalarea" ? Math.sqrt(2 / (1 + cc)) + : 1, + x = k * cy1 * sx1, + y = k * (sy0 * cy1 * cx1 - cy0 * sy1); + return [ + scale * x + translate[0], + scale * y + translate[1] + ]; + } + + azimuthal.invert = function(coordinates) { + var x = (coordinates[0] - translate[0]) / scale, + y = (coordinates[1] - translate[1]) / scale, + p = Math.sqrt(x * x + y * y), + c = mode === "stereographic" ? 2 * Math.atan(p) + : mode === "gnomonic" ? Math.atan(p) + : mode === "equidistant" ? p + : mode === "equalarea" ? 2 * Math.asin(.5 * p) + : Math.asin(p), + sc = Math.sin(c), + cc = Math.cos(c); + return [ + (x0 + Math.atan2(x * sc, p * cy0 * cc + y * sy0 * sc)) / d3_geo_radians, + Math.asin(cc * sy0 - (p ? (y * sc * cy0) / p : 0)) / d3_geo_radians + ]; + }; + + azimuthal.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return azimuthal; + }; + + azimuthal.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + x0 = origin[0] * d3_geo_radians; + y0 = origin[1] * d3_geo_radians; + cy0 = Math.cos(y0); + sy0 = Math.sin(y0); + return azimuthal; + }; + + azimuthal.scale = function(x) { + if (!arguments.length) return scale; + scale = +x; + return azimuthal; + }; + + azimuthal.translate = function(x) { + if (!arguments.length) return translate; + translate = [+x[0], +x[1]]; + return azimuthal; + }; + + return azimuthal.origin([0, 0]); +}; +// Derived from Tom Carden's Albers implementation for Protovis. +// http://gist.github.com/476238 +// http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html + +d3.geo.albers = function() { + var origin = [-98, 38], + parallels = [29.5, 45.5], + scale = 1000, + translate = [480, 250], + lng0, // d3_geo_radians * origin[0] + n, + C, + p0; + + function albers(coordinates) { + var t = n * (d3_geo_radians * coordinates[0] - lng0), + p = Math.sqrt(C - 2 * n * Math.sin(d3_geo_radians * coordinates[1])) / n; + return [ + scale * p * Math.sin(t) + translate[0], + scale * (p * Math.cos(t) - p0) + translate[1] + ]; + } + + albers.invert = function(coordinates) { + var x = (coordinates[0] - translate[0]) / scale, + y = (coordinates[1] - translate[1]) / scale, + p0y = p0 + y, + t = Math.atan2(x, p0y), + p = Math.sqrt(x * x + p0y * p0y); + return [ + (lng0 + t / n) / d3_geo_radians, + Math.asin((C - p * p * n * n) / (2 * n)) / d3_geo_radians + ]; + }; + + function reload() { + var phi1 = d3_geo_radians * parallels[0], + phi2 = d3_geo_radians * parallels[1], + lat0 = d3_geo_radians * origin[1], + s = Math.sin(phi1), + c = Math.cos(phi1); + lng0 = d3_geo_radians * origin[0]; + n = .5 * (s + Math.sin(phi2)); + C = c * c + 2 * n * s; + p0 = Math.sqrt(C - 2 * n * Math.sin(lat0)) / n; + return albers; + } + + albers.origin = function(x) { + if (!arguments.length) return origin; + origin = [+x[0], +x[1]]; + return reload(); + }; + + albers.parallels = function(x) { + if (!arguments.length) return parallels; + parallels = [+x[0], +x[1]]; + return reload(); + }; + + albers.scale = function(x) { + if (!arguments.length) return scale; + scale = +x; + return albers; + }; + + albers.translate = function(x) { + if (!arguments.length) return translate; + translate = [+x[0], +x[1]]; + return albers; + }; + + return reload(); +}; + +// A composite projection for the United States, 960x500. The set of standard +// parallels for each region comes from USGS, which is published here: +// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers +// TODO allow the composite projection to be rescaled? +d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + + var alaska = d3.geo.albers() + .origin([-160, 60]) + .parallels([55, 65]); + + var hawaii = d3.geo.albers() + .origin([-160, 20]) + .parallels([8, 18]); + + var puertoRico = d3.geo.albers() + .origin([-60, 10]) + .parallels([8, 18]); + + function albersUsa(coordinates) { + var lon = coordinates[0], + lat = coordinates[1]; + return (lat > 50 ? alaska + : lon < -140 ? hawaii + : lat < 21 ? puertoRico + : lower48)(coordinates); + } + + albersUsa.scale = function(x) { + if (!arguments.length) return lower48.scale(); + lower48.scale(x); + alaska.scale(x * .6); + hawaii.scale(x); + puertoRico.scale(x * 1.5); + return albersUsa.translate(lower48.translate()); + }; + + albersUsa.translate = function(x) { + if (!arguments.length) return lower48.translate(); + var dz = lower48.scale() / 1000, + dx = x[0], + dy = x[1]; + lower48.translate(x); + alaska.translate([dx - 400 * dz, dy + 170 * dz]); + hawaii.translate([dx - 190 * dz, dy + 200 * dz]); + puertoRico.translate([dx + 580 * dz, dy + 430 * dz]); + return albersUsa; + }; + + return albersUsa.scale(lower48.scale()); +}; +d3.geo.bonne = function() { + var scale = 200, + translate = [480, 250], + x0, // origin longitude in radians + y0, // origin latitude in radians + y1, // parallel latitude in radians + c1; // cot(y1) + + function bonne(coordinates) { + var x = coordinates[0] * d3_geo_radians - x0, + y = coordinates[1] * d3_geo_radians - y0; + if (y1) { + var p = c1 + y1 - y, E = x * Math.cos(y) / p; + x = p * Math.sin(E); + y = p * Math.cos(E) - c1; + } else { + x *= Math.cos(y); + y *= -1; + } + return [ + scale * x + translate[0], + scale * y + translate[1] + ]; + } + + bonne.invert = function(coordinates) { + var x = (coordinates[0] - translate[0]) / scale, + y = (coordinates[1] - translate[1]) / scale; + if (y1) { + var c = c1 + y, p = Math.sqrt(x * x + c * c); + y = c1 + y1 - p; + x = x0 + p * Math.atan2(x, c) / Math.cos(y); + } else { + y *= -1; + x /= Math.cos(y); + } + return [ + x / d3_geo_radians, + y / d3_geo_radians + ]; + }; + + // 90° for Werner, 0° for Sinusoidal + bonne.parallel = function(x) { + if (!arguments.length) return y1 / d3_geo_radians; + c1 = 1 / Math.tan(y1 = x * d3_geo_radians); + return bonne; + }; + + bonne.origin = function(x) { + if (!arguments.length) return [x0 / d3_geo_radians, y0 / d3_geo_radians]; + x0 = x[0] * d3_geo_radians; + y0 = x[1] * d3_geo_radians; + return bonne; + }; + + bonne.scale = function(x) { + if (!arguments.length) return scale; + scale = +x; + return bonne; + }; + + bonne.translate = function(x) { + if (!arguments.length) return translate; + translate = [+x[0], +x[1]]; + return bonne; + }; + + return bonne.origin([0, 0]).parallel(45); +}; +d3.geo.equirectangular = function() { + var scale = 500, + translate = [480, 250]; + + function equirectangular(coordinates) { + var x = coordinates[0] / 360, + y = -coordinates[1] / 360; + return [ + scale * x + translate[0], + scale * y + translate[1] + ]; + } + + equirectangular.invert = function(coordinates) { + var x = (coordinates[0] - translate[0]) / scale, + y = (coordinates[1] - translate[1]) / scale; + return [ + 360 * x, + -360 * y + ]; + }; + + equirectangular.scale = function(x) { + if (!arguments.length) return scale; + scale = +x; + return equirectangular; + }; + + equirectangular.translate = function(x) { + if (!arguments.length) return translate; + translate = [+x[0], +x[1]]; + return equirectangular; + }; + + return equirectangular; +}; +d3.geo.mercator = function() { + var scale = 500, + translate = [480, 250]; + + function mercator(coordinates) { + var x = coordinates[0] / 360, + y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_geo_radians / 2)) / d3_geo_radians) / 360; + return [ + scale * x + translate[0], + scale * Math.max(-.5, Math.min(.5, y)) + translate[1] + ]; + } + + mercator.invert = function(coordinates) { + var x = (coordinates[0] - translate[0]) / scale, + y = (coordinates[1] - translate[1]) / scale; + return [ + 360 * x, + 2 * Math.atan(Math.exp(-360 * y * d3_geo_radians)) / d3_geo_radians - 90 + ]; + }; + + mercator.scale = function(x) { + if (!arguments.length) return scale; + scale = +x; + return mercator; + }; + + mercator.translate = function(x) { + if (!arguments.length) return translate; + translate = [+x[0], +x[1]]; + return mercator; + }; + + return mercator; +}; +function d3_geo_type(types, defaultValue) { + return function(object) { + return object && object.type in types ? types[object.type](object) : defaultValue; + }; +} +/** + * Returns a function that, given a GeoJSON object (e.g., a feature), returns + * the corresponding SVG path. The function can be customized by overriding the + * projection. Point features are mapped to circles with a default radius of + * 4.5px; the radius can be specified either as a constant or a function that + * is evaluated per object. + */ +d3.geo.path = function() { + var pointRadius = 4.5, + pointCircle = d3_path_circle(pointRadius), + projection = d3.geo.albersUsa(); + + function path(d, i) { + if (typeof pointRadius === "function") { + pointCircle = d3_path_circle(pointRadius.apply(this, arguments)); + } + return pathType(d) || null; + } + + function project(coordinates) { + return projection(coordinates).join(","); + } + + var pathType = d3_geo_type({ + + FeatureCollection: function(o) { + var path = [], + features = o.features, + i = -1, // features.index + n = features.length; + while (++i < n) path.push(pathType(features[i].geometry)); + return path.join(""); + }, + + Feature: function(o) { + return pathType(o.geometry); + }, + + Point: function(o) { + return "M" + project(o.coordinates) + pointCircle; + }, + + MultiPoint: function(o) { + var path = [], + coordinates = o.coordinates, + i = -1, // coordinates.index + n = coordinates.length; + while (++i < n) path.push("M", project(coordinates[i]), pointCircle); + return path.join(""); + }, + + LineString: function(o) { + var path = ["M"], + coordinates = o.coordinates, + i = -1, // coordinates.index + n = coordinates.length; + while (++i < n) path.push(project(coordinates[i]), "L"); + path.pop(); + return path.join(""); + }, + + MultiLineString: function(o) { + var path = [], + coordinates = o.coordinates, + i = -1, // coordinates.index + n = coordinates.length, + subcoordinates, // coordinates[i] + j, // subcoordinates.index + m; // subcoordinates.length + while (++i < n) { + subcoordinates = coordinates[i]; + j = -1; + m = subcoordinates.length; + path.push("M"); + while (++j < m) path.push(project(subcoordinates[j]), "L"); + path.pop(); + } + return path.join(""); + }, + + Polygon: function(o) { + var path = [], + coordinates = o.coordinates, + i = -1, // coordinates.index + n = coordinates.length, + subcoordinates, // coordinates[i] + j, // subcoordinates.index + m; // subcoordinates.length + while (++i < n) { + subcoordinates = coordinates[i]; + j = -1; + if ((m = subcoordinates.length - 1) > 0) { + path.push("M"); + while (++j < m) path.push(project(subcoordinates[j]), "L"); + path[path.length - 1] = "Z"; + } + } + return path.join(""); + }, + + MultiPolygon: function(o) { + var path = [], + coordinates = o.coordinates, + i = -1, // coordinates index + n = coordinates.length, + subcoordinates, // coordinates[i] + j, // subcoordinates index + m, // subcoordinates.length + subsubcoordinates, // subcoordinates[j] + k, // subsubcoordinates index + p; // subsubcoordinates.length + while (++i < n) { + subcoordinates = coordinates[i]; + j = -1; + m = subcoordinates.length; + while (++j < m) { + subsubcoordinates = subcoordinates[j]; + k = -1; + if ((p = subsubcoordinates.length - 1) > 0) { + path.push("M"); + while (++k < p) path.push(project(subsubcoordinates[k]), "L"); + path[path.length - 1] = "Z"; + } + } + } + return path.join(""); + }, + + GeometryCollection: function(o) { + var path = [], + geometries = o.geometries, + i = -1, // geometries index + n = geometries.length; + while (++i < n) path.push(pathType(geometries[i])); + return path.join(""); + } + + }); + + var areaType = path.area = d3_geo_type({ + + FeatureCollection: function(o) { + var area = 0, + features = o.features, + i = -1, // features.index + n = features.length; + while (++i < n) area += areaType(features[i]); + return area; + }, + + Feature: function(o) { + return areaType(o.geometry); + }, + + Polygon: function(o) { + return polygonArea(o.coordinates); + }, + + MultiPolygon: function(o) { + var sum = 0, + coordinates = o.coordinates, + i = -1, // coordinates index + n = coordinates.length; + while (++i < n) sum += polygonArea(coordinates[i]); + return sum; + }, + + GeometryCollection: function(o) { + var sum = 0, + geometries = o.geometries, + i = -1, // geometries index + n = geometries.length; + while (++i < n) sum += areaType(geometries[i]); + return sum; + } + + }, 0); + + function polygonArea(coordinates) { + var sum = area(coordinates[0]), // exterior ring + i = 0, // coordinates.index + n = coordinates.length; + while (++i < n) sum -= area(coordinates[i]); // holes + return sum; + } + + function polygonCentroid(coordinates) { + var polygon = d3.geom.polygon(coordinates[0].map(projection)), // exterior ring + area = polygon.area(), + centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1), + x = centroid[0], + y = centroid[1], + z = area, + i = 0, // coordinates index + n = coordinates.length; + while (++i < n) { + polygon = d3.geom.polygon(coordinates[i].map(projection)); // holes + area = polygon.area(); + centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1); + x -= centroid[0]; + y -= centroid[1]; + z -= area; + } + return [x, y, 6 * z]; // weighted centroid + } + + var centroidType = path.centroid = d3_geo_type({ + + // TODO FeatureCollection + // TODO Point + // TODO MultiPoint + // TODO LineString + // TODO MultiLineString + // TODO GeometryCollection + + Feature: function(o) { + return centroidType(o.geometry); + }, + + Polygon: function(o) { + var centroid = polygonCentroid(o.coordinates); + return [centroid[0] / centroid[2], centroid[1] / centroid[2]]; + }, + + MultiPolygon: function(o) { + var area = 0, + coordinates = o.coordinates, + centroid, + x = 0, + y = 0, + z = 0, + i = -1, // coordinates index + n = coordinates.length; + while (++i < n) { + centroid = polygonCentroid(coordinates[i]); + x += centroid[0]; + y += centroid[1]; + z += centroid[2]; + } + return [x / z, y / z]; + } + + }); + + function area(coordinates) { + return Math.abs(d3.geom.polygon(coordinates.map(projection)).area()); + } + + path.projection = function(x) { + projection = x; + return path; + }; + + path.pointRadius = function(x) { + if (typeof x === "function") pointRadius = x; + else { + pointRadius = +x; + pointCircle = d3_path_circle(pointRadius); + } + return path; + }; + + return path; +}; + +function d3_path_circle(radius) { + return "m0," + radius + + "a" + radius + "," + radius + " 0 1,1 0," + (-2 * radius) + + "a" + radius + "," + radius + " 0 1,1 0," + (+2 * radius) + + "z"; +} +/** + * Given a GeoJSON object, returns the corresponding bounding box. The bounding + * box is represented by a two-dimensional array: [[left, bottom], [right, + * top]], where left is the minimum longitude, bottom is the minimum latitude, + * right is maximum longitude, and top is the maximum latitude. + */ +d3.geo.bounds = function(feature) { + var left = Infinity, + bottom = Infinity, + right = -Infinity, + top = -Infinity; + d3_geo_bounds(feature, function(x, y) { + if (x < left) left = x; + if (x > right) right = x; + if (y < bottom) bottom = y; + if (y > top) top = y; + }); + return [[left, bottom], [right, top]]; +}; + +function d3_geo_bounds(o, f) { + if (o.type in d3_geo_boundsTypes) d3_geo_boundsTypes[o.type](o, f); +} + +var d3_geo_boundsTypes = { + Feature: d3_geo_boundsFeature, + FeatureCollection: d3_geo_boundsFeatureCollection, + GeometryCollection: d3_geo_boundsGeometryCollection, + LineString: d3_geo_boundsLineString, + MultiLineString: d3_geo_boundsMultiLineString, + MultiPoint: d3_geo_boundsLineString, + MultiPolygon: d3_geo_boundsMultiPolygon, + Point: d3_geo_boundsPoint, + Polygon: d3_geo_boundsPolygon +}; + +function d3_geo_boundsFeature(o, f) { + d3_geo_bounds(o.geometry, f); +} + +function d3_geo_boundsFeatureCollection(o, f) { + for (var a = o.features, i = 0, n = a.length; i < n; i++) { + d3_geo_bounds(a[i].geometry, f); + } +} + +function d3_geo_boundsGeometryCollection(o, f) { + for (var a = o.geometries, i = 0, n = a.length; i < n; i++) { + d3_geo_bounds(a[i], f); + } +} + +function d3_geo_boundsLineString(o, f) { + for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { + f.apply(null, a[i]); + } +} + +function d3_geo_boundsMultiLineString(o, f) { + for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { + for (var b = a[i], j = 0, m = b.length; j < m; j++) { + f.apply(null, b[j]); + } + } +} + +function d3_geo_boundsMultiPolygon(o, f) { + for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) { + for (var b = a[i][0], j = 0, m = b.length; j < m; j++) { + f.apply(null, b[j]); + } + } +} + +function d3_geo_boundsPoint(o, f) { + f.apply(null, o.coordinates); +} + +function d3_geo_boundsPolygon(o, f) { + for (var a = o.coordinates[0], i = 0, n = a.length; i < n; i++) { + f.apply(null, a[i]); + } +} +// TODO breakAtDateLine? + +d3.geo.circle = function() { + var origin = [0, 0], + degrees = 90 - 1e-2, + radians = degrees * d3_geo_radians, + arc = d3.geo.greatArc().target(Object); + + function circle() { + // TODO render a circle as a Polygon + } + + function visible(point) { + return arc.distance(point) < radians; + } + + circle.clip = function(d) { + arc.source(typeof origin === "function" ? origin.apply(this, arguments) : origin); + return clipType(d); + }; + + var clipType = d3_geo_type({ + + FeatureCollection: function(o) { + var features = o.features.map(clipType).filter(Object); + return features && (o = Object.create(o), o.features = features, o); + }, + + Feature: function(o) { + var geometry = clipType(o.geometry); + return geometry && (o = Object.create(o), o.geometry = geometry, o); + }, + + Point: function(o) { + return visible(o.coordinates) && o; + }, + + MultiPoint: function(o) { + var coordinates = o.coordinates.filter(visible); + return coordinates.length && { + type: o.type, + coordinates: coordinates + }; + }, + + LineString: function(o) { + var coordinates = clip(o.coordinates); + return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); + }, + + MultiLineString: function(o) { + var coordinates = o.coordinates.map(clip).filter(function(d) { return d.length; }); + return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); + }, + + Polygon: function(o) { + var coordinates = o.coordinates.map(clip); + return coordinates[0].length && (o = Object.create(o), o.coordinates = coordinates, o); + }, + + MultiPolygon: function(o) { + var coordinates = o.coordinates.map(function(d) { return d.map(clip); }).filter(function(d) { return d[0].length; }); + return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o); + }, + + GeometryCollection: function(o) { + var geometries = o.geometries.map(clipType).filter(Object); + return geometries.length && (o = Object.create(o), o.geometries = geometries, o); + } + + }); + + function clip(coordinates) { + var i = -1, + n = coordinates.length, + clipped = [], + p0, + p1, + p2, + d0, + d1; + + while (++i < n) { + d1 = arc.distance(p2 = coordinates[i]); + if (d1 < radians) { + if (p1) clipped.push(d3_geo_greatArcInterpolate(p1, p2)((d0 - radians) / (d0 - d1))); + clipped.push(p2); + p0 = p1 = null; + } else { + p1 = p2; + if (!p0 && clipped.length) { + clipped.push(d3_geo_greatArcInterpolate(clipped[clipped.length - 1], p1)((radians - d0) / (d1 - d0))); + p0 = p1; + } + } + d0 = d1; + } + + if (p1 && clipped.length) { + d1 = arc.distance(p2 = clipped[0]); + clipped.push(d3_geo_greatArcInterpolate(p1, p2)((d0 - radians) / (d0 - d1))); + } + + return resample(clipped); + } + + // Resample coordinates, creating great arcs between each. + function resample(coordinates) { + var i = 0, + n = coordinates.length, + j, + m, + resampled = n ? [coordinates[0]] : coordinates, + resamples, + origin = arc.source(); + + while (++i < n) { + resamples = arc.source(coordinates[i - 1])(coordinates[i]).coordinates; + for (j = 0, m = resamples.length; ++j < m;) resampled.push(resamples[j]); + } + + arc.source(origin); + return resampled; + } + + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + + circle.angle = function(x) { + if (!arguments.length) return degrees; + radians = (degrees = +x) * d3_geo_radians; + return circle; + }; + + // Precision is specified in degrees. + circle.precision = function(x) { + if (!arguments.length) return arc.precision(); + arc.precision(x); + return circle; + }; + + return circle; +} +d3.geo.greatArc = function() { + var source = d3_geo_greatArcSource, + target = d3_geo_greatArcTarget, + precision = 6 * d3_geo_radians; + + function greatArc() { + var a = typeof source === "function" ? source.apply(this, arguments) : source, + b = typeof target === "function" ? target.apply(this, arguments) : target, + i = d3_geo_greatArcInterpolate(a, b), + dt = precision / i.d, + t = 0, + coordinates = [a]; + while ((t += dt) < 1) coordinates.push(i(t)); + coordinates.push(b); + return { + type: "LineString", + coordinates: coordinates + }; + } + + // Length returned in radians; multiply by radius for distance. + greatArc.distance = function() { + var a = typeof source === "function" ? source.apply(this, arguments) : source, + b = typeof target === "function" ? target.apply(this, arguments) : target; + return d3_geo_greatArcInterpolate(a, b).d; + }; + + greatArc.source = function(x) { + if (!arguments.length) return source; + source = x; + return greatArc; + }; + + greatArc.target = function(x) { + if (!arguments.length) return target; + target = x; + return greatArc; + }; + + // Precision is specified in degrees. + greatArc.precision = function(x) { + if (!arguments.length) return precision / d3_geo_radians; + precision = x * d3_geo_radians; + return greatArc; + }; + + return greatArc; +}; + +function d3_geo_greatArcSource(d) { + return d.source; +} + +function d3_geo_greatArcTarget(d) { + return d.target; +} + +function d3_geo_greatArcInterpolate(a, b) { + var x0 = a[0] * d3_geo_radians, cx0 = Math.cos(x0), sx0 = Math.sin(x0), + y0 = a[1] * d3_geo_radians, cy0 = Math.cos(y0), sy0 = Math.sin(y0), + x1 = b[0] * d3_geo_radians, cx1 = Math.cos(x1), sx1 = Math.sin(x1), + y1 = b[1] * d3_geo_radians, cy1 = Math.cos(y1), sy1 = Math.sin(y1), + d = interpolate.d = Math.acos(Math.max(-1, Math.min(1, sy0 * sy1 + cy0 * cy1 * Math.cos(x1 - x0)))), + sd = Math.sin(d); + + // From http://williams.best.vwh.net/avform.htm#Intermediate + function interpolate(t) { + var A = Math.sin(d - (t *= d)) / sd, + B = Math.sin(t) / sd, + x = A * cy0 * cx0 + B * cy1 * cx1, + y = A * cy0 * sx0 + B * cy1 * sx1, + z = A * sy0 + B * sy1; + return [ + Math.atan2(y, x) / d3_geo_radians, + Math.atan2(z, Math.sqrt(x * x + y * y)) / d3_geo_radians + ]; + } + + return interpolate; +} +d3.geo.greatCircle = d3.geo.circle; +})(); diff --git a/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geom.js b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geom.js new file mode 100644 index 0000000..d860c2b --- /dev/null +++ b/modules/enterprise/gui/rest-examples-war/src/main/webapp/js/d3.geom.js @@ -0,0 +1,835 @@ +(function(){d3.geom = {}; +/** + * Computes a contour for a given input grid function using the <a + * href="http://en.wikipedia.org/wiki/Marching_squares%22%3Emarching + * squares</a> algorithm. Returns the contour polygon as an array of points. + * + * @param grid a two-input function(x, y) that returns true for values + * inside the contour and false for values outside the contour. + * @param start an optional starting point [x, y] on the grid. + * @returns polygon [[x1, y1], [x2, y2], …] + */ +d3.geom.contour = function(grid, start) { + var s = start || d3_geom_contourStart(grid), // starting point + c = [], // contour polygon + x = s[0], // current x position + y = s[1], // current y position + dx = 0, // next x direction + dy = 0, // next y direction + pdx = NaN, // previous x direction + pdy = NaN, // previous y direction + i = 0; + + do { + // determine marching squares index + i = 0; + if (grid(x-1, y-1)) i += 1; + if (grid(x, y-1)) i += 2; + if (grid(x-1, y )) i += 4; + if (grid(x, y )) i += 8; + + // determine next direction + if (i === 6) { + dx = pdy === -1 ? -1 : 1; + dy = 0; + } else if (i === 9) { + dx = 0; + dy = pdx === 1 ? -1 : 1; + } else { + dx = d3_geom_contourDx[i]; + dy = d3_geom_contourDy[i]; + } + + // update contour polygon + if (dx != pdx && dy != pdy) { + c.push([x, y]); + pdx = dx; + pdy = dy; + } + + x += dx; + y += dy; + } while (s[0] != x || s[1] != y); + + return c; +}; + +// lookup tables for marching directions +var d3_geom_contourDx = [1, 0, 1, 1,-1, 0,-1, 1,0, 0,0,0,-1, 0,-1,NaN], + d3_geom_contourDy = [0,-1, 0, 0, 0,-1, 0, 0,1,-1,1,1, 0,-1, 0,NaN]; + +function d3_geom_contourStart(grid) { + var x = 0, + y = 0; + + // search for a starting point; begin at origin + // and proceed along outward-expanding diagonals + while (true) { + if (grid(x,y)) { + return [x,y]; + } + if (x === 0) { + x = y + 1; + y = 0; + } else { + x = x - 1; + y = y + 1; + } + } +} +/** + * Computes the 2D convex hull of a set of points using Graham's scanning + * algorithm. The algorithm has been implemented as described in Cormen, + * Leiserson, and Rivest's Introduction to Algorithms. The running time of + * this algorithm is O(n log n), where n is the number of input points. + * + * @param vertices [[x1, y1], [x2, y2], …] + * @returns polygon [[x1, y1], [x2, y2], …] + */ +d3.geom.hull = function(vertices) { + if (vertices.length < 3) return []; + + var len = vertices.length, + plen = len - 1, + points = [], + stack = [], + i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; + + // find the starting ref point: leftmost point with the minimum y coord + for (i=1; i<len; ++i) { + if (vertices[i][1] < vertices[h][1]) { + h = i; + } else if (vertices[i][1] == vertices[h][1]) { + h = (vertices[i][0] < vertices[h][0] ? i : h); + } + } + + // calculate polar angles from ref point and sort + for (i=0; i<len; ++i) { + if (i === h) continue; + y1 = vertices[i][1] - vertices[h][1]; + x1 = vertices[i][0] - vertices[h][0]; + points.push({angle: Math.atan2(y1, x1), index: i}); + } + points.sort(function(a, b) { return a.angle - b.angle; }); + + // toss out duplicate angles + a = points[0].angle; + v = points[0].index; + u = 0; + for (i=1; i<plen; ++i) { + j = points[i].index; + if (a == points[i].angle) { + // keep angle for point most distant from the reference + x1 = vertices[v][0] - vertices[h][0]; + y1 = vertices[v][1] - vertices[h][1]; + x2 = vertices[j][0] - vertices[h][0]; + y2 = vertices[j][1] - vertices[h][1]; + if ((x1*x1 + y1*y1) >= (x2*x2 + y2*y2)) { + points[i].index = -1; + } else { + points[u].index = -1; + a = points[i].angle; + u = i; + v = j; + } + } else { + a = points[i].angle; + u = i; + v = j; + } + } + + // initialize the stack + stack.push(h); + for (i=0, j=0; i<2; ++j) { + if (points[j].index !== -1) { + stack.push(points[j].index); + i++; + } + } + sp = stack.length; + + // do graham's scan + for (; j<plen; ++j) { + if (points[j].index === -1) continue; // skip tossed out points + while (!d3_geom_hullCCW(stack[sp-2], stack[sp-1], points[j].index, vertices)) { + --sp; + } + stack[sp++] = points[j].index; + } + + // construct the hull + var poly = []; + for (i=0; i<sp; ++i) { + poly.push(vertices[stack[i]]); + } + return poly; +} + +// are three points in counter-clockwise order? +function d3_geom_hullCCW(i1, i2, i3, v) { + var t, a, b, c, d, e, f; + t = v[i1]; a = t[0]; b = t[1]; + t = v[i2]; c = t[0]; d = t[1]; + t = v[i3]; e = t[0]; f = t[1]; + return ((f-b)*(c-a) - (d-b)*(e-a)) > 0; +} +// Note: requires coordinates to be counterclockwise and convex! +d3.geom.polygon = function(coordinates) { + + coordinates.area = function() { + var i = 0, + n = coordinates.length, + a = coordinates[n - 1][0] * coordinates[0][1], + b = coordinates[n - 1][1] * coordinates[0][0]; + while (++i < n) { + a += coordinates[i - 1][0] * coordinates[i][1]; + b += coordinates[i - 1][1] * coordinates[i][0]; + } + return (b - a) * .5; + }; + + coordinates.centroid = function(k) { + var i = -1, + n = coordinates.length - 1, + x = 0, + y = 0, + a, + b, + c; + if (!arguments.length) k = -1 / (6 * coordinates.area()); + while (++i < n) { + a = coordinates[i]; + b = coordinates[i + 1]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [x * k, y * k]; + }; + + // The Sutherland-Hodgman clipping algorithm. + coordinates.clip = function(subject) { + var input, + i = -1, + n = coordinates.length, + j, + m, + a = coordinates[n - 1], + b, + c, + d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = coordinates[i]; + c = input[(m = input.length) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + a = b; + } + return subject; + }; + + return coordinates; +}; + +function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); +} + +// Intersect two infinite lines cd and ab. +function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0], + y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1], + x13 = x1 - x3, + x21 = x2 - x1, + x43 = x4 - x3, + y13 = y1 - y3, + y21 = y2 - y1, + y43 = y4 - y3, + ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21); + return [x1 + ua * x21, y1 + ua * y21]; +} +// Adapted from Nicolas Garcia Belmonte's JIT implementation: +// http://blog.thejit.org/2010/02/12/voronoi-tessellation/ +// http://blog.thejit.org/assets/voronoijs/voronoi.js +// See lib/jit/LICENSE for details. + +// Notes: +// +// This implementation does not clip the returned polygons, so if you want to +// clip them to a particular shape you will need to do that either in SVG or by +// post-processing with d3.geom.polygon's clip method. +// +// If any vertices are coincident or have NaN positions, the behavior of this +// method is undefined. Most likely invalid polygons will be returned. You +// should filter invalid points, and consolidate coincident points, before +// computing the tessellation. + +/** + * @param vertices [[x1, y1], [x2, y2], …] + * @returns polygons [[[x1, y1], [x2, y2], …], …] + */ +d3.geom.voronoi = function(vertices) { + var polygons = vertices.map(function() { return []; }); + + d3_voronoi_tessellate(vertices, function(e) { + var s1, + s2, + x1, + x2, + y1, + y2; + if (e.a === 1 && e.b >= 0) { + s1 = e.ep.r; + s2 = e.ep.l; + } else { + s1 = e.ep.l; + s2 = e.ep.r; + } + if (e.a === 1) { + y1 = s1 ? s1.y : -1e6; + x1 = e.c - e.b * y1; + y2 = s2 ? s2.y : 1e6; + x2 = e.c - e.b * y2; + } else { + x1 = s1 ? s1.x : -1e6; + y1 = e.c - e.a * x1; + x2 = s2 ? s2.x : 1e6; + y2 = e.c - e.a * x2; + } + var v1 = [x1, y1], + v2 = [x2, y2]; + polygons[e.region.l.index].push(v1, v2); + polygons[e.region.r.index].push(v1, v2); + }); + + // Reconnect the polygon segments into counterclockwise loops. + return polygons.map(function(polygon, i) { + var cx = vertices[i][0], + cy = vertices[i][1]; + polygon.forEach(function(v) { + v.angle = Math.atan2(v[0] - cx, v[1] - cy); + }); + return polygon.sort(function(a, b) { + return a.angle - b.angle; + }).filter(function(d, i) { + return !i || (d.angle - polygon[i - 1].angle > 1e-10); + }); + }); +}; + +var d3_voronoi_opposite = {"l": "r", "r": "l"}; + +function d3_voronoi_tessellate(vertices, callback) { + + var Sites = { + list: vertices + .map(function(v, i) { + return { + index: i, + x: v[0], + y: v[1] + }; + }) + .sort(function(a, b) { + return a.y < b.y ? -1 + : a.y > b.y ? 1 + : a.x < b.x ? -1 + : a.x > b.x ? 1 + : 0; + }), + bottomSite: null + }; + + var EdgeList = { + list: [], + leftEnd: null, + rightEnd: null, + + init: function() { + EdgeList.leftEnd = EdgeList.createHalfEdge(null, "l"); + EdgeList.rightEnd = EdgeList.createHalfEdge(null, "l"); + EdgeList.leftEnd.r = EdgeList.rightEnd; + EdgeList.rightEnd.l = EdgeList.leftEnd; + EdgeList.list.unshift(EdgeList.leftEnd, EdgeList.rightEnd); + }, + + createHalfEdge: function(edge, side) { + return { + edge: edge, + side: side, + vertex: null, + "l": null, + "r": null + }; + }, + + insert: function(lb, he) { + he.l = lb; + he.r = lb.r; + lb.r.l = he; + lb.r = he; + }, + + leftBound: function(p) { + var he = EdgeList.leftEnd; + do { + he = he.r; + } while (he != EdgeList.rightEnd && Geom.rightOf(he, p)); + he = he.l; + return he; + }, + + del: function(he) { + he.l.r = he.r; + he.r.l = he.l; + he.edge = null; + }, + + right: function(he) { + return he.r; + }, + + left: function(he) { + return he.l; + }, + + leftRegion: function(he) { + return he.edge == null + ? Sites.bottomSite + : he.edge.region[he.side]; + }, + + rightRegion: function(he) { + return he.edge == null + ? Sites.bottomSite + : he.edge.region[d3_voronoi_opposite[he.side]]; + } + }; + + var Geom = { + + bisect: function(s1, s2) { + var newEdge = { + region: {"l": s1, "r": s2}, + ep: {"l": null, "r": null} + }; + + var dx = s2.x - s1.x, + dy = s2.y - s1.y, + adx = dx > 0 ? dx : -dx, + ady = dy > 0 ? dy : -dy; + + newEdge.c = s1.x * dx + s1.y * dy + + (dx * dx + dy * dy) * .5; + + if (adx > ady) { + newEdge.a = 1; + newEdge.b = dy / dx; + newEdge.c /= dx; + } else { + newEdge.b = 1; + newEdge.a = dx / dy; + newEdge.c /= dy; + } + + return newEdge; + }, + + intersect: function(el1, el2) { + var e1 = el1.edge, + e2 = el2.edge; + if (!e1 || !e2 || (e1.region.r == e2.region.r)) { + return null; + } + var d = (e1.a * e2.b) - (e1.b * e2.a); + if (Math.abs(d) < 1e-10) { + return null; + } + var xint = (e1.c * e2.b - e2.c * e1.b) / d, + yint = (e2.c * e1.a - e1.c * e2.a) / d, + e1r = e1.region.r, + e2r = e2.region.r, + el, + e; + if ((e1r.y < e2r.y) || + (e1r.y == e2r.y && e1r.x < e2r.x)) { + el = el1; + e = e1; + } else { + el = el2; + e = e2; + } + var rightOfSite = (xint >= e.region.r.x); + if ((rightOfSite && (el.side === "l")) || + (!rightOfSite && (el.side === "r"))) { + return null; + } + return { + x: xint, + y: yint + }; + }, + + rightOf: function(he, p) { + var e = he.edge, + topsite = e.region.r, + rightOfSite = (p.x > topsite.x); + + if (rightOfSite && (he.side === "l")) { + return 1; + } + if (!rightOfSite && (he.side === "r")) { + return 0; + } + if (e.a === 1) { + var dyp = p.y - topsite.y, + dxp = p.x - topsite.x, + fast = 0, + above = 0; + + if ((!rightOfSite && (e.b < 0)) || + (rightOfSite && (e.b >= 0))) { + above = fast = (dyp >= e.b * dxp); + } else { + above = ((p.x + p.y * e.b) > e.c); + if (e.b < 0) { + above = !above; + } + if (!above) { + fast = 1; + } + } + if (!fast) { + var dxs = topsite.x - e.region.l.x; + above = (e.b * (dxp * dxp - dyp * dyp)) < + (dxs * dyp * (1 + 2 * dxp / dxs + e.b * e.b)); + + if (e.b < 0) { + above = !above; + } + } + } else /* e.b == 1 */ { + var yl = e.c - e.a * p.x, + t1 = p.y - yl, + t2 = p.x - topsite.x, + t3 = yl - topsite.y; + + above = (t1 * t1) > (t2 * t2 + t3 * t3); + } + return he.side === "l" ? above : !above; + }, + + endPoint: function(edge, side, site) { + edge.ep[side] = site; + if (!edge.ep[d3_voronoi_opposite[side]]) return; + callback(edge); + }, + + distance: function(s, t) { + var dx = s.x - t.x, + dy = s.y - t.y; + return Math.sqrt(dx * dx + dy * dy); + } + }; + + var EventQueue = { + list: [], + + insert: function(he, site, offset) { + he.vertex = site; + he.ystar = site.y + offset; + for (var i=0, list=EventQueue.list, l=list.length; i<l; i++) { + var next = list[i]; + if (he.ystar > next.ystar || + (he.ystar == next.ystar && + site.x > next.vertex.x)) { + continue; + } else { + break; + } + } + list.splice(i, 0, he); + }, + + del: function(he) { + for (var i=0, ls=EventQueue.list, l=ls.length; i<l && (ls[i] != he); ++i) {} + ls.splice(i, 1); + }, + + empty: function() { return EventQueue.list.length === 0; }, + + nextEvent: function(he) { + for (var i=0, ls=EventQueue.list, l=ls.length; i<l; ++i) { + if (ls[i] == he) return ls[i+1]; + } + return null; + }, + + min: function() { + var elem = EventQueue.list[0]; + return { + x: elem.vertex.x, + y: elem.ystar + }; + }, + + extractMin: function() { + return EventQueue.list.shift(); + } + }; + + EdgeList.init(); + Sites.bottomSite = Sites.list.shift(); + + var newSite = Sites.list.shift(), newIntStar; + var lbnd, rbnd, llbnd, rrbnd, bisector; + var bot, top, temp, p, v; + var e, pm; + + while (true) { + if (!EventQueue.empty()) { + newIntStar = EventQueue.min(); + } + if (newSite && (EventQueue.empty() + || newSite.y < newIntStar.y + || (newSite.y == newIntStar.y + && newSite.x < newIntStar.x))) { //new site is smallest + lbnd = EdgeList.leftBound(newSite); + rbnd = EdgeList.right(lbnd); + bot = EdgeList.rightRegion(lbnd); + e = Geom.bisect(bot, newSite); + bisector = EdgeList.createHalfEdge(e, "l"); + EdgeList.insert(lbnd, bisector); + p = Geom.intersect(lbnd, bisector); + if (p) { + EventQueue.del(lbnd); + EventQueue.insert(lbnd, p, Geom.distance(p, newSite)); + } + lbnd = bisector; + bisector = EdgeList.createHalfEdge(e, "r"); + EdgeList.insert(lbnd, bisector); + p = Geom.intersect(bisector, rbnd); + if (p) { + EventQueue.insert(bisector, p, Geom.distance(p, newSite)); + } + newSite = Sites.list.shift(); + } else if (!EventQueue.empty()) { //intersection is smallest + lbnd = EventQueue.extractMin(); + llbnd = EdgeList.left(lbnd); + rbnd = EdgeList.right(lbnd); + rrbnd = EdgeList.right(rbnd); + bot = EdgeList.leftRegion(lbnd); + top = EdgeList.rightRegion(rbnd); + v = lbnd.vertex; + Geom.endPoint(lbnd.edge, lbnd.side, v); + Geom.endPoint(rbnd.edge, rbnd.side, v); + EdgeList.del(lbnd); + EventQueue.del(rbnd); + EdgeList.del(rbnd); + pm = "l"; + if (bot.y > top.y) { + temp = bot; + bot = top; + top = temp; + pm = "r"; + } + e = Geom.bisect(bot, top); + bisector = EdgeList.createHalfEdge(e, pm); + EdgeList.insert(llbnd, bisector); + Geom.endPoint(e, d3_voronoi_opposite[pm], v); + p = Geom.intersect(llbnd, bisector); + if (p) { + EventQueue.del(llbnd); + EventQueue.insert(llbnd, p, Geom.distance(p, bot)); + } + p = Geom.intersect(bisector, rrbnd); + if (p) { + EventQueue.insert(bisector, p, Geom.distance(p, bot)); + } + } else { + break; + } + }//end while + + for (lbnd = EdgeList.right(EdgeList.leftEnd); + lbnd != EdgeList.rightEnd; + lbnd = EdgeList.right(lbnd)) { + callback(lbnd.edge); + } +} +/** +* @param vertices [[x1, y1], [x2, y2], …] +* @returns triangles [[[x1, y1], [x2, y2], [x3, y3]], …] + */ +d3.geom.delaunay = function(vertices) { + var edges = vertices.map(function() { return []; }), + triangles = []; + + // Use the Voronoi tessellation to determine Delaunay edges. + d3_voronoi_tessellate(vertices, function(e) { + edges[e.region.l.index].push(vertices[e.region.r.index]); + }); + + // Reconnect the edges into counterclockwise triangles. + edges.forEach(function(edge, i) { + var v = vertices[i], + cx = v[0], + cy = v[1]; + edge.forEach(function(v) { + v.angle = Math.atan2(v[0] - cx, v[1] - cy); + }); + edge.sort(function(a, b) { + return a.angle - b.angle; + }); + for (var j = 0, m = edge.length - 1; j < m; j++) { + triangles.push([v, edge[j], edge[j + 1]]); + } + }); + + return triangles; +}; +// Constructs a new quadtree for the specified array of points. A quadtree is a +// two-dimensional recursive spatial subdivision. This implementation uses +// square partitions, dividing each square into four equally-sized squares. Each +// point exists in a unique node; if multiple points are in the same position, +// some points may be stored on internal nodes rather than leaf nodes. Quadtrees +// can be used to accelerate various spatial operations, such as the Barnes-Hut +// approximation for computing n-body forces, or collision detection. +d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var p, + i = -1, + n = points.length; + + // Type conversion for deprecated API. + if (n && isNaN(points[0].x)) points = points.map(d3_geom_quadtreePoint); + + // Allow bounds to be specified explicitly. + if (arguments.length < 5) { + if (arguments.length === 3) { + y2 = x2 = y1; + y1 = x1; + } else { + x1 = y1 = Infinity; + x2 = y2 = -Infinity; + + // Compute bounds. + while (++i < n) { + p = points[i]; + if (p.x < x1) x1 = p.x; + if (p.y < y1) y1 = p.y; + if (p.x > x2) x2 = p.x; + if (p.y > y2) y2 = p.y; + } + + // Squarify the bounds. + var dx = x2 - x1, + dy = y2 - y1; + if (dx > dy) y2 = y1 + dx; + else x2 = x1 + dy; + } + } + + // Recursively inserts the specified point p at the node n or one of its + // descendants. The bounds are defined by [x1, x2] and [y1, y2]. + function insert(n, p, x1, y1, x2, y2) { + if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid points + if (n.leaf) { + var v = n.point; + if (v) { + // If the point at this leaf node is at the same position as the new + // point we are adding, we leave the point associated with the + // internal node while adding the new point to a child node. This + // avoids infinite recursion. + if ((Math.abs(v.x - p.x) + Math.abs(v.y - p.y)) < .01) { + insertChild(n, p, x1, y1, x2, y2); + } else { + n.point = null; + insertChild(n, v, x1, y1, x2, y2); + insertChild(n, p, x1, y1, x2, y2); + } + } else { + n.point = p; + } + } else { + insertChild(n, p, x1, y1, x2, y2); + } + } + + // Recursively inserts the specified point p into a descendant of node n. The + // bounds are defined by [x1, x2] and [y1, y2]. + function insertChild(n, p, x1, y1, x2, y2) { + // Compute the split point, and the quadrant in which to insert p. + var sx = (x1 + x2) * .5, + sy = (y1 + y2) * .5, + right = p.x >= sx, + bottom = p.y >= sy, + i = (bottom << 1) + right; + + // Recursively insert into the child node. + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + + // Update the bounds as we recurse. + if (right) x1 = sx; else x2 = sx; + if (bottom) y1 = sy; else y2 = sy; + insert(n, p, x1, y1, x2, y2); + } + + // Create the root node. + var root = d3_geom_quadtreeNode(); + + root.add = function(p) { + insert(root, p, x1, y1, x2, y2); + }; + + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1, y1, x2, y2); + }; + + // Insert all points. + points.forEach(root.add); + return root; +}; + +function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null + }; +} + +function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, + sy = (y1 + y2) * .5, + children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x