.gitignore
| 3
modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java
| 4
modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java
| 4
modules/common/drift/src/main/java/org/rhq/common/drift/FileEntry.java
| 19
modules/common/drift/src/main/java/org/rhq/common/drift/Headers.java
| 28
modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java
| 16
modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java
| 16
modules/common/jboss-as/pom.xml
| 4
modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
| 51
modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java
| 11
modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataParser.java
| 2
modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
| 10
modules/core/client-api/src/main/resources/rhq-configuration.xsd
| 11
modules/core/client-api/src/main/resources/rhq-plugin.xsd
| 12
modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java
| 16
modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
| 2
modules/core/domain/pom.xml
| 11
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetCriteria.java
| 4
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftConfigurationCriteria.java
| 87
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftDefinitionCriteria.java
| 85
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java
| 10
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java
| 20
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java
| 6
modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java
| 6
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSet.java
| 44
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftComposite.java
| 2
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
| 421 ---
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java
| 140 -
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java
| 38
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
| 467 ++++
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinitionComparator.java
| 140 +
modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java
| 6
modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java
| 36
modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
| 4
modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
| 22
modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java
| 16
modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
| 29
modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java
| 50
modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftSnapshotTest.java
| 4
modules/core/domain/src/test/java/org/rhq/core/domain/resource/ResourceTypeTest.java
| 2
modules/core/native-system/pom.xml
| 58
modules/core/plugin-api/pom.xml
| 41
modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java
| 20
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManager.java
| 20
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManagerImpl.java
| 33
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java
| 8
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionSchedule.java
| 22
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
| 137 -
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java
| 6
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
| 320 +-
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
| 73
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
| 77
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
| 47
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSynchronizer.java
| 46
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/RuntimeSynchronizer.java
| 64
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/StartupSynchronizer.java
| 62
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryFile.java
| 23
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
| 84
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
| 22
modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginClassLoader.java
| 32
modules/core/plugin-container/src/main/java/org/rhq/core/pc/standaloneContainer/History.java
| 23
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java
| 4
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
| 6
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
| 382 ++-
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java
| 4
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
| 87
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
| 42
modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/PluginDocGenerator.java
| 14
modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/VelocityTemplateProcessor.java
| 14
modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
| 24
modules/core/util/src/main/java/org/rhq/core/util/ZipUtil.java
| 33
modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java
| 10
modules/core/util/src/main/java/org/rhq/core/util/jdbc/JDBCUtil.java
| 15
modules/core/util/src/main/java/org/rhq/core/util/maven/MavenArtifactProperties.java
| 6
modules/enterprise/agentupdate/src/main/java/org/rhq/enterprise/agent/update/AgentUpdate.java
| 25
modules/enterprise/binding/pom.xml
| 51
modules/enterprise/binding/src/main/java/org/rhq/bindings/client/ResourceClientProxy.java
| 8
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
| 60
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java
| 10
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java
| 2
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/Carousel.java
| 1135 ++++++++++
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselMember.java
| 35
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselWidget.java
| 28
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
| 93
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeDataSource.java
| 8
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
| 60
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselMemberView.java
| 189 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
| 201 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationDataSource.java
| 289 --
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationEditView.java
| 194 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationView.java
| 243 --
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java
| 25
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionDataSource.java
| 313 ++
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionEditView.java
| 192 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionsView.java
| 259 ++
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java
| 2
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java
| 7
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeDataSource.java
| 6
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java
| 20
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftConfigurationView.java
| 40
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftDefinitionsView.java
| 40
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddConfigWizard.java
| 93
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddDefinitionWizard.java
| 93
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizard.java
| 159 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardConfigStep.java
| 76
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardInfoStep.java
| 125 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizard.java
| 160 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardConfigStep.java
| 76
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardInfoStep.java
| 125 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
| 44
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java
| 8
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java
| 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
| 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java
| 12
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestDataSourceResponseStatisticsView.java
| 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestRemoteServiceStatisticsView.java
| 6
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java
| 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java
| 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
| 46
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
| 2
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties
| 11
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
| 11
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties
| 11
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties
| 11
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties
| 11
modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
| 15
modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
| 97
modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
| 108
modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java
| 38
modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/util/ContextUtils.java
| 6
modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/ClientMain.java
| 2
modules/enterprise/remoting/client-api/pom.xml
| 13
modules/enterprise/server/jar/pom.xml
| 17
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/engine/model/DriftCacheElement.java
| 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentManagerBean.java
| 29
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentSourceManagerBean.java
| 8
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/AgentManagerBean.java
| 34
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java
| 54
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java
| 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
| 156 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
| 39
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
| 8
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
| 32
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
| 65
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java
| 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
| 188 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java
| 6
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
| 46
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataInserter.java
| 19
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataReader.java
| 84
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/ServerPluginsBean.java
| 22
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginClassLoader.java
| 36
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftChangeSetSummary.java
| 15
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
| 10
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/perspective/PerspectiveServerPluginManager.java
| 24
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
| 7
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java
| 4
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java
| 20
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java
| 8
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/EnhancedScheduler.java
| 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
| 25
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
| 181 -
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java
| 42
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java
| 20
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
| 15
modules/enterprise/server/plugins/alert-irc/pom.xml
| 3
modules/enterprise/server/plugins/alert-microblog/pom.xml
| 6
modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/PrintTokens.java
| 11
modules/enterprise/server/plugins/alert-scriptlang/pom.xml
| 4
modules/enterprise/server/plugins/alert-sms/pom.xml
| 4
modules/enterprise/server/plugins/alert-snmp/pom.xml
| 2
modules/enterprise/server/plugins/alert-snmp/src/main/java/org/rhq/enterprise/server/plugins/alertSnmp/SnmpTrapSender.java
| 54
modules/enterprise/server/plugins/ant-bundle/pom.xml
| 4
modules/enterprise/server/plugins/cloud/pom.xml
| 4
modules/enterprise/server/plugins/cobbler/pom.xml
| 2
modules/enterprise/server/plugins/drift-mongodb/pom.xml
| 3
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
| 8
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
| 4
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
| 2
modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
| 12
modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
| 4
modules/enterprise/server/plugins/filetemplate-bundle/pom.xml
| 4
modules/enterprise/server/plugins/groovy-script/pom.xml
| 1
modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/RHNHelper.java
| 8
modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/certificate/PublicKeyRing.java
| 18
modules/enterprise/server/plugins/yum/src/main/java/org/rhq/enterprise/server/plugins/yum/Repo.java
| 8
modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
| 39
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
| 1
modules/integration-tests/apache-plugin-test/src/test/java/org/rhq/plugins/apache/util/ApacheDeploymentUtil.java
| 43
modules/integration-tests/jboss-as-7-plugin-test/pom.xml
| 2
modules/jopr/dist/server/pom.xml
| 4
modules/jopr/tools/jbas5-plugin-descriptor-gen/src/main/java/org/jboss/jopr/tool/jbas5/PluginDescriptorGenerator.java
| 17
modules/plugins/JBossOSGi/pom.xml
| 2
modules/plugins/ant-bundle/pom.xml
| 2
modules/plugins/apache/pom.xml
| 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKComponent.java
| 78
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
| 33
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
| 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
| 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
| 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
| 6
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
| 14
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
| 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
| 4
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
| 7
modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/AugeasNodeBuffer.java
| 2
modules/plugins/augeas/src/main/java/org/rhq/rhqtransform/impl/ConfigurationToAugeasSimple.java
| 10
modules/plugins/byteman/pom.xml
| 2
modules/plugins/cobbler/pom.xml
| 3
modules/plugins/filetemplate-bundle/pom.xml
| 2
modules/plugins/hibernate/pom.xml
| 4
modules/plugins/irc/pom.xml
| 3
modules/plugins/jboss-as-5/pom.xml
| 1
modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerContentFacetDelegate.java
| 1
modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
| 14
modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/deploy/ManagedComponentDeployer.java
| 14
modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JnpConfig.java
| 24
modules/plugins/jboss-as-5/testsuite/pom.xml
| 3
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
| 13
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
| 11
modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/FileContentDelegate.java
| 14
modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JnpConfig.java
| 24
modules/plugins/jboss-cache-v3/pom.xml
| 2
modules/plugins/jboss-cache-v3/src/test/java/org/rhq/plugins/jbosscache3/test/TestHelper.java
| 2
modules/plugins/jdbctrace/pom.xml
| 2
modules/plugins/jira/pom.xml
| 6
modules/plugins/jmx/pom.xml
| 4
modules/plugins/lsof/pom.xml
| 2
modules/plugins/mysql/pom.xml
| 4
modules/plugins/netservices/pom.xml
| 6
modules/plugins/onewire/pom.xml
| 2
modules/plugins/oracle/pom.xml
| 4
modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
| 19
modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/event/PerfTestEventPoller.java
| 2
modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/measurement/SimpleNumericMeasurementFactory.java
| 16
modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/trait/SimpleTraitFactory.java
| 20
modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
| 174 -
modules/plugins/perftest/src/main/resources/configurable-1.xml
| 4
modules/plugins/perftest/src/main/resources/configurable-5.xml
| 12
modules/plugins/postgres/pom.xml
| 4
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseComponent.java
| 19
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseDiscoveryComponent.java
| 2
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresServerComponent.java
| 25
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableComponent.java
| 38
modules/plugins/raw-config-test/pom.xml
| 2
modules/plugins/rhq-server/pom.xml
| 5
modules/plugins/script2/pom.xml
| 2
modules/plugins/script2/src/main/java/org/rhq/modules/plugins/script2/ScriptComponent.java
| 31
modules/plugins/snmptrapd/pom.xml
| 3
modules/plugins/tomcat/src/main/java/org/jboss/on/plugins/tomcat/helper/FileContentDelegate.java
| 2
modules/plugins/twitter/pom.xml
| 2
modules/plugins/virt/pom.xml
| 2
pom.xml
| 100
253 files changed, 6819 insertions(+), 4132 deletions(-)
New commits:
commit 1ea2ef9b1e18e9f34981ba9a909f02cd329f55c4
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Sep 30 18:09:03 2011 -0400
more merge clean up
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index eb05284..af01526 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@ -19,14 +19,6 @@
package org.rhq.core.pc.drift;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
-import static org.rhq.core.util.file.FileUtil.copyFile;
-import static org.rhq.core.util.file.FileUtil.forEachFile;
-
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
@@ -47,6 +39,14 @@ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.file.FileVisitor;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.common.drift.FileEntry.removedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+import static org.rhq.core.util.file.FileUtil.copyFile;
+import static org.rhq.core.util.file.FileUtil.forEachFile;
+
public class DriftDetector implements Runnable {
private Log log = LogFactory.getLog(DriftDetector.class);
@@ -268,7 +268,7 @@ public class DriftDetector implements Runnable {
Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), DRIFT);
+ schedule.getDriftDefinition().getName(), DRIFT);
ChangeSetWriter deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet,
deltaHeaders);
summary.setDriftChangeSet(driftChangeSet);
@@ -318,7 +318,7 @@ public class DriftDetector implements Runnable {
}));
}
writer.close();
- if (schedule.getDriftConfiguration().isPinned()) {
+ if (schedule.getDriftDefinition().isPinned()) {
copyFile(snapshot, new File(snapshot.getParentFile(),
"snapshot.pinned"));
}
summary.setNewSnapshot(snapshot);
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
index 49ac579..72f605c 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
@@ -59,6 +59,7 @@ import org.rhq.core.pc.agent.AgentService;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.measurement.MeasurementManager;
+import org.rhq.core.util.file.FileUtil;
import org.rhq.core.util.stream.StreamUtil;
import static org.rhq.common.drift.FileEntry.addedFileEntry;
@@ -208,7 +209,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
log.info("Detected deleted drift definition,
DriftDefinition[name: " + driftDef.getName()
+ ", resourceId: " + resourceId + "]");
log.info("Deleting drift definition directory " +
defDir.getPath());
- purge(defDir, true);
+ FileUtil.purge(defDir, true);
}
}
}
@@ -233,14 +234,6 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
- private String toString(Resource r, DriftDefinition c) {
- return toString(r.getId(), c);
- }
-
- private String toString(int resourceId, DriftDefinition c) {
- return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ resourceId + ", name: " + c.getName() + "]";
- }
-
private Headers createHeaders(Resource resource, DriftDefinition driftDefinition) {
Headers headers = new Headers();
headers.setResourceId(resource.getId());
@@ -463,7 +456,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
public void run() {
File resourceDir = new File(changeSetsDir,
Integer.toString(resourceId));
File changeSetDir = new File(resourceDir, driftDefinition.getName());
- purge(changeSetDir, true);
+ FileUtil.purge(changeSetDir, true);
log.debug("Removed change set directory " +
changeSetDir.getAbsolutePath());
}
@@ -536,7 +529,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
try {
// Replace the current snapshot and then create/copy it to the
pinned
// snapshot file
- writeSnapshotToFile(createHeaders(resourceId,
schedule.getDriftDefintion()), snapshot);
+ writeSnapshotToFile(createHeaders(resourceId,
schedule.getDriftDefinition()), snapshot);
schedulesQueue.addSchedule(schedule);
copyFile(snapshotFile, new File(snapshotFile.getParentFile(),
"snapshot.pinned"));
} catch (IOException e) {
@@ -553,7 +546,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
defName + "]");
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, driftDefName);
+ File changeSetDir = new File(resourceDir, defName);
if (!changeSetDir.exists()) {
log.warn("Cannot complete acknowledgement. Change set directory " +
changeSetDir.getPath()
@@ -561,7 +554,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
return;
}
- File snapshot = changeSetMgr.findChangeSet(resourceId, driftDefName, COVERAGE);
+ File snapshot = changeSetMgr.findChangeSet(resourceId, defName, COVERAGE);
File previousSnapshot = new File(snapshot.getParentFile(), snapshot.getName() +
".previous");
previousSnapshot.delete();
@@ -707,15 +700,15 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
return toString(r.getId(), d);
}
- private String toString(int resourceId, DriftDefintion d) {
- return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ resourceId + ", name: " + d.getName() + "]";
+ private String toString(int resourceId, DriftDefinition d) {
+ return "DriftDefinition[id: " + d.getId() + ", resourceId: "
+ resourceId + ", name: " + d.getName() + "]";
}
private String toString(int resourceId, String defName) {
return "[resourceId: " + resourceId + ", driftDefintionName:
" + defName + "]";
}
- private Headers createHeaders(int resourceId, DriftDefintion driftDef) {
+ private Headers createHeaders(int resourceId, DriftDefinition driftDef) {
Headers headers = new Headers();
headers.setResourceId(resourceId);
headers.setDriftDefinitionId(driftDef.getId());
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
index fd4afe4..05024d1 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
@@ -102,7 +102,7 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public boolean contains(int resourceId, DriftDefinition driftDef,
DriftConfigurationComparator comparator) {
+ public boolean contains(int resourceId, DriftDefinition driftDef,
DriftDefinitionComparator comparator) {
if (isActiveSchedule(resourceId, driftDef, comparator)) {
return true;
}
@@ -129,7 +129,6 @@ public class ScheduleQueueImpl implements ScheduleQueue {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
if (schedule.getResourceId() == resourceId
-<<<<<<< HEAD
&& schedule.getDriftDefinition().getName().equals(defName))
{
return schedule.copy();
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
index 60cf207..44ba315 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
@@ -19,20 +19,6 @@
package org.rhq.core.pc.drift;
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.apache.commons.io.FileUtils.touch;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
-import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
-import static org.rhq.test.AssertUtils.assertPropertiesMatch;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@@ -52,6 +38,20 @@ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.system.OperatingSystemType;
import org.rhq.core.system.SystemInfoFactory;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.apache.commons.io.FileUtils.touch;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.common.drift.FileEntry.removedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
+import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
public class DriftDetectorTest extends DriftTest {
ScheduleQueue scheduleQueue;
@@ -641,10 +641,10 @@ public class DriftDetectorTest extends DriftTest {
@Test
public void doNotModifyPinnedSnapshotWhenDriftIsDetected() throws Exception {
- DriftConfiguration config =
driftConfiguration("do-not-modify-pinned-snapshot",
resourceDir.getAbsolutePath());
- config.setPinned(true);
- config.setPinnedVersion(0);
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+ DriftDefinition driftDef =
driftDefinition("do-not-modify-pinned-snapshot",
resourceDir.getAbsolutePath());
+ driftDef.setPinned(true);
+ driftDef.setPinnedVersion(0);
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
driftDef);
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server1.conf");
@@ -654,7 +654,7 @@ public class DriftDetectorTest extends DriftTest {
// When the initial snapshot is pinned, we need to generate it; otherwise, it
should
// be provided by the server.
- File currentSnapshot = changeSet(config.getName(), COVERAGE);
+ File currentSnapshot = changeSet(driftDef.getName(), COVERAGE);
File pinnedSnapshot = new File(currentSnapshot.getParentFile(),
"snapshot.pinned");
String originalPinnedHash = sha256(pinnedSnapshot);
@@ -674,21 +674,21 @@ public class DriftDetectorTest extends DriftTest {
addedFileEntry("conf/server1.conf", sha256(server1Conf)),
addedFileEntry("conf/server2.conf", sha256(server2Conf)));
- assertHeaderEquals(currentSnapshot, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(currentSnapshot, createHeaders(driftDef, COVERAGE, 1));
assertFileEntriesMatch("The current snapshot file should still get updated
even when using a pinned snapshot",
fileEntries, currentSnapshot);
}
@Test
public void updateCurrentSnapshotVersionNumberWhenUsingPinnedSnapshot() throws
Exception {
- DriftConfiguration config =
driftConfiguration("update-snapshot-version-pinned",
resourceDir.getAbsolutePath());
- config.setPinned(true);
- config.setPinnedVersion(0);
+ DriftDefinition driftDef =
driftDefinition("update-snapshot-version-pinned",
resourceDir.getAbsolutePath());
+ driftDef.setPinned(true);
+ driftDef.setPinnedVersion(0);
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server1.conf");
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
driftDef);
scheduleQueue.addSchedule(schedule);
detector.run();
@@ -697,7 +697,7 @@ public class DriftDetectorTest extends DriftTest {
schedule.resetSchedule();
detector.run();
- File currentSnapshot = changeSet(config.getName(), COVERAGE);
+ File currentSnapshot = changeSet(driftDef.getName(), COVERAGE);
File previousSnapshot = new File(currentSnapshot.getParentFile(),
"changeset.txt.previous");
previousSnapshot.delete();
@@ -712,17 +712,17 @@ public class DriftDetectorTest extends DriftTest {
addedFileEntry("conf/server2.conf", sha256(server2Conf)),
addedFileEntry("conf/server3.conf", sha256(server3Conf)));
- assertHeaderEquals(currentSnapshot, createHeaders(config, COVERAGE, 2));
+ assertHeaderEquals(currentSnapshot, createHeaders(driftDef, COVERAGE, 2));
assertFileEntriesMatch("The current snapshot file should still get updated
even when using a pinned snapshot",
currentSnapshotEntries, currentSnapshot);
// verify that the the drift/deleta change set was generated
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(driftDef.getName(), DRIFT);
List<FileEntry> driftEntries = asList(
addedFileEntry("conf/server2.conf", sha256(server2Conf)),
addedFileEntry("conf/server3.conf", sha256(server3Conf)));
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 2));
+ assertHeaderEquals(driftChangeSet, createHeaders(driftDef, DRIFT, 2));
assertFileEntriesMatch("The drift change set was not generated correctly
when using a pinned snapshot",
driftEntries, driftChangeSet);
@@ -730,22 +730,22 @@ public class DriftDetectorTest extends DriftTest {
@Test
public void generatePinnedSnapshotFileWhenInitialVersionIsPinned() throws Exception
{
- DriftConfiguration config =
driftConfiguration("initial-snapshot-pinned-test",
resourceDir.getAbsolutePath());
- config.setPinned(true);
- config.setPinnedVersion(0);
+ DriftDefinition driftDef =
driftDefinition("initial-snapshot-pinned-test", resourceDir.getAbsolutePath());
+ driftDef.setPinned(true);
+ driftDef.setPinnedVersion(0);
File confDir = mkdir(resourceDir, "conf");
File serverConf = createRandomFile(confDir, "server.conf");
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), driftDef));
detector.run();
- File changeSet = changeSet(config.getName(), COVERAGE);
+ File changeSet = changeSet(driftDef.getName(), COVERAGE);
File pinnedSnapshot = new File(changeSet.getParentFile(),
"snapshot.pinned");
List<FileEntry> entries =
asList(addedFileEntry("conf/server.conf", sha256(serverConf)));
assertTrue(changeSet.exists(), "An initial snapshot file should be generated
even when it is pinned");
- assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
+ assertHeaderEquals(changeSet, createHeaders(driftDef, COVERAGE));
assertFileEntriesMatch("Initial snapshot entries are wrong for pinned
snapshot", entries, changeSet);
assertTrue(pinnedSnapshot.exists(), "Pinned snapshot file should be
generated when initial version is pinned");
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
index 9a5832f..f1f1536 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
@@ -424,7 +424,7 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
PageList<? extends DriftChangeSet<?>> changeSets =
findDriftChangeSetsByCriteria(subject, criteria);
DriftChangeSet<?> changeSet = changeSets.get(0);
- DriftConfiguration config = entityManager.find(DriftConfiguration.class,
changeSet.getDriftConfigurationId());
+ DriftDefinition config = entityManager.find(DriftDefinition.class,
changeSet.getDriftDefinitionId());
config.setPinned(true);
config.setPinnedVersion(changeSet.getVersion());
@@ -432,7 +432,7 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
config = entityManager.merge(config);
GenericDriftChangeSetCriteria snapshotCriteria = new
GenericDriftChangeSetCriteria();
- snapshotCriteria.addFilterDriftConfigurationId(config.getId());
+ snapshotCriteria.addFilterDriftDefinitionId(config.getId());
snapshotCriteria.addFilterEndVersion(Integer.toString(changeSet.getVersion()));
DriftSnapshot snapshot = createSnapshot(subject, snapshotCriteria);
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
index 7b6283a..f8f6192 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
@@ -29,7 +29,6 @@ import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
-import org.rhq.core.domain.drift.DriftConfiguration;
import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.FileDiffReport;
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
index 9670199..29589a2 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
@@ -23,11 +23,11 @@ import javax.ejb.Remote;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
import org.rhq.core.domain.criteria.DriftCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.drift.FileDiffReport;
import org.rhq.core.domain.util.PageList;
@@ -35,10 +35,10 @@ import org.rhq.core.domain.util.PageList;
@Remote
public interface DriftManagerRemote {
- PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject
subject,
- DriftConfigurationCriteria criteria);
+ PageList<DriftDefinition> findDriftDefinitionsByCriteria(Subject subject,
+ DriftDefinitionCriteria criteria);
- void updateDriftConfiguration(Subject subject, EntityContext entityContext,
DriftConfiguration driftConfig);
+ void updateDriftDefinition(Subject subject, EntityContext entityContext,
DriftDefinition driftConfig);
DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) throws
Exception;
commit 3d63af180e2723425d753143727e4a16ae4ed5a8
Merge: c3a7a17 2537cbd
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Sep 30 17:00:38 2011 -0400
Merge branch 'master' into pinned-snapshot
Conflicts:
modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
diff --cc
modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
index 35128df,4a2d134..45012f3
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
@@@ -22,9 -22,8 +22,9 @@@ package org.rhq.core.clientapi.agent.dr
import java.util.List;
import org.rhq.common.drift.Headers;
- import org.rhq.core.domain.drift.DriftConfiguration;
+ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.DriftSnapshot;
/**
* The interface to agent's drift subsystem which allows the server to request
@@@ -126,13 -125,11 +126,13 @@@ public interface DriftAgentService
* persisted change set content that was previously sent to the server. The agent
* will proceed to purge the referenced content zip file.
*
- * @param resourceId The id of the resource to which the referenced drift
configuration
+ * @param resourceId The id of the resource to which the referenced drift
definition
* belongs.
- * @param driftConfigName The name of the drift configuration to which the content
- * @param driftDefName The name of the drift definition to which the content
++ * @param defName The name of the drift definition to which the content
* belongs.
* @param token A token that is used to identify the content zip file
*/
- void ackChangeSetContent(int resourceId, String driftConfigName, String token);
- void ackChangeSetContent(int resourceId, String driftDefName, String token);
++ void ackChangeSetContent(int resourceId, String defName, String token);
+
- void pinSnapshot(int resourceId, String configName, DriftSnapshot snapshot);
++ void pinSnapshot(int resourceId, String defName, DriftSnapshot snapshot);
}
diff --cc
modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
index 0000000,33bb483..033746f
mode 000000,100644..100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
@@@ -1,0 -1,421 +1,467 @@@
+ /*
+ * RHQ Management Platform
+ * Copyright (C) 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.core.domain.drift;
+
+ import static java.util.Collections.emptyList;
+
+ import java.io.Serializable;
+ import java.util.ArrayList;
+ import java.util.List;
+
+ import javax.persistence.CascadeType;
+ import javax.persistence.Column;
+ import javax.persistence.Entity;
+ import javax.persistence.EnumType;
+ import javax.persistence.Enumerated;
+ import javax.persistence.FetchType;
+ import javax.persistence.GeneratedValue;
+ import javax.persistence.GenerationType;
+ import javax.persistence.Id;
+ import javax.persistence.JoinColumn;
+ import javax.persistence.ManyToOne;
+ import javax.persistence.PrePersist;
+ import javax.persistence.SequenceGenerator;
+ import javax.persistence.Table;
+
+ import org.rhq.core.domain.configuration.Configuration;
+ import org.rhq.core.domain.configuration.Property;
+ import org.rhq.core.domain.configuration.PropertyList;
+ import org.rhq.core.domain.configuration.PropertyMap;
+ import org.rhq.core.domain.configuration.PropertySimple;
+ import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+ import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+ import org.rhq.core.domain.resource.Resource;
+
+ /**
+ * This is a convienence wrapper around a Configuration object whose schema is that
+ * of {@link DriftConfigurationDefinition}.
+ *
+ * Note that this is not an actual Configuration object - it's got a HAS-A
relationship
+ * with Configuration.
+ *
+ * This object also has an optional relationship with a Resource.
+ *
+ * @author John Sanda
+ * @author John Mazzitelli
+ * @author Jay Shaughnessy
+ */
+ @Entity
+ @Table(name = "RHQ_DRIFT_CONFIG")
+ @SequenceGenerator(name = "SEQ", sequenceName =
"RHQ_DRIFT_CONFIG_ID_SEQ")
+ public class DriftDefinition implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Column(name = "ID", nullable = false)
+ @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
+ @Id
+ private int id;
+
+ @Column(name = "CTIME", nullable = false)
+ private Long ctime = -1L;
+
+ @Column(name = "NAME", nullable = false)
+ private String name;
+
+ @Column(name = "IS_ENABLED", nullable = false)
+ private boolean isEnabled;
+
+ @Column(name = "DRIFT_HANDLING_MODE", nullable = false)
+ @Enumerated(EnumType.STRING)
+ private DriftHandlingMode driftHandlingMode;
+
+ // unit = millis
+ @Column(name = "INTERVAL", nullable = false)
+ private long interval;
+
+ @JoinColumn(name = "CONFIG_ID", referencedColumnName = "ID",
nullable = false)
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
+ private Configuration configuration;
+
+ @JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID",
nullable = true)
+ @ManyToOne(optional = true)
+ private Resource resource = null;
+
++ @Column(name = "PINNED", nullable = false)
++ private boolean pinned;
++
++ @Column(name = "PINNED_VERSION", nullable = true)
++ private Integer pinnedVersion;
++
+ // required for jaxb/web services stuff
+ protected DriftDefinition() {
+ }
+
+ public DriftDefinition(Configuration c) {
+ this.setConfiguration(c);
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public Long getCtime() {
+ return ctime;
+ }
+
+ @PrePersist
+ void onPersist() {
+ this.ctime = System.currentTimeMillis();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ if (null == name) {
+ throw new IllegalArgumentException("Drift congig name can not be
null");
+ }
+
+ this.name = name;
+ this.setNameProperty(name);
+ }
+
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ /**
+ * If null set to default
+ * @param isEnabled
+ */
+ public void setEnabled(Boolean isEnabled) {
+ if (isEnabled == null) {
+ isEnabled = DriftConfigurationDefinition.DEFAULT_ENABLED;
+ }
+
+ this.isEnabled = isEnabled;
+ this.setEnabledProperty(isEnabled);
+ }
+
+ public DriftHandlingMode getDriftHandlingMode() {
+ return driftHandlingMode;
+ }
+
+ public void setDriftHandlingMode(DriftHandlingMode driftHandlingMode) {
+ if (null == driftHandlingMode) {
+ driftHandlingMode =
DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE;
+ }
+
+ this.driftHandlingMode = driftHandlingMode;
+ this.setDriftHandlingModeProperty(driftHandlingMode);
+ }
+
+ public long getInterval() {
+ return interval;
+ }
+
+ /**
+ * If null, set to default.
+ * @param interval
+ */
+ public void setInterval(Long interval) {
+ if (interval == null) {
+ interval = DriftConfigurationDefinition.DEFAULT_INTERVAL;
+ }
+
+ this.interval = interval;
+ this.setIntervalProperty(interval);
+ }
+
++ public boolean isPinned() {
++ return pinned;
++ }
++
++ public void setPinned(boolean pinned) {
++ this.pinned = pinned;
++ setPinnedProperty(pinned);
++ }
++
++ public int getPinnedVersion() {
++ return pinnedVersion;
++ }
++
++ public void setPinnedVersion(Integer version) {
++ pinnedVersion = version;
++ setPinnedVersionProperty(version);
++ }
++
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(Configuration configuration) {
+ this.configuration = configuration;
- this.name = this.getNameProperty();
- this.isEnabled = this.getIsEnabledProperty();
- this.interval = this.getIntervalProperty();
- this.driftHandlingMode = this.getDriftHandlingModeProperty();
++ name = getNameProperty();
++ isEnabled = getIsEnabledProperty();
++ interval = getIntervalProperty();
++ driftHandlingMode = getDriftHandlingModeProperty();
++ pinned = getPinnedProperty();
++ pinnedVersion = getPinnedVersionProperty();
+ }
+
+ public Resource getResource() {
+ return resource;
+ }
+
+ public void setResource(Resource resource) {
+ this.resource = resource;
+ if (this.resource != null) {
+ this.resource.getDriftDefinitions().add(this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("DriftDefinition [id=").append(id).append(",
name=").append(name).append(", enabled=").append(
+ isEnabled).append(", interval=").append(interval).append(",
resource=").append(resource).append(
+ ", basedir=").append(getBasedir()).append(",
includes=").append(getIncludes()).append(", excludes=")
+ .append(getExcludes()).append("]");
+ return builder.toString();
+ }
+
+ public static class BaseDirectory implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private BaseDirValueContext context;
+ private String name;
+
+ // required for jaxb/web services remoting
+ protected BaseDirectory() {
+ }
+
+ public BaseDirectory(BaseDirValueContext context, String name) {
+ this.context = context;
+ this.name = name;
+ }
+
+ public BaseDirValueContext getValueContext() {
+ return context;
+ }
+
+ public String getValueName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("BaseDirectory
[context=").append(context).append(",
name=").append(name).append("]");
+ return builder.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 1;
+ result = 31 * result + ((context == null) ? 0 : context.hashCode());
+ result = 31 * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof BaseDirectory)) {
+ return false;
+ }
+ BaseDirectory other = (BaseDirectory) obj;
+ if (context == null) {
+ if (other.context != null) {
+ return false;
+ }
+ } else if (!context.equals(other.context)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+ }
+
+ private String getNameProperty() {
+ return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME,
null);
+ }
+
+ private void setNameProperty(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("name is null");
+ }
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_NAME,
name));
+ }
+
+ public BaseDirectory getBasedir() {
+ PropertyMap map =
configuration.getMap(DriftConfigurationDefinition.PROP_BASEDIR);
+ if (map == null) {
+ return null;
+ }
+
+ String valueContext =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, null);
+ String valueName =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, null);
+
+ BaseDirValueContext valueContextEnum;
+
+ if (valueContext == null) {
+ throw new NullPointerException("valueContext is null");
+ } else {
+ try {
+ valueContextEnum = BaseDirValueContext.valueOf(valueContext);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Invalid valueContext: " +
valueContext);
+ }
+ }
+
+ if (valueName == null) {
+ throw new NullPointerException("valueName is null");
+ }
+
+ return new BaseDirectory(valueContextEnum, valueName);
+ }
+
+ public void setBasedir(BaseDirectory basedir) {
+ if (basedir == null) {
+ throw new NullPointerException("basedir is null");
+ }
+ if (basedir.getValueContext() == null) {
+ throw new NullPointerException("valueContext is null");
+ }
+ if (basedir.getValueName() == null) {
+ throw new NullPointerException("valueName is null");
+ }
+
+ String valueContext = basedir.getValueContext().name();
+ String valueName = basedir.getValueName();
+
+ PropertyMap basedirMap = new
PropertyMap(DriftConfigurationDefinition.PROP_BASEDIR);
+ basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, valueContext));
+ basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, valueName));
+
+ configuration.put(basedirMap);
+ }
+
+ private Long getIntervalProperty() {
+ return
Long.parseLong(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_INTERVAL,
String
+ .valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL)));
+ }
+
+ private void setIntervalProperty(Long interval) {
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL,
interval.toString()));
+ }
+
++ private boolean getPinnedProperty() {
++ return
Boolean.valueOf(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_PINNED,
"false"));
++ }
++
++ private void setPinnedProperty(boolean pinned) {
++ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_PINNED,
pinned));
++ }
++
++ private Integer getPinnedVersionProperty() {
++ String value =
configuration.getSimpleValue(DriftConfigurationDefinition.PROP_PINNED_VERSION, null);
++ if (value == null) {
++ return null;
++ }
++ return Integer.valueOf(value);
++ }
++
++ private void setPinnedVersionProperty(Integer version) {
++ configuration.put(new
PropertySimple(DriftConfigurationDefinition.PROP_PINNED_VERSION, version));
++ }
++
+ private DriftHandlingMode getDriftHandlingModeProperty() {
+ return DriftHandlingMode.valueOf(configuration.getSimpleValue(
+ DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE,
+ DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE.name()));
+ }
+
+ private void setDriftHandlingModeProperty(DriftHandlingMode mode) {
+ configuration.put(new
PropertySimple(DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE, mode.name()));
+ }
+
+ private boolean getIsEnabledProperty() {
+ return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_ENABLED,
+
String.valueOf(DriftConfigurationDefinition.DEFAULT_ENABLED)).equals("true");
+ }
+
+ private void setEnabledProperty(boolean enabled) {
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_ENABLED,
String.valueOf(enabled)));
+ }
+
+ public List<Filter> getIncludes() {
+ return getFilters(DriftConfigurationDefinition.PROP_INCLUDES);
+ }
+
+ public List<Filter> getExcludes() {
+ return getFilters(DriftConfigurationDefinition.PROP_EXCLUDES);
+ }
+
+ public void addInclude(Filter filter) {
+ PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_INCLUDES);
+ if (filtersList == null) {
+ // this is going to be our first include filter - make sure we create an
initial list and put it in the config
+ filtersList = new PropertyList(DriftConfigurationDefinition.PROP_INCLUDES);
+ configuration.put(filtersList);
+ }
+
+ PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_INCLUDES_INCLUDE);
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
+ filtersList.add(filterMap);
+ }
+
+ public void addExclude(Filter filter) {
+ PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_EXCLUDES);
+ if (filtersList == null) {
+ // this is going to be our first include filter - make sure we create an
initial list and put it in the config
+ filtersList = new PropertyList(DriftConfigurationDefinition.PROP_EXCLUDES);
+ configuration.put(filtersList);
+ }
+
+ PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_EXCLUDES_EXCLUDE);
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
+ filtersList.add(filterMap);
+ }
+
+ private List<Filter> getFilters(String type) {
+ PropertyList filtersListProperty = configuration.getList(type);
+ if (filtersListProperty == null) {
+ return emptyList();
+ }
+
+ List<Filter> filters = new ArrayList<Filter>();
+ for (Property property : filtersListProperty.getList()) {
+ PropertyMap filter = (PropertyMap) property;
+ filters.add(new
Filter(filter.getSimpleValue(DriftConfigurationDefinition.PROP_PATH, ""),
filter
+ .getSimpleValue(DriftConfigurationDefinition.PROP_PATTERN,
"")));
+ }
+
+ return filters;
+ }
+ }
diff --cc
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index 072b83b,8f8c23d..eb05284
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@@ -156,29 -156,14 +156,29 @@@ public class DriftDetector implements R
log.debug("Generating drift change set for " + schedule);
+ File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), COVERAGE);
++ schedule.getDriftDefinition().getName(), COVERAGE);
+ File snapshotFile = currentSnapshot;
+
- if (schedule.getDriftConfiguration().isPinned()) {
++ if (schedule.getDriftDefinition().isPinned()) {
+ snapshotFile = new File(snapshotFile.getParentFile(),
"snapshot.pinned");
+
+ }
+
- final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftConfiguration()));
+ final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftDefinition()));
final Set<File> processedFiles = new HashSet<File>();
final List<FileEntry> snapshotEntries = new
LinkedList<FileEntry>();
final List<FileEntry> deltaEntries = new LinkedList<FileEntry>();
- int newVersion = coverageReader.getHeaders().getVersion() + 1;
+ final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(snapshotFile);
+
+ int newVersion;
- if (schedule.getDriftConfiguration().isPinned()) {
++ if (schedule.getDriftDefinition().isPinned()) {
+ ChangeSetReader snapshotReader =
changeSetMgr.getChangeSetReader(currentSnapshot);
+ newVersion = snapshotReader.getHeaders().getVersion() + 1;
+ snapshotReader.close();
+ } else {
+ newVersion = coverageReader.getHeaders().getVersion() + 1;
+ }
// First look for files that have either been modified or deleted
for (FileEntry entry : coverageReader) {
@@@ -256,9 -240,15 +255,9 @@@
copyFile(currentSnapshot, oldSnapshot);
currentSnapshot.delete();
- Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
-
- File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
- .getName(), DRIFT);
- ChangeSetWriter deltaWriter =
changeSetMgr.getChangeSetWriter(driftChangeSet, deltaHeaders);
-
- File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
- .getName(), COVERAGE);
+ File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), COVERAGE);
++ schedule.getDriftDefinition().getName(), COVERAGE);
ChangeSetWriter newSnapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(),
snapshotHeaders);
diff --cc
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
index b3f41474,74ed3d4..49ac579
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
@@@ -185,9 -184,24 +191,9 @@@ public class DriftManager extends Agent
headers.setVersion(snapshot.getVersion());
- log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for "
- + toString(resource, driftDefinition));
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resource.getId(),
headers);
-
- for (Drift<?, ?> drift : snapshot.getEntries()) {
- switch (drift.getCategory()) {
- case FILE_ADDED:
- writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
- break;
- case FILE_CHANGED:
- writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(), drift
- .getNewDriftFile().getHashId()));
- break;
- default: // FILE_REMOVED
- writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
- }
- }
- writer.close();
+ log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for " +
- toString(resource, configuration));
++ toString(resource, driftDefinition));
+ writeSnapshotToFile(headers, snapshot);
}
}
@@@ -495,48 -524,16 +516,48 @@@
}
@Override
- public void pinSnapshot(final int resourceId, final String configName, final
DriftSnapshot snapshot) {
- public void ackChangeSet(int resourceId, String driftDefName) {
- log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftDefinition:" + driftDefName
- + "]");
++ public void pinSnapshot(final int resourceId, final String defName, final
DriftSnapshot snapshot) {
+ if (log.isInfoEnabled()) {
- log.info("Pinning snapshot version " + snapshot.getVersion() +
" for " + toString(resourceId, configName));
++ log.info("Pinning snapshot version " + snapshot.getVersion() +
" for " + toString(resourceId, defName));
+ }
- final DriftDetectionSchedule schedule = schedulesQueue.find(resourceId,
configName);
++ final DriftDetectionSchedule schedule = schedulesQueue.find(resourceId,
defName);
+ if (schedule == null) {
+ return;
+ }
+
- schedule.getDriftConfiguration().setPinned(true);
- schedule.getDriftConfiguration().setPinnedVersion(snapshot.getVersion());
++ schedule.getDriftDefinition().setPinned(true);
++ schedule.getDriftDefinition().setPinnedVersion(snapshot.getVersion());
+
- schedulesQueue.removeAndExecute(resourceId, configName, new Runnable() {
++ schedulesQueue.removeAndExecute(resourceId, defName, new Runnable() {
+ @Override
+ public void run() {
- File snapshotFile = changeSetMgr.findChangeSet(resourceId, configName,
COVERAGE);
++ File snapshotFile = changeSetMgr.findChangeSet(resourceId, defName,
COVERAGE);
+ snapshotFile.delete();
+ try {
+ // Replace the current snapshot and then create/copy it to the
pinned
+ // snapshot file
- writeSnapshotToFile(createHeaders(resourceId,
schedule.getDriftConfiguration()), snapshot);
++ writeSnapshotToFile(createHeaders(resourceId,
schedule.getDriftDefintion()), snapshot);
+ schedulesQueue.addSchedule(schedule);
+ copyFile(snapshotFile, new File(snapshotFile.getParentFile(),
"snapshot.pinned"));
+ } catch (IOException e) {
+ log.error("An error occurred while writing the pinned snapshot
to disk. Drift detection will " +
+ "not be rescheduled for " + schedule);
+ }
+ }
+ });
+ }
+
+ @Override
- public void ackChangeSet(int resourceId, String driftConfigName) {
- log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftConfiguration:" +
- driftConfigName + "]");
++ public void ackChangeSet(int resourceId, String defName) {
++ log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftDefinition:" +
++ defName + "]");
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, driftConfigName);
+ File changeSetDir = new File(resourceDir, driftDefName);
if (!changeSetDir.exists()) {
- log.warn("Cannot complete acknowledgement. Change set directory "
+ changeSetDir.getPath() +
- " does not exist.");
+ log.warn("Cannot complete acknowledgement. Change set directory "
+ changeSetDir.getPath()
+ + " does not exist.");
return;
}
@@@ -664,46 -661,6 +685,46 @@@
return PluginContainer.getInstance().getMeasurementManager();
}
+ private void writeSnapshotToFile(Headers headers, DriftSnapshot snapshot) throws
IOException {
+ ChangeSetWriter writer =
changeSetMgr.getChangeSetWriter(headers.getResourceId(), headers);
+ for (Drift drift : snapshot.getEntries()) {
+ switch (drift.getCategory()) {
+ case FILE_ADDED:
+ writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
+ break;
+ case FILE_CHANGED:
+ writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(),
+ drift.getNewDriftFile().getHashId()));
+ break;
+ default: // FILE_REMOVED
+ writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
+ }
+ }
+ writer.close();
+ }
+
- private String toString(Resource r, DriftConfiguration c) {
- return toString(r.getId(), c);
++ private String toString(Resource r, DriftDefinition d) {
++ return toString(r.getId(), d);
+ }
+
- private String toString(int resourceId, DriftConfiguration c) {
- return "DriftConfiguration[id: " + c.getId() + ", resourceId:
" + resourceId + ", name: " + c.getName() + "]";
++ private String toString(int resourceId, DriftDefintion d) {
++ return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ resourceId + ", name: " + d.getName() + "]";
+ }
+
- private String toString(int resourceId, String configName) {
- return "[resourceId: " + resourceId + ", driftConfigurationName:
" + configName + "]";
++ private String toString(int resourceId, String defName) {
++ return "[resourceId: " + resourceId + ", driftDefintionName:
" + defName + "]";
+ }
+
- private Headers createHeaders(int resourceId, DriftConfiguration configuration) {
++ private Headers createHeaders(int resourceId, DriftDefintion driftDef) {
+ Headers headers = new Headers();
+ headers.setResourceId(resourceId);
- headers.setDriftCofigurationId(configuration.getId());
++ headers.setDriftDefinitionId(driftDef.getId());
+ headers.setType(COVERAGE);
- headers.setDriftConfigurationName(configuration.getName());
- headers.setBasedir(getAbsoluteBaseDirectory(resourceId,
configuration).getAbsolutePath());
++ headers.setDriftDefinitionName(driftDef.getName());
++ headers.setBasedir(getAbsoluteBaseDirectory(resourceId,
driftDef).getAbsolutePath());
+ return headers;
+ }
+
private static class ZipFileNameFilter implements FilenameFilter {
private String prefix;
diff --cc
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
index 17ce367,8d45b75..35960ad
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
@@@ -46,27 -46,17 +46,27 @@@ public interface ScheduleQueue
boolean addSchedule(DriftDetectionSchedule schedule);
/**
- * Searches the queue for a schedule with a matching resource id and drift
configuration
++ * Searches the queue for a schedule with a matching resource id and drift
definition
+ * name. If found, a copy of the schedule is returned.
+ *
+ * @param resourceId The resource id of the schedule being sought
- * @param configName The name of the drift configuration in the schedule being
sought
++ * @param defName The name of the drift definition in the schedule being sought
+ * @return A copy of the schedule or null if no match is found
+ */
- DriftDetectionSchedule find(int resourceId, String configName);
++ DriftDetectionSchedule find(int resourceId, String defName);
+
+ /**
- * Checks the queue for a schedule with specified resource id and drift
configuration
- * whose name matches the specified configuration.
+ * Checks the queue for a schedule with specified resource id and drift definition
+ * whose name matches the specified definition.
*
* @param resourceId The resource id of the schedule
- * @param config The drift configuration of the schedule
+ * @param driftDef The drift definition of the schedule
* @return true if the queue contains a schedule with the specified resource id and
a
- * drift configuration whose name matches the name of the specified configuration.
+ * drift definition whose name matches the name of the specified definition.
*/
- boolean contains(int resourceId, DriftConfiguration config);
+ boolean contains(int resourceId, DriftDefinition driftDef);
- boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator);
+ boolean contains(int resourceId, DriftDefinition driftDef, DriftDefinitionComparator
comparator);
/**
* This method attempts to update the schedule identified by the resource id the
and
@@@ -95,22 -85,10 +95,22 @@@
* @return The {@link DriftDetectionSchedule} that is removed or null if no
matching
* schedule is found.
*/
- DriftDetectionSchedule remove(int resourceId, DriftConfiguration config);
+ DriftDetectionSchedule remove(int resourceId, DriftDefinition driftDef);
/**
- * Removes the schedule identified by the resource id and drift configuration name.
++ * Removes the schedule identified by the resource id and drift definition name.
+ * This method will remove the currently active schedule or a schedule that is on
the
+ * queue.
+ *
+ * @param resourceId The resource id
- * @param configName The drift configuration name
++ * @param defName The drift definition name
+ * @return The {@link DriftDetectionSchedule} that is removed or null if no
matching
+ * schedule is found.
+ */
- DriftDetectionSchedule remove(int resourceId, String configName);
++ DriftDetectionSchedule remove(int resourceId, String defName);
+
+ /**
- * Removes the schedule identified by the resource id and the drift configuration
name.
+ * Removes the schedule identified by the resource id and the drift definition
name.
* This method can remove either the active schedule or a schedule on the queue.
When
* the schedule is in the queue, <code>task</code> is executed
immediately after the
* schedule is removed from the queue. If the schedule is active, then
<code>task</code>
@@@ -134,18 -112,9 +134,18 @@@
* @return The {@link DriftDetectionSchedule} that is removed or null if no
matching
* schedule is found.
*/
- DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration config,
Runnable task);
+ DriftDetectionSchedule removeAndExecute(int resourceId, DriftDefinition driftDef,
Runnable task);
/**
+ * Removes the schedule
+ * @param resourceId
+ * @param configName
+ * @param task
+ * @return
+ */
+ DriftDetectionSchedule removeAndExecute(int resourceId, String configName, Runnable
task);
+
+ /**
* Removes all elements from the queue and deactivates the active schedule.
*/
void clear();
diff --cc
modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
index 1677b40,13e20b6..fd4afe4
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
@@@ -41,15 -41,11 +41,15 @@@ public class ScheduleQueueImpl implemen
}
}
- private boolean isActiveSchedule(int resourceId, DriftConfiguration config) {
- return isActiveSchedule(resourceId, config.getName());
+ private boolean isActiveSchedule(int resourceId, DriftDefinition driftDef) {
++ return isActiveSchedule(resourceId, driftDef.getName());
+ }
+
- private boolean isActiveSchedule(int resourceId, String configName) {
++ private boolean isActiveSchedule(int resourceId, String defName) {
try {
lock.readLock().lock();
return activeSchedule != null && activeSchedule.getResourceId() ==
resourceId
- &&
activeSchedule.getDriftConfiguration().getName().equals(configName);
- &&
activeSchedule.getDriftDefinition().getName().equals(driftDef.getName());
++ &&
activeSchedule.getDriftDefinition().getName().equals(defName);
} finally {
lock.readLock().unlock();
}
@@@ -98,20 -93,15 +97,20 @@@
}
@Override
- public boolean contains(int resourceId, DriftConfiguration config) {
- return find(resourceId, config.getName()) != null;
+ public boolean contains(int resourceId, DriftDefinition driftDef) {
- if (isActiveSchedule(resourceId, driftDef)) {
++ return find(resourceId, driftDef.getName()) != null;
+ }
+
+ @Override
- public boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator) {
- if (isActiveSchedule(resourceId, config, comparator)) {
++ public boolean contains(int resourceId, DriftDefinition driftDef,
DriftConfigurationComparator comparator) {
++ if (isActiveSchedule(resourceId, driftDef, comparator)) {
return true;
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
- if (schedule.getResourceId() == resourceId
- &&
schedule.getDriftDefinition().getName().equals(driftDef.getName())) {
+ if (schedule.getResourceId() == resourceId &&
- comparator.compare(schedule.getDriftConfiguration(), config) == 0)
{
++ comparator.compare(schedule.getDriftDefinition(), driftDef) == 0) {
return true;
}
}
@@@ -122,44 -112,34 +121,45 @@@
}
@Override
- public DriftDetectionSchedule find(int resourceId, String configName) {
- if (isActiveSchedule(resourceId, configName)) {
- public boolean contains(int resourceId, DriftDefinition driftDef,
DriftDefinitionComparator comparator) {
- if (isActiveSchedule(resourceId, driftDef, comparator)) {
- return true;
++ public DriftDetectionSchedule find(int resourceId, String defName) {
++ if (isActiveSchedule(resourceId, defName)) {
+ return activeSchedule.copy();
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
if (schedule.getResourceId() == resourceId
- &&
schedule.getDriftConfiguration().getName().equals(configName)) {
- && comparator.compare(schedule.getDriftDefinition(),
driftDef) == 0) {
- return true;
++<<<<<<< HEAD
++ && schedule.getDriftDefinition().getName().equals(defName))
{
+ return schedule.copy();
}
}
- return false;
+ return null;
} finally {
lock.readLock().unlock();
}
}
@Override
- public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) {
- return remove(resourceId, config.getName());
+ public DriftDetectionSchedule remove(int resourceId, DriftDefinition driftDef) {
- return removeAndExecute(resourceId, driftDef, NO_OP);
++ return remove(resourceId, driftDef.getName());
+ }
+
+ @Override
- public DriftDetectionSchedule remove(int resourceId, String configName) {
- return removeAndExecute(resourceId, configName, NO_OP);
++ public DriftDetectionSchedule remove(int resourceId, String defName) {
++ return removeAndExecute(resourceId, defName, NO_OP);
}
@Override
- public DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration
config, Runnable task) {
- return removeAndExecute(resourceId, config.getName(), task);
+ public DriftDetectionSchedule removeAndExecute(int resourceId, DriftDefinition
driftDef, Runnable task) {
++ return removeAndExecute(resourceId, driftDef.getName(), task);
+ }
+
+ @Override
- public DriftDetectionSchedule removeAndExecute(int resourceId, String configName,
Runnable task) {
++ public DriftDetectionSchedule removeAndExecute(int resourceId, String defName,
Runnable task) {
try {
lock.writeLock().lock();
- if (isActiveSchedule(resourceId, configName)) {
- if (isActiveSchedule(resourceId, driftDef)) {
++ if (isActiveSchedule(resourceId, defName)) {
deactivationTask = task;
DriftDetectionSchedule removedSchedule = activeSchedule;
activeSchedule = null;
@@@ -170,7 -150,7 +170,7 @@@
while (iterator.hasNext()) {
DriftDetectionSchedule schedule = iterator.next();
if (schedule.getResourceId() == resourceId
- &&
schedule.getDriftConfiguration().getName().equals(configName)) {
- &&
schedule.getDriftDefinition().getName().equals(driftDef.getName())) {
++ && schedule.getDriftDefinition().getName().equals(defName))
{
iterator.remove();
task.run();
return schedule;
@@@ -203,12 -183,9 +203,12 @@@
}
}
- private void update(DriftDetectionSchedule schedule, DriftConfiguration config) {
- schedule.getDriftConfiguration().setEnabled(config.isEnabled());
- schedule.getDriftConfiguration().setInterval(config.getInterval());
-
schedule.getDriftConfiguration().setDriftHandlingMode(config.getDriftHandlingMode());
- schedule.getDriftConfiguration().setPinned(config.isPinned());
- schedule.getDriftConfiguration().setPinnedVersion(config.getPinnedVersion());
+ private void update(DriftDetectionSchedule schedule, DriftDefinition driftDef) {
+ schedule.getDriftDefinition().setEnabled(driftDef.isEnabled());
+ schedule.getDriftDefinition().setInterval(driftDef.getInterval());
++
schedule.getDriftDefinition().setDriftHandlingMode(driftDef.getDriftHandlingMode());
++ schedule.getDriftDefinition().setPinned(driftDef.isPinned());
++ schedule.getDriftDefinition().setPinnedVersion(driftDef.getPinnedVersion());
}
@Override
diff --cc
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
index d4c3703,194d0b0..7b6283a
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
@@@ -26,10 -26,9 +26,11 @@@ import javax.ejb.Local
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
- import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
+ import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.drift.Drift;
+import org.rhq.core.domain.drift.DriftChangeSet;
+import org.rhq.core.domain.drift.DriftConfiguration;
+ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.FileDiffReport;
import org.rhq.core.domain.util.PageList;
diff --cc
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
index 4bf7887,2544540..612967c
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
@@@ -45,12 -52,11 +52,12 @@@ import org.rhq.core.domain.criteria.Res
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftCategory;
import org.rhq.core.domain.drift.DriftChangeSet;
- import org.rhq.core.domain.drift.DriftConfiguration;
- import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
- import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftFileStatus;
+import org.rhq.core.domain.drift.DriftSnapshot;
+ import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+ import org.rhq.core.domain.drift.DriftDefinition.BaseDirectory;
import org.rhq.core.domain.resource.Agent;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
diff --cc
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
index c701f97,1515869..c1a9db6
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
@@@ -58,9 -58,8 +58,9 @@@ import org.rhq.core.domain.content.tran
import org.rhq.core.domain.discovery.AvailabilityReport;
import org.rhq.core.domain.discovery.MergeResourceResponse;
import org.rhq.core.domain.discovery.ResourceSyncInfo;
- import org.rhq.core.domain.drift.DriftConfiguration;
+ import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.MeasurementData;
import org.rhq.core.domain.measurement.MeasurementDataRequest;
commit c3a7a177041c710b6b789c23153db05f2a632a57
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Sep 30 16:24:25 2011 -0400
First, (very) rough cut of support for pinned snapshots
Some of this code, particylarly on the server may get changed
substantially or altogether go away. The key changes are primarily on
the agent side for supporting the notion of a pinned snapshot. The agent
checks to see if it is using a pinned snapshot. If so, it does not
update that snapshot file, and it will continue using the pinned
snapshot for comparison against the file system during drift detection.
There is also a new DriftAgentService method, pinSnapshot. The server
calls this to pin a snapshot for a particular drift definition. A
DriftSnapshot object is passed to the agent, and that object is written
to disk in the standard snapshot/changeset format.
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
index d58c766..35128df 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
@@ -24,6 +24,7 @@ import java.util.List;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftConfiguration;
import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.DriftSnapshot;
/**
* The interface to agent's drift subsystem which allows the server to request
@@ -132,4 +133,6 @@ public interface DriftAgentService {
* @param token A token that is used to identify the content zip file
*/
void ackChangeSetContent(int resourceId, String driftConfigName, String token);
+
+ void pinSnapshot(int resourceId, String configName, DriftSnapshot snapshot);
}
\ No newline at end of file
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
index 1ad1b18..06b1032 100644
--- a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
+++ b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
@@ -674,6 +674,8 @@
<column name="DRIFT_HANDLING_MODE" type="VARCHAR2"
size="20" required="true"/>
<column name="CONFIG_ID" type="INTEGER"
required="true" references="RHQ_CONFIG"/>
<column name="RESOURCE_ID" type="INTEGER"
required="false" references="RHQ_RESOURCE"/>
+ <column name="PINNED" type="BOOLEAN"
required="true"/>
+ <column name="PINNED_VERSION" type="INTEGER"
required="false"/>
</table>
<!-- A drift change-set report for a resource -->
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
index d7ac85a..a88758f 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
@@ -97,6 +97,12 @@ public class DriftConfiguration implements Serializable {
@ManyToOne(optional = true)
private Resource resource = null;
+ @Column(name = "PINNED", nullable = false)
+ private boolean pinned;
+
+ @Column(name = "PINNED_VERSION", nullable = true)
+ private Integer pinnedVersion;
+
// required for jaxb/web services stuff
protected DriftConfiguration() {
}
@@ -182,16 +188,36 @@ public class DriftConfiguration implements Serializable {
this.setIntervalProperty(interval);
}
+ public boolean isPinned() {
+ return pinned;
+ }
+
+ public void setPinned(boolean pinned) {
+ this.pinned = pinned;
+ setPinnedProperty(pinned);
+ }
+
+ public int getPinnedVersion() {
+ return pinnedVersion;
+ }
+
+ public void setPinnedVersion(Integer version) {
+ pinnedVersion = version;
+ setPinnedVersionProperty(version);
+ }
+
public Configuration getConfiguration() {
return configuration;
}
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
- this.name = this.getNameProperty();
- this.isEnabled = this.getIsEnabledProperty();
- this.interval = this.getIntervalProperty();
- this.driftHandlingMode = this.getDriftHandlingModeProperty();
+ name = getNameProperty();
+ isEnabled = getIsEnabledProperty();
+ interval = getIntervalProperty();
+ driftHandlingMode = getDriftHandlingModeProperty();
+ pinned = getPinnedProperty();
+ pinnedVersion = getPinnedVersionProperty();
}
public Resource getResource() {
@@ -348,6 +374,26 @@ public class DriftConfiguration implements Serializable {
configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL,
interval.toString()));
}
+ private boolean getPinnedProperty() {
+ return
Boolean.valueOf(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_PINNED,
"false"));
+ }
+
+ private void setPinnedProperty(boolean pinned) {
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_PINNED,
pinned));
+ }
+
+ private Integer getPinnedVersionProperty() {
+ String value =
configuration.getSimpleValue(DriftConfigurationDefinition.PROP_PINNED_VERSION, null);
+ if (value == null) {
+ return null;
+ }
+ return Integer.valueOf(value);
+ }
+
+ private void setPinnedVersionProperty(Integer version) {
+ configuration.put(new
PropertySimple(DriftConfigurationDefinition.PROP_PINNED_VERSION, version));
+ }
+
private DriftHandlingMode getDriftHandlingModeProperty() {
return DriftHandlingMode.valueOf(configuration.getSimpleValue(
DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE,
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java
index 561f055..5f27f84 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java
@@ -51,6 +51,8 @@ public class DriftConfigurationDefinition implements Serializable {
public static final String PROP_BASEDIR_VALUENAME = "valueName";
public static final String PROP_INTERVAL = "interval";
public static final String PROP_DRIFT_HANDLING_MODE = "driftHandlingMode";
+ public static final String PROP_PINNED = "pinned";
+ public static final String PROP_PINNED_VERSION = "pinnedVersion";
public static final String PROP_INCLUDES = "includes";
public static final String PROP_INCLUDES_INCLUDE = "include";
public static final String PROP_EXCLUDES = "excludes";
@@ -129,6 +131,8 @@ public class DriftConfigurationDefinition implements Serializable {
INSTANCE.put(createBasedir(INSTANCE, false));
INSTANCE.put(createIncludes(INSTANCE, false));
INSTANCE.put(createExcludes(INSTANCE, false));
+ INSTANCE.put(createPinned(INSTANCE));
+ INSTANCE.put(createPinnedVersion(INSTANCE));
INSTANCE_FOR_EXISTING_CONFIGS.setConfigurationFormat(ConfigurationFormat.STRUCTURED);
INSTANCE_FOR_EXISTING_CONFIGS.put(createName(INSTANCE_FOR_EXISTING_CONFIGS,
true));
@@ -138,6 +142,8 @@ public class DriftConfigurationDefinition implements Serializable {
INSTANCE_FOR_EXISTING_CONFIGS.put(createBasedir(INSTANCE_FOR_EXISTING_CONFIGS,
true));
INSTANCE_FOR_EXISTING_CONFIGS.put(createIncludes(INSTANCE_FOR_EXISTING_CONFIGS,
true));
INSTANCE_FOR_EXISTING_CONFIGS.put(createExcludes(INSTANCE_FOR_EXISTING_CONFIGS,
true));
+ INSTANCE_FOR_EXISTING_CONFIGS.put(createPinned(INSTANCE_FOR_EXISTING_CONFIGS));
+
INSTANCE_FOR_EXISTING_CONFIGS.put(createPinnedVersion(INSTANCE_FOR_EXISTING_CONFIGS));
}
private static PropertyDefinitionSimple createName(ConfigurationDefinition configDef,
boolean readOnly) {
@@ -215,6 +221,38 @@ public class DriftConfigurationDefinition implements Serializable {
return pd;
}
+ private static PropertyDefinitionSimple createPinned(ConfigurationDefinition
configDef) {
+ String name = PROP_PINNED;
+ String description = "If set, pins the snapshot that the agent uses for
comparing files during drift " +
+ "detection. Normally, the agent compares those files being monitored for
drift against the latest " +
+ "snapshot. If you pin a snapshot, the agent will use that pinned version
to compare against files " +
+ "being monitored for drift";
+ boolean required = true;
+ PropertySimpleType type = PropertySimpleType.BOOLEAN;
+
+ PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description,
required, type);
+ pd.setDisplayName("Pinned");
+ pd.setDefaultValue("false");
+ // TODO set order
+ pd.setConfigurationDefinition(configDef);
+
+ return pd;
+ }
+
+ private static PropertyDefinitionSimple createPinnedVersion(ConfigurationDefinition
configDef) {
+ String name = PROP_PINNED_VERSION;
+ String description = "Specifies the snapshot version to use as the pinned
snapshot.";
+ boolean required = false;
+ PropertySimpleType type = PropertySimpleType.INTEGER;
+
+ PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description,
required, type);
+ pd.setDisplayName("Pinned Snapshot");
+ // TODO set order
+ pd.setConfigurationDefinition(configDef);
+
+ return pd;
+ }
+
private static PropertyDefinitionSimple createInterval(ConfigurationDefinition
configDef) {
String name = PROP_INTERVAL;
String description = "The frequency in seconds in which drift detection
should run. Defaults to 1800 seconds (i.e. 30 minutes)";
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index 1aedea3..072b83b 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@ -156,14 +156,29 @@ public class DriftDetector implements Runnable {
log.debug("Generating drift change set for " + schedule);
- final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftConfiguration()));
File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftConfiguration().getName(), COVERAGE);
- final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(currentSnapshot);
+ File snapshotFile = currentSnapshot;
+
+ if (schedule.getDriftConfiguration().isPinned()) {
+ snapshotFile = new File(snapshotFile.getParentFile(),
"snapshot.pinned");
+
+ }
+
+ final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftConfiguration()));
final Set<File> processedFiles = new HashSet<File>();
final List<FileEntry> snapshotEntries = new LinkedList<FileEntry>();
final List<FileEntry> deltaEntries = new LinkedList<FileEntry>();
- int newVersion = coverageReader.getHeaders().getVersion() + 1;
+ final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(snapshotFile);
+
+ int newVersion;
+ if (schedule.getDriftConfiguration().isPinned()) {
+ ChangeSetReader snapshotReader =
changeSetMgr.getChangeSetReader(currentSnapshot);
+ newVersion = snapshotReader.getHeaders().getVersion() + 1;
+ snapshotReader.close();
+ } else {
+ newVersion = coverageReader.getHeaders().getVersion() + 1;
+ }
// First look for files that have either been modified or deleted
for (FileEntry entry : coverageReader) {
@@ -237,23 +252,26 @@ public class DriftDetector implements Runnable {
// If nothing has changed, there is no need to add/update any files
summary.setNewSnapshot(currentSnapshot);
} else {
- File oldSnapshot = new File(currentSnapshot.getParentFile(),
currentSnapshot.getName() +
- ".previous");
+ File oldSnapshot = new File(currentSnapshot.getParentFile(),
currentSnapshot.getName() + ".previous");
copyFile(currentSnapshot, oldSnapshot);
currentSnapshot.delete();
- Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
-
- File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), DRIFT);
- ChangeSetWriter deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet,
deltaHeaders);
-
File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftConfiguration().getName(), COVERAGE);
ChangeSetWriter newSnapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(),
snapshotHeaders);
+ for (FileEntry entry : snapshotEntries) {
+ newSnapshotWriter.write(entry);
+ }
+ newSnapshotWriter.close();
+ Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
+
+ File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
+ schedule.getDriftConfiguration().getName(), DRIFT);
+ ChangeSetWriter deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet,
deltaHeaders);
+
summary.setDriftChangeSet(driftChangeSet);
summary.setNewSnapshot(newSnapshot);
summary.setOldSnapshot(oldSnapshot);
@@ -262,11 +280,6 @@ public class DriftDetector implements Runnable {
deltaWriter.write(entry);
}
deltaWriter.close();
-
- for (FileEntry entry : snapshotEntries) {
- newSnapshotWriter.write(entry);
- }
- newSnapshotWriter.close();
}
}
@@ -306,6 +319,9 @@ public class DriftDetector implements Runnable {
}));
}
writer.close();
+ if (schedule.getDriftConfiguration().isPinned()) {
+ copyFile(snapshot, new File(snapshot.getParentFile(),
"snapshot.pinned"));
+ }
summary.setNewSnapshot(snapshot);
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
index 8fd065f..b3f41474 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
@@ -59,6 +59,7 @@ import static org.rhq.common.drift.FileEntry.addedFileEntry;
import static org.rhq.common.drift.FileEntry.changedFileEntry;
import static org.rhq.common.drift.FileEntry.removedFileEntry;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.util.file.FileUtil.copyFile;
import static org.rhq.core.util.file.FileUtil.purge;
public class DriftManager extends AgentService implements DriftAgentService, DriftClient,
ContainerService {
@@ -162,7 +163,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
private void syncWithServer(Resource resource, DriftConfiguration configuration)
throws IOException {
- Headers headers = createHeaders(resource, configuration);
+ Headers headers = createHeaders(resource.getId(), configuration);
if (!changeSetMgr.changeSetExists(resource.getId(), headers)) {
log.info("No snapshot found for " + toString(resource,
configuration) + ". Downloading snapshot from " +
"server");
@@ -186,22 +187,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for " +
toString(resource, configuration));
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resource.getId(),
headers);
-
- for (Drift drift : snapshot.getEntries()) {
- switch (drift.getCategory()) {
- case FILE_ADDED:
- writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
- break;
- case FILE_CHANGED:
- writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(),
- drift.getNewDriftFile().getHashId()));
- break;
- default: // FILE_REMOVED
- writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
- }
- }
- writer.close();
+ writeSnapshotToFile(headers, snapshot);
}
}
@@ -241,24 +227,6 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
- private String toString(Resource r, DriftConfiguration c) {
- return toString(r.getId(), c);
- }
-
- private String toString(int resourceId, DriftConfiguration c) {
- return "DriftConfiguration[id: " + c.getId() + ", resourceId:
" + resourceId + ", name: " + c.getName() + "]";
- }
-
- private Headers createHeaders(Resource resource, DriftConfiguration configuration) {
- Headers headers = new Headers();
- headers.setResourceId(resource.getId());
- headers.setDriftCofigurationId(configuration.getId());
- headers.setType(COVERAGE);
- headers.setDriftConfigurationName(configuration.getName());
- headers.setBasedir(getAbsoluteBaseDirectory(resource.getId(),
configuration).getAbsolutePath());
- return headers;
- }
-
/**
* This method is provided as a test hook.
*
@@ -527,6 +495,38 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
+ public void pinSnapshot(final int resourceId, final String configName, final
DriftSnapshot snapshot) {
+ if (log.isInfoEnabled()) {
+ log.info("Pinning snapshot version " + snapshot.getVersion() +
" for " + toString(resourceId, configName));
+ }
+ final DriftDetectionSchedule schedule = schedulesQueue.find(resourceId,
configName);
+ if (schedule == null) {
+ return;
+ }
+
+ schedule.getDriftConfiguration().setPinned(true);
+ schedule.getDriftConfiguration().setPinnedVersion(snapshot.getVersion());
+
+ schedulesQueue.removeAndExecute(resourceId, configName, new Runnable() {
+ @Override
+ public void run() {
+ File snapshotFile = changeSetMgr.findChangeSet(resourceId, configName,
COVERAGE);
+ snapshotFile.delete();
+ try {
+ // Replace the current snapshot and then create/copy it to the
pinned
+ // snapshot file
+ writeSnapshotToFile(createHeaders(resourceId,
schedule.getDriftConfiguration()), snapshot);
+ schedulesQueue.addSchedule(schedule);
+ copyFile(snapshotFile, new File(snapshotFile.getParentFile(),
"snapshot.pinned"));
+ } catch (IOException e) {
+ log.error("An error occurred while writing the pinned snapshot
to disk. Drift detection will " +
+ "not be rescheduled for " + schedule);
+ }
+ }
+ });
+ }
+
+ @Override
public void ackChangeSet(int resourceId, String driftConfigName) {
log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftConfiguration:" +
driftConfigName + "]");
@@ -664,6 +664,46 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
return PluginContainer.getInstance().getMeasurementManager();
}
+ private void writeSnapshotToFile(Headers headers, DriftSnapshot snapshot) throws
IOException {
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(headers.getResourceId(),
headers);
+ for (Drift drift : snapshot.getEntries()) {
+ switch (drift.getCategory()) {
+ case FILE_ADDED:
+ writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
+ break;
+ case FILE_CHANGED:
+ writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(),
+ drift.getNewDriftFile().getHashId()));
+ break;
+ default: // FILE_REMOVED
+ writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
+ }
+ }
+ writer.close();
+ }
+
+ private String toString(Resource r, DriftConfiguration c) {
+ return toString(r.getId(), c);
+ }
+
+ private String toString(int resourceId, DriftConfiguration c) {
+ return "DriftConfiguration[id: " + c.getId() + ", resourceId:
" + resourceId + ", name: " + c.getName() + "]";
+ }
+
+ private String toString(int resourceId, String configName) {
+ return "[resourceId: " + resourceId + ", driftConfigurationName:
" + configName + "]";
+ }
+
+ private Headers createHeaders(int resourceId, DriftConfiguration configuration) {
+ Headers headers = new Headers();
+ headers.setResourceId(resourceId);
+ headers.setDriftCofigurationId(configuration.getId());
+ headers.setType(COVERAGE);
+ headers.setDriftConfigurationName(configuration.getName());
+ headers.setBasedir(getAbsoluteBaseDirectory(resourceId,
configuration).getAbsolutePath());
+ return headers;
+ }
+
private static class ZipFileNameFilter implements FilenameFilter {
private String prefix;
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
index a453f74..17ce367 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
@@ -46,6 +46,16 @@ public interface ScheduleQueue {
boolean addSchedule(DriftDetectionSchedule schedule);
/**
+ * Searches the queue for a schedule with a matching resource id and drift
configuration
+ * name. If found, a copy of the schedule is returned.
+ *
+ * @param resourceId The resource id of the schedule being sought
+ * @param configName The name of the drift configuration in the schedule being
sought
+ * @return A copy of the schedule or null if no match is found
+ */
+ DriftDetectionSchedule find(int resourceId, String configName);
+
+ /**
* Checks the queue for a schedule with specified resource id and drift
configuration
* whose name matches the specified configuration.
*
@@ -88,6 +98,18 @@ public interface ScheduleQueue {
DriftDetectionSchedule remove(int resourceId, DriftConfiguration config);
/**
+ * Removes the schedule identified by the resource id and drift configuration name.
+ * This method will remove the currently active schedule or a schedule that is on
the
+ * queue.
+ *
+ * @param resourceId The resource id
+ * @param configName The drift configuration name
+ * @return The {@link DriftDetectionSchedule} that is removed or null if no matching
+ * schedule is found.
+ */
+ DriftDetectionSchedule remove(int resourceId, String configName);
+
+ /**
* Removes the schedule identified by the resource id and the drift configuration
name.
* This method can remove either the active schedule or a schedule on the queue.
When
* the schedule is in the queue, <code>task</code> is executed
immediately after the
@@ -115,6 +137,15 @@ public interface ScheduleQueue {
DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration config,
Runnable task);
/**
+ * Removes the schedule
+ * @param resourceId
+ * @param configName
+ * @param task
+ * @return
+ */
+ DriftDetectionSchedule removeAndExecute(int resourceId, String configName, Runnable
task);
+
+ /**
* Removes all elements from the queue and deactivates the active schedule.
*/
void clear();
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
index e5fa56e..1677b40 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
@@ -42,10 +42,14 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
private boolean isActiveSchedule(int resourceId, DriftConfiguration config) {
+ return isActiveSchedule(resourceId, config.getName());
+ }
+
+ private boolean isActiveSchedule(int resourceId, String configName) {
try {
lock.readLock().lock();
return activeSchedule != null && activeSchedule.getResourceId() ==
resourceId
- &&
activeSchedule.getDriftConfiguration().getName().equals(config.getName());
+ &&
activeSchedule.getDriftConfiguration().getName().equals(configName);
} finally {
lock.readLock().unlock();
}
@@ -95,14 +99,19 @@ public class ScheduleQueueImpl implements ScheduleQueue {
@Override
public boolean contains(int resourceId, DriftConfiguration config) {
- if (isActiveSchedule(resourceId, config)) {
+ return find(resourceId, config.getName()) != null;
+ }
+
+ @Override
+ public boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator) {
+ if (isActiveSchedule(resourceId, config, comparator)) {
return true;
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
if (schedule.getResourceId() == resourceId &&
- schedule.getDriftConfiguration().getName().equals(config.getName()))
{
+ comparator.compare(schedule.getDriftConfiguration(), config) == 0) {
return true;
}
}
@@ -113,19 +122,19 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator) {
- if (isActiveSchedule(resourceId, config, comparator)) {
- return true;
+ public DriftDetectionSchedule find(int resourceId, String configName) {
+ if (isActiveSchedule(resourceId, configName)) {
+ return activeSchedule.copy();
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
- if (schedule.getResourceId() == resourceId &&
- comparator.compare(schedule.getDriftConfiguration(), config) == 0) {
- return true;
+ if (schedule.getResourceId() == resourceId
+ &&
schedule.getDriftConfiguration().getName().equals(configName)) {
+ return schedule.copy();
}
}
- return false;
+ return null;
} finally {
lock.readLock().unlock();
}
@@ -133,14 +142,24 @@ public class ScheduleQueueImpl implements ScheduleQueue {
@Override
public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) {
- return removeAndExecute(resourceId, config, NO_OP);
+ return remove(resourceId, config.getName());
+ }
+
+ @Override
+ public DriftDetectionSchedule remove(int resourceId, String configName) {
+ return removeAndExecute(resourceId, configName, NO_OP);
}
@Override
public DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration
config, Runnable task) {
+ return removeAndExecute(resourceId, config.getName(), task);
+ }
+
+ @Override
+ public DriftDetectionSchedule removeAndExecute(int resourceId, String configName,
Runnable task) {
try {
lock.writeLock().lock();
- if (isActiveSchedule(resourceId, config)) {
+ if (isActiveSchedule(resourceId, configName)) {
deactivationTask = task;
DriftDetectionSchedule removedSchedule = activeSchedule;
activeSchedule = null;
@@ -151,7 +170,7 @@ public class ScheduleQueueImpl implements ScheduleQueue {
while (iterator.hasNext()) {
DriftDetectionSchedule schedule = iterator.next();
if (schedule.getResourceId() == resourceId
- &&
schedule.getDriftConfiguration().getName().equals(config.getName())) {
+ &&
schedule.getDriftConfiguration().getName().equals(configName)) {
iterator.remove();
task.run();
return schedule;
@@ -187,6 +206,9 @@ public class ScheduleQueueImpl implements ScheduleQueue {
private void update(DriftDetectionSchedule schedule, DriftConfiguration config) {
schedule.getDriftConfiguration().setEnabled(config.isEnabled());
schedule.getDriftConfiguration().setInterval(config.getInterval());
+
schedule.getDriftConfiguration().setDriftHandlingMode(config.getDriftHandlingMode());
+ schedule.getDriftConfiguration().setPinned(config.isPinned());
+ schedule.getDriftConfiguration().setPinnedVersion(config.getPinnedVersion());
}
@Override
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
index 4811044..60e9d22 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
@@ -562,7 +562,7 @@ public class DriftDetectorTest extends DriftTest {
detector.run();
File driftChangeSet = changeSet(config.getName(), DRIFT);
- List<FileEntry> driftEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash,
newServer1Hash));
+ List<FileEntry> driftEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash, newServer1Hash));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
@@ -571,7 +571,7 @@ public class DriftDetectorTest extends DriftTest {
// verify that the coverage change set was updated
File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> coverageEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash,
newServer1Hash));
+ List<FileEntry> coverageEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash, newServer1Hash));
assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
@@ -613,6 +613,120 @@ public class DriftDetectorTest extends DriftTest {
coverageChangeSet);
}
+ @Test
+ public void doNotModifyPinnedSnapshotWhenDriftIsDetected() throws Exception {
+ DriftConfiguration config =
driftConfiguration("do-not-modify-pinned-snapshot",
resourceDir.getAbsolutePath());
+ config.setPinned(true);
+ config.setPinnedVersion(0);
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server1.conf");
+
+ scheduleQueue.addSchedule(schedule);
+ detector.run();
+
+ // When the initial snapshot is pinned, we need to generate it; otherwise, it
should
+ // be provided by the server.
+ File currentSnapshot = changeSet(config.getName(), COVERAGE);
+ File pinnedSnapshot = new File(currentSnapshot.getParentFile(),
"snapshot.pinned");
+ String originalPinnedHash = sha256(pinnedSnapshot);
+
+ // generate some drift
+ File server2Conf = createRandomFile(confDir, "server2.conf");
+ schedule.resetSchedule();
+ detector.run();
+
+ String newPinnedHash = sha256(pinnedSnapshot);
+
+ assertEquals(newPinnedHash, originalPinnedHash, "When a snapshot is pinned,
it should not get updated during " +
+ "drift detection");
+
+ // We always generate/update the current snapshot so we still need to verify that
it
+ // was generated/updated correctly
+ List<FileEntry> fileEntries = asList(
+ addedFileEntry("conf/server1.conf", sha256(server1Conf)),
+ addedFileEntry("conf/server2.conf", sha256(server2Conf)));
+
+ assertHeaderEquals(currentSnapshot, createHeaders(config, COVERAGE, 1));
+ assertFileEntriesMatch("The current snapshot file should still get updated
even when using a pinned snapshot",
+ fileEntries, currentSnapshot);
+ }
+
+ @Test
+ public void updateCurrentSnapshotVersionNumberWhenUsingPinnedSnapshot() throws
Exception {
+ DriftConfiguration config =
driftConfiguration("update-snapshot-version-pinned",
resourceDir.getAbsolutePath());
+ config.setPinned(true);
+ config.setPinnedVersion(0);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server1.conf");
+
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+ scheduleQueue.addSchedule(schedule);
+ detector.run();
+
+ // create some drift which should result in version 1
+ File server2Conf = createRandomFile(confDir, "server2.conf");
+ schedule.resetSchedule();
+ detector.run();
+
+ File currentSnapshot = changeSet(config.getName(), COVERAGE);
+ File previousSnapshot = new File(currentSnapshot.getParentFile(),
"changeset.txt.previous");
+ previousSnapshot.delete();
+
+ // create some more drift which should result in version 2
+ File server3Conf = createRandomFile(confDir, "server3.conf");
+ schedule.resetSchedule();
+ detector.run();
+
+ // verify that the current snapshot was updated
+ List<FileEntry> currentSnapshotEntries = asList(
+ addedFileEntry("conf/server1.conf", sha256(server1Conf)),
+ addedFileEntry("conf/server2.conf", sha256(server2Conf)),
+ addedFileEntry("conf/server3.conf", sha256(server3Conf)));
+
+ assertHeaderEquals(currentSnapshot, createHeaders(config, COVERAGE, 2));
+ assertFileEntriesMatch("The current snapshot file should still get updated
even when using a pinned snapshot",
+ currentSnapshotEntries, currentSnapshot);
+
+ // verify that the the drift/deleta change set was generated
+ File driftChangeSet = changeSet(config.getName(), DRIFT);
+ List<FileEntry> driftEntries = asList(
+ addedFileEntry("conf/server2.conf", sha256(server2Conf)),
+ addedFileEntry("conf/server3.conf", sha256(server3Conf)));
+
+ assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 2));
+ assertFileEntriesMatch("The drift change set was not generated correctly
when using a pinned snapshot",
+ driftEntries, driftChangeSet);
+
+ }
+
+ @Test
+ public void generatePinnedSnapshotFileWhenInitialVersionIsPinned() throws Exception
{
+ DriftConfiguration config =
driftConfiguration("initial-snapshot-pinned-test",
resourceDir.getAbsolutePath());
+ config.setPinned(true);
+ config.setPinnedVersion(0);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File serverConf = createRandomFile(confDir, "server.conf");
+
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ detector.run();
+
+ File changeSet = changeSet(config.getName(), COVERAGE);
+ File pinnedSnapshot = new File(changeSet.getParentFile(),
"snapshot.pinned");
+ List<FileEntry> entries =
asList(addedFileEntry("conf/server.conf", sha256(serverConf)));
+
+ assertTrue(changeSet.exists(), "An initial snapshot file should be generated
even when it is pinned");
+ assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
+ assertFileEntriesMatch("Initial snapshot entries are wrong for pinned
snapshot", entries, changeSet);
+
+ assertTrue(pinnedSnapshot.exists(), "Pinned snapshot file should be
generated when initial version is pinned");
+ assertEquals(sha256(changeSet), sha256(pinnedSnapshot), "The contents of the
pinned snapshot file and the " +
+ "initial snapshot should be identical");
+ }
+
void assertHeaderEquals(File changeSet, Headers expected) throws Exception {
ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new
FileReader(changeSet)));
Headers actual = reader.getHeaders();
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
index fb63830..e14b84b 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
@@ -24,6 +24,7 @@ package org.rhq.enterprise.gui.coregui.client.drift;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
+import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.types.SortDirection;
@@ -50,6 +51,8 @@ import org.rhq.enterprise.gui.coregui.client.ImageManager;
import org.rhq.enterprise.gui.coregui.client.ViewId;
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.message.Message;
import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid;
/**
@@ -309,6 +312,29 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
idItem.setEnabled(false);
contextMenu.addItem(idItem);
+ MenuItem pinSnapshotItem = new MenuItem("Pin Snapshot");
+ pinSnapshotItem.setEnabled(true);
+ contextMenu.addItem(pinSnapshotItem);
+ pinSnapshotItem.addClickHandler(new ClickHandler() {
+ @Override
+ public void onClick(MenuItemClickEvent menuItemClickEvent) {
+ String changeSetId = node.getChangeSetId();
+ GWTServiceLookup.getDriftService().pinSnapshot(changeSetId, new
AsyncCallback<Void>() {
+ @Override
+ public void onFailure(Throwable caught) {
+ CoreGUI.getErrorHandler().handleError("Failed to pin change
set: " + caught.getMessage(),
+ caught);
+ }
+
+ @Override
+ public void onSuccess(Void result) {
+ CoreGUI.getMessageCenter().notify(new Message("Sent request
to agent to pin snapshot",
+ Message.Severity.Info));
+ }
+ });
+ }
+ });
+
return contextMenu;
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
index d4faced..73aeb61 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
@@ -118,4 +118,6 @@ public interface DriftGWTService extends RemoteService {
DriftDetails getDriftDetails(String driftId) throws RuntimeException;
+ void pinSnapshot(String changeSetId) throws RuntimeException;
+
}
\ No newline at end of file
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
index 55f9f7e..048a7f5 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
@@ -178,4 +178,13 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
throw getExceptionToThrowToClient(t);
}
}
+
+ @Override
+ public void pinSnapshot(String changeSetId) throws RuntimeException {
+ try {
+ driftManager.pinSnapshot(getSessionSubject(), changeSetId);
+ } catch (Throwable t) {
+ throw getExceptionToThrowToClient(t);
+ }
+ }
}
\ No newline at end of file
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
index aafd0bb..126c5cb 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
@@ -417,6 +417,35 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
+ public void pinSnapshot(Subject subject, String changeSetId) {
+ DriftServerPluginFacet driftServerPlugin = getServerPlugin();
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterId(changeSetId);
+ PageList<? extends DriftChangeSet<?>> changeSets =
findDriftChangeSetsByCriteria(subject, criteria);
+ DriftChangeSet<?> changeSet = changeSets.get(0);
+
+ DriftConfiguration config = entityManager.find(DriftConfiguration.class,
changeSet.getDriftConfigurationId());
+ config.setPinned(true);
+ config.setPinnedVersion(changeSet.getVersion());
+
+ // TODO is this merge call needed? - jsanda
+ config = entityManager.merge(config);
+
+ GenericDriftChangeSetCriteria snapshotCriteria = new
GenericDriftChangeSetCriteria();
+ snapshotCriteria.addFilterDriftConfigurationId(config.getId());
+ snapshotCriteria.addFilterEndVersion(Integer.toString(changeSet.getVersion()));
+ DriftSnapshot snapshot = createSnapshot(subject, snapshotCriteria);
+
+ entityManager.flush();
+ entityManager.clear();
+
+ AgentClient agent = agentManager.getAgentClient(subjectManager.getOverlord(),
changeSet.getResourceId());
+ DriftAgentService driftService = agent.getDriftAgentService();
+ driftService.pinSnapshot(changeSet.getResourceId(), config.getName(), snapshot);
+ }
+
+ @Override
@TransactionAttribute(NOT_SUPPORTED)
public String getDriftFileBits(String hash) {
log.debug("Retrieving drift file content for " + hash);
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
index c11482e..d4c3703 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
@@ -28,6 +28,7 @@ import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
import org.rhq.core.domain.drift.Drift;
+import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftConfiguration;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.FileDiffReport;
@@ -146,4 +147,6 @@ public interface DriftManagerLocal extends DriftServerPluginFacet,
DriftManagerR
DriftDetails getDriftDetails(Subject subject, String driftId);
boolean isBinaryFile(Drift<?, ?> drift);
+
+ void pinSnapshot(Subject subject, String changeSetId);
}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
index 8bb4590..9670199 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java
@@ -21,10 +21,13 @@ package org.rhq.enterprise.server.drift;
import javax.ejb.Remote;
import org.rhq.core.domain.auth.Subject;
+import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
+import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
import org.rhq.core.domain.criteria.DriftCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
+import org.rhq.core.domain.drift.DriftConfiguration;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.drift.FileDiffReport;
import org.rhq.core.domain.util.PageList;
@@ -32,6 +35,11 @@ import org.rhq.core.domain.util.PageList;
@Remote
public interface DriftManagerRemote {
+ PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject
subject,
+ DriftConfigurationCriteria criteria);
+
+ void updateDriftConfiguration(Subject subject, EntityContext entityContext,
DriftConfiguration driftConfig);
+
DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) throws
Exception;
/**
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
index ab84ce5..4bf7887 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
@@ -50,6 +50,7 @@ import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftFileStatus;
+import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.resource.Agent;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
@@ -455,5 +456,9 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
@Override
public void ackChangeSetContent(int resourceId, String driftConfigName, String
token) {
}
+
+ @Override
+ public void pinSnapshot(int resourceId, String configName, DriftSnapshot
snapshot) {
+ }
}
}
\ No newline at end of file
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
index 43d0ded..c701f97 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
@@ -60,6 +60,7 @@ import org.rhq.core.domain.discovery.MergeResourceResponse;
import org.rhq.core.domain.discovery.ResourceSyncInfo;
import org.rhq.core.domain.drift.DriftConfiguration;
import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.MeasurementData;
import org.rhq.core.domain.measurement.MeasurementDataRequest;
@@ -358,4 +359,8 @@ public class TestAgentClient implements AgentClient,
BundleAgentService, DriftAg
@Override
public void ackChangeSetContent(int resourceId, String driftConfigName, String token)
{
}
+
+ @Override
+ public void pinSnapshot(int resourceId, String configName, DriftSnapshot snapshot) {
+ }
}
commit 2537cbdd8fe54e73764f58d4329c67bec1b0eaa6
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Sep 30 10:37:38 2011 -0400
Protect certain tests from the fact that windows flavors don't support
File.setReadable(). Tests were failing on win.
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
index 50f2899..665233b 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
@@ -49,6 +49,8 @@ import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.system.OperatingSystemType;
+import org.rhq.core.system.SystemInfoFactory;
public class DriftDetectorTest extends DriftTest {
@@ -58,6 +60,8 @@ public class DriftDetectorTest extends DriftTest {
DriftDetector detector;
+ boolean isWindows = (SystemInfoFactory.createSystemInfo().getOperatingSystemType() ==
OperatingSystemType.WINDOWS);
+
@BeforeMethod
public void initDetector() {
driftClient = new DriftClientTestStub();
@@ -517,12 +521,21 @@ public class DriftDetectorTest extends DriftTest {
@Test
public void ignoreFilesThatAreNotReadableForCoverageChangeSet() throws Exception {
+
DriftDefinition def = driftDefinition("nonreadable-files-coverage",
resourcesDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
File server2Conf = createRandomFile(confDir, "server-2.conf");
- assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
+ boolean setToReadable = server2Conf.setReadable(false);
+ // not every win os (maybe none) supports this call, perform the test anyway, as
best as possible
+ if (!setToReadable) {
+ if (isWindows) {
+ server2Conf.delete();
+ } else {
+ assertTrue(setToReadable, "Failed to make " +
server2Conf.getPath() + " write only");
+ }
+ }
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
@@ -553,7 +566,15 @@ public class DriftDetectorTest extends DriftTest {
String newServer1Hash = sha256(server1Conf);
File server2Conf = createRandomFile(confDir, "server-2.conf");
- assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
+ boolean setToReadable = server2Conf.setReadable(false);
+ // not every win os (maybe none) supports this call, perform the test anyway, as
best as possible
+ if (!setToReadable) {
+ if (isWindows) {
+ server2Conf.delete();
+ } else {
+ assertTrue(setToReadable, "Failed to make " +
server2Conf.getPath() + " write only");
+ }
+ }
schedule.resetSchedule();
detector.run();
@@ -588,7 +609,15 @@ public class DriftDetectorTest extends DriftTest {
detector.run();
// make the file non-readable and run the detector again
- assertTrue(server1Conf.setReadable(false), "Failed to make " +
server1Conf.getPath() + " write only");
+ boolean setToReadable = server1Conf.setReadable(false);
+ // not every win os (maybe none) supports this call, perform the test anyway, as
best as possible
+ if (!setToReadable) {
+ if (isWindows) {
+ server1Conf.delete();
+ } else {
+ assertTrue(setToReadable, "Failed to make " +
server1Conf.getPath() + " write only");
+ }
+ }
schedule.resetSchedule();
detector.run();
commit 7ff17c046f4a499b86bb8a83f2edc6382190ed1d
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Sep 30 10:36:38 2011 -0400
Normalize drift file entries to use forward slash for safer comparison
and consistent views.
diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/FileEntry.java
b/modules/common/drift/src/main/java/org/rhq/common/drift/FileEntry.java
index 65bfec3..bafd297 100644
--- a/modules/common/drift/src/main/java/org/rhq/common/drift/FileEntry.java
+++ b/modules/common/drift/src/main/java/org/rhq/common/drift/FileEntry.java
@@ -19,13 +19,14 @@
package org.rhq.common.drift;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED;
+
import java.io.Serializable;
import org.rhq.core.domain.drift.DriftCategory;
-
-import static org.rhq.core.domain.drift.DriftCategory.*;
-import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
-import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED;
+import org.rhq.core.util.file.FileUtil;
public class FileEntry implements Serializable {
@@ -33,7 +34,7 @@ public class FileEntry implements Serializable {
public static FileEntry removedFileEntry(String file, String sha) {
FileEntry entry = new FileEntry();
- entry.file = file;
+ entry.file = FileUtil.useForwardSlash(file);
entry.oldSHA = sha;
entry.newSHA = "0";
entry.type = FILE_REMOVED;
@@ -43,7 +44,7 @@ public class FileEntry implements Serializable {
public static FileEntry addedFileEntry(String file, String sha) {
FileEntry entry = new FileEntry();
- entry.file = file;
+ entry.file = FileUtil.useForwardSlash(file);
entry.oldSHA = "0";
entry.newSHA = sha;
entry.type = FILE_ADDED;
@@ -53,7 +54,7 @@ public class FileEntry implements Serializable {
public static FileEntry changedFileEntry(String file, String oldSHA, String newSHA)
{
FileEntry entry = new FileEntry();
- entry.file = file;
+ entry.file = FileUtil.useForwardSlash(file);
entry.oldSHA = oldSHA;
entry.newSHA = newSHA;
entry.type = FILE_CHANGED;
@@ -97,7 +98,7 @@ public class FileEntry implements Serializable {
@Override
public String toString() {
- return getClass().getSimpleName() + "[newSHA: " + newSHA + ",
oldSHA: " + oldSHA + ", file: " + file +
- ", type: " + type.code() + "]";
+ return getClass().getSimpleName() + "[newSHA: " + newSHA + ",
oldSHA: " + oldSHA + ", file: " + file
+ + ", type: " + type.code() + "]";
}
}
commit 748a494b8ccd1c5b772e281da6c23f204cec11d1
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Fri Sep 30 10:36:00 2011 -0400
Add null protection for fileUtil.useForwardSlash()
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java
b/modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java
index 204ba1c..d297c49 100644
--- a/modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java
@@ -313,13 +313,13 @@ public class FileUtil {
}
/**
- * Ensure that the path uses only forward slash
- * Like java.io.File(String,String) but just
+ * Ensure that the path uses only forward slash like @{link
java.io.File(String,String)}
* @param path
- * @return
+ * @return forward-slashed path, or null if path is null
*/
public static String useForwardSlash(String path) {
- return path.replace('\\', '/');
+
+ return (null != path) ? path.replace('\\', '/') : null;
}
/**
@@ -335,7 +335,7 @@ public class FileUtil {
Deque<File> directories = new LinkedList<File>();
directories.push(directory);
- while(!directories.isEmpty()) {
+ while (!directories.isEmpty()) {
File dir = directories.pop();
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
commit 4d56f0b1e2f567ac333804fea42803ba757e6696
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Thu Sep 29 23:08:28 2011 -0400
Make sure our renamed resource field does not get wiped when sent to the
gui.
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
index 694fafd..89e217e 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
@@ -107,7 +107,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl
implements Re
// "eventSources \n" +
// "productVersion "}
"tags", //
- "driftConfigurations" };
+ "driftDefinitions" };
public static Set<String> importantFieldsSet = new
HashSet<String>(Arrays.asList(importantFields));
commit 55a79bc86a143d766a8ca7df69a0f2ddc1e04943
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Thu Sep 29 23:07:44 2011 -0400
Fix a variety of merge issues. Hopefully got them all.
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
index c121cfa..4a2d134 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
@@ -52,7 +52,7 @@ public interface DriftAgentService {
* Because the drift detection happens asynchronously, it cannot be guaranteed that
the
* drift detection will actually happen immediately. Drift detection schedules are
* maintained by a priority queue and are ordered by their next scan time. The
schedule
- * corresponding to <code>resourceId</code> and
<code>driftConfiguration</code> has its
+ * corresponding to <code>resourceId</code> and
<code>driftDefinition</code> has its
* next scan time reset in order to move the schedule to the front of the queue.
* <p/>
* Note that when the drift detection occurs is largely dependent on a couple of
@@ -64,72 +64,72 @@ public interface DriftAgentService {
* finish plus the time period between executions of the drift detector task.
*
* @param resourceId The id of the resource for which the request is being made
- * @param driftConfiguration Specifies how the detection should be carried out. This
+ * @param driftDefinition Specifies how the detection should be carried out. This
* includes any filtering rules that should be applied.
*/
- void detectDrift(int resourceId, DriftDefinition driftConfiguration);
+ void detectDrift(int resourceId, DriftDefinition driftDefinition);
/**
* Requests that the agent start performing drift detection for a resource with the
- * specified drift configuration. The interval at which the drift detection occurs
is
- * specified by the drift configuration.
+ * specified drift definition. The interval at which the drift detection occurs is
+ * specified by the drift definition.
* <p/>
* Note that drift detection occurs asynchronously which means that this method
should
- * return very quickly which could be before the drift detection for this
configuration
+ * return very quickly which could be before the drift detection for this definition
* has actually started.
*
* @param resourceId The id of the resource for which the request is being made
- * @param driftConfiguration Specifies how and when the detection should be carried
out
+ * @param driftDefinition Specifies how and when the detection should be carried out
* @see DriftDefinition
*/
- void scheduleDriftDetection(int resourceId, DriftDefinition driftConfiguration);
+ void scheduleDriftDetection(int resourceId, DriftDefinition driftDefinition);
/**
* Requests that the agent stop performing the specified drift detection for the
resource. (In
* effect, a remove operation).
*
* @param resourceId The id of the resource for which the request is being made
- * @param driftConfiguration The doomed drift config
+ * @param driftDefinition The doomed drift config
* @see DriftDefinition
*/
- void unscheduleDriftDetection(int resourceId, DriftDefinition driftConfiguration);
+ void unscheduleDriftDetection(int resourceId, DriftDefinition driftDefinition);
/**
- * Requests that the agent update its processing of the specified driftConfiguration.
The filters
+ * Requests that the agent update its processing of the specified driftDefinition.
The filters
* are unchanged, but something else may have changed (enablement/interval, etc).
*
* @param resourceId The id of the resource for which the request is being made
- * @param driftConfiguration The updated driftConfiguration.
+ * @param driftDefinition The updated driftDefinition.
* @see DriftDefinition
*/
- void updateDriftDetection(int resourceId, DriftDefinition driftConfiguration);
+ void updateDriftDetection(int resourceId, DriftDefinition driftDefinition);
/**
* This method is invoked to inform the agent that the server has successfully
* persisted the last change set sent to the server for the specified drift
- * configuration. The agent will proceed to purge the older, previous snapshot
+ * definition. The agent will proceed to purge the older, previous snapshot
* as well as the the change set zip file.
* <br/><br/>
* <strong>Note:</strong> The agent will not resume drift detection for
this drift
- * configuration until the server has acknowledged the last change set sent.
+ * definition until the server has acknowledged the last change set sent.
*
* @param resourceId The id of the resource to which the acknowledged change set
* belongs.
- * @param driftConfigName The name of the drift configuration to which the change
set
+ * @param driftDefName The name of the drift definition to which the change set
* belongs.
*/
- void ackChangeSet(int resourceId, String driftConfigName);
+ void ackChangeSet(int resourceId, String driftDefName);
/**
* This method is invoked to inform the agent that the server has successfully
* persisted change set content that was previously sent to the server. The agent
* will proceed to purge the referenced content zip file.
*
- * @param resourceId The id of the resource to which the referenced drift
configuration
+ * @param resourceId The id of the resource to which the referenced drift definition
* belongs.
- * @param driftConfigName The name of the drift configuration to which the content
+ * @param driftDefName The name of the drift definition to which the content
* belongs.
* @param token A token that is used to identify the content zip file
*/
- void ackChangeSetContent(int resourceId, String driftConfigName, String token);
+ void ackChangeSetContent(int resourceId, String driftDefName, String token);
}
\ No newline at end of file
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
index c7c88ef..f476263 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
@@ -107,7 +107,7 @@ public interface DriftServerService {
* for the acknowledgement step.
*
* @param resourceId The id of the resource to which the change set content belongs
- * @param driftConfigName The drift configuration name. This is needed for the
+ * @param driftDefName The drift definition name. This is needed for the
* acknowledgement step.
* @param token A token needed for the acknowledgement step that allows the agent to
* uniquely identify the zip file that was sent.
@@ -115,9 +115,9 @@ public interface DriftServerService {
* @param zipStream A RemoteStream
*/
@Asynchronous(guaranteedDelivery = true)
- void sendFilesZip(int resourceId, String driftConfigName, String token, long zipSize,
InputStream zipStream);
+ void sendFilesZip(int resourceId, String driftDefName, String token, long zipSize,
InputStream zipStream);
Map<Integer, List<DriftDefinition>>
getDriftDefinitions(Set<Integer> resourceIds);
- DriftSnapshot getCurrentSnapshot(int driftConfigurationId);
+ DriftSnapshot getCurrentSnapshot(int driftDefinitionId);
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index cba943f..8f8c23d 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@ -28,6 +28,7 @@ import static org.rhq.core.util.file.FileUtil.copyFile;
import static org.rhq.core.util.file.FileUtil.forEachFile;
import java.io.File;
+import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
@@ -71,7 +72,7 @@ public class DriftDetector implements Runnable {
@Override
public void run() {
- log.debug("Starting drift detection..");
+ log.debug("Starting drift detection...");
long startTime = System.currentTimeMillis();
try {
if (log.isDebugEnabled()) {
@@ -99,25 +100,30 @@ public class DriftDetector implements Runnable {
return;
}
- DriftDefinition driftDef = schedule.getDriftDefinition();
- DriftChangeSetCategory changeSetType = null;
- int changes = 0;
+ if (previousSnapshotExists(schedule)) {
+ log.debug("Skipping " + schedule + " because server has
not yet acked previous change set");
+ return;
+ }
+ DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
+ detectionSummary.setSchedule(schedule);
try {
if (changeSetMgr.changeSetExists(schedule.getResourceId(),
createHeaders(schedule, COVERAGE, 0))) {
- changeSetType = DRIFT;
- changes = generateDriftChangeSet(schedule);
+ detectionSummary.setType(DRIFT);
+ generateDriftChangeSet(detectionSummary);
} else {
- changeSetType = COVERAGE;
- generateSnapshot(schedule);
+ detectionSummary.setType(COVERAGE);
+ generateSnapshot(detectionSummary);
+ }
+ if (detectionSummary.getType() == COVERAGE ||
detectionSummary.getDriftChangeSet() != null) {
+ driftClient.sendChangeSetToServer(detectionSummary);
}
} catch (IOException e) {
- // TODO Call ChangeSetManager here to rollback any thing that was written
to disk.
- log.error("An error occurred while scanning for drift", e);
- }
-
- if (changeSetType == COVERAGE || changes > 0) {
- driftClient.sendChangeSetToServer(schedule.getResourceId(), driftDef,
changeSetType);
+ log.error("Drift detection failed: " + e.getMessage(), e);
+ revertSnapshot(detectionSummary);
+ } catch (RuntimeException e) {
+ log.error("Drift detection failed: " + e.getMessage(), e);
+ revertSnapshot(detectionSummary);
}
} catch (Throwable t) {
Throwable cause = t.getCause();
@@ -138,12 +144,22 @@ public class DriftDetector implements Runnable {
}
}
- private int generateDriftChangeSet(final DriftDetectionSchedule schedule) throws
IOException {
+ private boolean previousSnapshotExists(DriftDetectionSchedule schedule) {
+ File snapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition().getName(),
+ COVERAGE);
+ File previousSnapshot = new File(snapshot.getParentFile(), snapshot.getName() +
".previous");
+ return previousSnapshot.exists();
+ }
+
+ private void generateDriftChangeSet(DriftDetectionSummary summary) throws IOException
{
+ final DriftDetectionSchedule schedule = summary.getSchedule();
+
log.debug("Generating drift change set for " + schedule);
final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftDefinition()));
- final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(schedule.getResourceId(), schedule
- .getDriftDefinition().getName());
+ File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
+ .getName(), COVERAGE);
+ final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(currentSnapshot);
final Set<File> processedFiles = new HashSet<File>();
final List<FileEntry> snapshotEntries = new LinkedList<FileEntry>();
final List<FileEntry> deltaEntries = new LinkedList<FileEntry>();
@@ -154,16 +170,22 @@ public class DriftDetector implements Runnable {
File file = new File(basedir, entry.getFile());
if (!file.exists()) {
// The file has been deleted since the last scan
- if (log.isInfoEnabled()) {
- log.info("Detected deleted file for " + schedule + "
--> " + file.getAbsolutePath());
+ if (log.isDebugEnabled()) {
+ log.debug("Detected deleted file for " + schedule + "
--> " + file.getAbsolutePath());
+ }
+ deltaEntries.add(removedFileEntry(entry.getFile(), entry.getNewSHA()));
+ } else if (!file.canRead()) {
+ processedFiles.add(file);
+ if (log.isDebugEnabled()) {
+ log.debug(file.getPath() + " is no longer readable. Treating it
as a deleted file.");
}
deltaEntries.add(removedFileEntry(entry.getFile(), entry.getNewSHA()));
} else {
processedFiles.add(file);
String currentSHA = sha256(file);
if (!currentSHA.equals(entry.getNewSHA())) {
- if (log.isInfoEnabled()) {
- log.info("Detected modified file for " + schedule +
" --> " + file.getAbsolutePath());
+ if (log.isDebugEnabled()) {
+ log.debug("Detected modified file for " + schedule +
" --> " + file.getAbsolutePath());
}
FileEntry modifiedEntry = changedFileEntry(entry.getFile(),
entry.getNewSHA(), currentSHA);
deltaEntries.add(modifiedEntry);
@@ -187,6 +209,13 @@ public class DriftDetector implements Runnable {
return;
}
+ if (!file.canRead()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Skipping " + file.getPath() + "
since it is not readable.");
+ return;
+ }
+ }
+
if (log.isInfoEnabled()) {
log.info("Detected added file for " + schedule +
" --> " + file.getAbsolutePath());
}
@@ -205,39 +234,47 @@ public class DriftDetector implements Runnable {
if (deltaEntries.isEmpty()) {
// If nothing has changed, there is no need to add/update any files
- return 0;
- }
-
- File snapshotFile = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
- .getName(), COVERAGE);
- File backupSnapshotFile = new File(snapshotFile.getParentFile(),
snapshotFile.getName() + ".bak");
- copyFile(snapshotFile, snapshotFile);
-
- Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
- Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
-
- ChangeSetWriter deltaWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), deltaHeaders);
- ChangeSetWriter snapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), snapshotHeaders);
-
- for (FileEntry entry : deltaEntries) {
- deltaWriter.write(entry);
- }
- deltaWriter.close();
+ summary.setNewSnapshot(currentSnapshot);
+ } else {
+ File oldSnapshot = new File(currentSnapshot.getParentFile(),
currentSnapshot.getName() + ".previous");
+ copyFile(currentSnapshot, oldSnapshot);
+ currentSnapshot.delete();
+
+ Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
+ Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
+
+ File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
+ .getName(), DRIFT);
+ ChangeSetWriter deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet,
deltaHeaders);
+
+ File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
+ .getName(), COVERAGE);
+ ChangeSetWriter newSnapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(),
+ snapshotHeaders);
+
+ summary.setDriftChangeSet(driftChangeSet);
+ summary.setNewSnapshot(newSnapshot);
+ summary.setOldSnapshot(oldSnapshot);
+
+ for (FileEntry entry : deltaEntries) {
+ deltaWriter.write(entry);
+ }
+ deltaWriter.close();
- for (FileEntry entry : snapshotEntries) {
- snapshotWriter.write(entry);
+ for (FileEntry entry : snapshotEntries) {
+ newSnapshotWriter.write(entry);
+ }
+ newSnapshotWriter.close();
}
- snapshotWriter.close();
- backupSnapshotFile.delete();
-
- return deltaEntries.size();
}
- private void generateSnapshot(final DriftDetectionSchedule schedule) throws
IOException {
+ private void generateSnapshot(DriftDetectionSummary summary) throws IOException {
+ final DriftDetectionSchedule schedule = summary.getSchedule();
log.debug("Generating coverage change set for " + schedule);
- final ChangeSetWriter writer =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(
- schedule, COVERAGE, 0));
+ File snapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition().getName(),
+ COVERAGE);
+ final ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(snapshot,
createHeaders(schedule, COVERAGE, 0));
final DriftDefinition driftDef = schedule.getDriftDefinition();
final File basedir = new File(basedir(schedule.getResourceId(), driftDef));
if (basedir.isDirectory()) {
@@ -247,10 +284,14 @@ public class DriftDetector implements Runnable {
@Override
public void visit(File file) {
try {
- if (log.isInfoEnabled()) {
- log
- .info("Adding " + file.getAbsolutePath() +
" to coverage change set for "
- + schedule);
+ if (!file.canRead()) {
+ if (log.isDebugEnabled()) {
+ log.debug("Skipping " + file.getPath() +
" since it is not readable.");
+ }
+ return;
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("Adding " + file.getPath() + "
to coverage change set for " + schedule);
}
writer.write(addedFileEntry(relativePath(basedir, file),
sha256(file)));
} catch (IOException e) {
@@ -263,6 +304,7 @@ public class DriftDetector implements Runnable {
}));
}
writer.close();
+ summary.setNewSnapshot(snapshot);
}
private String relativePath(File basedir, File file) {
@@ -292,4 +334,50 @@ public class DriftDetector implements Runnable {
return headers;
}
+ private void revertSnapshot(DriftDetectionSummary summary) throws IOException {
+ log.info("Reverting snapshot for " + summary.getSchedule());
+
+ DriftDetectionSchedule scheudle = summary.getSchedule();
+ File newSnapshot = changeSetMgr.findChangeSet(scheudle.getResourceId(),
+ scheudle.getDriftDefinition().getName(), COVERAGE);
+
+ // We want to delete the snapshot file regardless of whether the drift detection
+ // was for an initial coverage change set or for a drift change set. We do not
know
+ // the state of the snapshot file so we have to delete it. If we have only
generated
+ // the initial coverage change set, then it will get regenerated.
+ newSnapshot.delete();
+
+ if (summary.getType() == DRIFT) {
+ File oldSnapshotBackup = summary.getOldSnapshot();
+ // If we generated a drift change set, we need to check for a back up of the
+ // previous snapshot. We revert to the back up. If no back up is found, we
log
+ // an error.
+ if (oldSnapshotBackup != null && oldSnapshotBackup.exists()) {
+ copyFile(oldSnapshotBackup, newSnapshot);
+ // We have to delete to the previous version snapshot file; otherwise,
+ // subsequent detection runs will be skipped.
+ oldSnapshotBackup.delete();
+ } else {
+ // TODO Should we throw an exception and/or disable detection?
+ // If we fall into this else block, that means we were not able to
revert
+ // to the previous snapshot version, and we may be in an inconsistent
state.
+ log.error("Cannot revert snapshot to previous version for " +
summary.getSchedule()
+ + ". Snapshot back up file not found.");
+ }
+ }
+ deleteZipFiles(newSnapshot.getParentFile());
+ }
+
+ private void deleteZipFiles(File dir) {
+ File[] files = dir.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".zip");
+ }
+ });
+ for (File file : files) {
+ file.delete();
+ }
+ }
+
}
\ No newline at end of file
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
index f655dd7..74ed3d4 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
@@ -22,14 +22,16 @@ package org.rhq.core.pc.drift;
import static org.rhq.common.drift.FileEntry.addedFileEntry;
import static org.rhq.common.drift.FileEntry.changedFileEntry;
import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
import static org.rhq.core.util.file.FileUtil.purge;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -46,9 +48,7 @@ import org.rhq.core.clientapi.agent.drift.DriftAgentService;
import org.rhq.core.clientapi.server.drift.DriftServerService;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.drift.Drift;
-import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
-import org.rhq.core.domain.drift.DriftDefinitionComparator;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.resource.Resource;
@@ -94,6 +94,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
@Override
public void initialize() {
+ long initStartTime = System.currentTimeMillis();
changeSetsDir.mkdir();
changeSetMgr = new ChangeSetManagerImpl(changeSetsDir);
@@ -106,8 +107,12 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
long startTime = System.currentTimeMillis();
initSchedules(inventoryMgr.getPlatform(), inventoryMgr);
long endTime = System.currentTimeMillis();
- log.info("Finished initializing drift detection schedules in " +
(endTime - startTime) + " ms");
+ if (log.isInfoEnabled()) {
+ log.info("Finished initializing drift detection schedules in " +
(endTime - startTime) + " ms");
+ }
+
+ scanForContentToResend();
purgeDeletedDriftDefDirs();
driftThreadPool = new ScheduledThreadPoolExecutor(5);
@@ -122,6 +127,10 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
initialized = true;
+ long initEndTime = System.currentTimeMillis();
+ if (log.isInfoEnabled()) {
+ log.info("Finished initialization in " + (initEndTime -
initStartTime) + " ms");
+ }
}
private void initSchedules(Resource r, InventoryManager inventoryMgr) {
@@ -152,32 +161,34 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
- private void syncWithServer(Resource resource, DriftDefinition driftDef) throws
IOException {
- Headers headers = createHeaders(resource, driftDef);
+ private void syncWithServer(Resource resource, DriftDefinition driftDefinition)
throws IOException {
+ Headers headers = createHeaders(resource, driftDefinition);
if (!changeSetMgr.changeSetExists(resource.getId(), headers)) {
- log.info("No snapshot found for " + toString(resource, driftDef) +
". Downloading snapshot from "
+ log.info("No snapshot found for " + toString(resource,
driftDefinition) + ". Downloading snapshot from "
+ "server");
DriftSnapshot snapshot =
pluginContainerConfiguration.getServerServices().getDriftServerService()
- .getCurrentSnapshot(driftDef.getId());
+ .getCurrentSnapshot(driftDefinition.getId());
if (snapshot.getVersion() == -1) {
// A version of -1 indicates that no change sets have been reported
- // for this def. This can occur when a user creates a
- // drift def while the agent is offline for example. At
+ // for this definition. This can occur when a user creates a
+ // drift definition while the agent is offline for example. At
// this point we just return and allow the agent to generate the
// initial snapshot file.
if (log.isDebugEnabled()) {
- log.debug("The server does not have any change sets for " +
toString(resource, driftDef)
+ log.debug("The server does not have any change sets for " +
toString(resource, driftDefinition)
+ ". An initial snapshot needs to be generated.");
}
return;
}
+ headers.setVersion(snapshot.getVersion());
+
log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for "
- + toString(resource, driftDef));
+ + toString(resource, driftDefinition));
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resource.getId(),
headers);
- for (Drift drift : snapshot.getEntries()) {
+ for (Drift<?, ?> drift : snapshot.getEntries()) {
switch (drift.getCategory()) {
case FILE_ADDED:
writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
@@ -196,15 +207,13 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
private void purgeDeletedDriftDefDirs() {
log.info("Checking for deleted drift definitions");
- DriftDefinitionComparator comparator = new DriftDefinitionComparator(
- BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
for (File resourceDir : changeSetsDir.listFiles()) {
int resourceId = Integer.parseInt(resourceDir.getName());
for (File defDir : resourceDir.listFiles()) {
- DriftDefinition def = new DriftDefinition(new Configuration());
- def.setName(defDir.getName());
- if (!schedulesQueue.contains(resourceId, def)) {
- log.info("Detected deleted drift definition,
DriftDefinition[name: " + def.getName()
+ DriftDefinition driftDef = new DriftDefinition(new Configuration());
+ driftDef.setName(defDir.getName());
+ if (!schedulesQueue.contains(resourceId, driftDef)) {
+ log.info("Detected deleted drift definition,
DriftDefinition[name: " + driftDef.getName()
+ ", resourceId: " + resourceId + "]");
log.info("Deleting drift definition directory " +
defDir.getPath());
purge(defDir, true);
@@ -213,17 +222,40 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
+ /**
+ * Scans the changesets directory for any change set content zip files. This method
+ * assumes that any content zip files found have not been received or persisted by
the
+ * server. Each content zip file is resent to the server.
+ */
+ public void scanForContentToResend() {
+ log.info("Scanning for change set content to resend...");
+ for (File resourceDir : changeSetsDir.listFiles()) {
+ for (File defDir : resourceDir.listFiles()) {
+ for (File contentZipFile : defDir.listFiles(new
ZipFileNameFilter("content_"))) {
+ if (log.isDebugEnabled()) {
+ log.debug("Resending " + contentZipFile.getPath());
+ }
+ sendContentZipFile(Integer.parseInt(resourceDir.getName()),
defDir.getName(), contentZipFile);
+ }
+ }
+ }
+ }
+
private String toString(Resource r, DriftDefinition c) {
- return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ r.getId() + ", name: " + c.getName() + "]";
+ return toString(r.getId(), c);
+ }
+
+ private String toString(int resourceId, DriftDefinition c) {
+ return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ resourceId + ", name: " + c.getName() + "]";
}
- private Headers createHeaders(Resource resource, DriftDefinition driftDef) {
+ private Headers createHeaders(Resource resource, DriftDefinition driftDefinition) {
Headers headers = new Headers();
headers.setResourceId(resource.getId());
- headers.setDriftDefinitionId(driftDef.getId());
- headers.setType(DriftChangeSetCategory.COVERAGE);
- headers.setDriftDefinitionName(driftDef.getName());
- headers.setBasedir(getAbsoluteBaseDirectory(resource.getId(),
driftDef).getAbsolutePath());
+ headers.setDriftDefinitionId(driftDefinition.getId());
+ headers.setType(COVERAGE);
+ headers.setDriftDefinitionName(driftDefinition.getName());
+ headers.setBasedir(getAbsoluteBaseDirectory(resource.getId(),
driftDefinition).getAbsolutePath());
return headers;
}
@@ -256,55 +288,69 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void sendChangeSetToServer(int resourceId, DriftDefinition driftDef,
DriftChangeSetCategory type) {
- try {
- if (!schedulesQueue.contains(resourceId, driftDef)) {
- return;
- }
+ public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
+ int resourceId = detectionSummary.getSchedule().getResourceId();
+ DriftDefinition driftDefinition =
detectionSummary.getSchedule().getDriftDefinition();
- File changeSetFile = changeSetMgr.findChangeSet(resourceId,
driftDef.getName(), type);
- if (changeSetFile == null) {
- log.warn("changeset[resourceId: " + resourceId + ",
driftDefinition: " + driftDef.getName()
- + "] was not found. Cancelling request to send change set "
+ "to server");
- return;
- }
+ if (!schedulesQueue.contains(resourceId, driftDefinition)) {
+ return;
+ }
- DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ File changeSetFile;
+ if (detectionSummary.getType() == COVERAGE) {
+ changeSetFile = detectionSummary.getNewSnapshot();
+ } else {
+ changeSetFile = detectionSummary.getDriftChangeSet();
+ }
+ if (changeSetFile == null) {
+ log.warn("changeset[resourceId: " + resourceId + ",
driftDefinition: " + driftDefinition.getName()
+ + "] was not found. Cancelling request to send change set " +
"to server");
+ return;
+ }
- // TODO Include the version in the change set file name to ensure the file
name is unique
- String fileName = "changeset_" + System.currentTimeMillis() +
".zip";
- final File zipFile = new File(changeSetFile.getParentFile(), fileName);
- ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
+ DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ String fileName = "changeset_" + System.currentTimeMillis() +
".zip";
+ final File zipFile = new File(changeSetFile.getParentFile(), fileName);
+ ZipOutputStream stream = null;
+
+ try {
+ stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
FileInputStream fis = new FileInputStream(changeSetFile);
stream.putNextEntry(new ZipEntry(changeSetFile.getName()));
StreamUtil.copy(fis, stream, false);
fis.close();
stream.close();
+ } catch (IOException e) {
+ zipFile.delete();
+ throw new DriftDetectionException("Failed to create change set zip file
" + zipFile.getPath(), e);
+ } finally {
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (IOException e) {
+ log.warn("An error occurred while trying to close change set zip
file output stream", e);
+ }
+ }
- // We want to clean up after we send the zip file to the server. We do this
by
- // deleting the files in the content directory and the content zip itself.
They
- // are no longer needed after being sent to the server. We cannot
immediately
- // delete the content zip file though because it is sent asynchronously, and
we
- // wind up deleting it before it is sent. The following approach allows us
to
- // safely delete it when the comm layer closes the remote input stream.
- //
- // jsanda
- DriftInputStream inputStream = new DriftInputStream(new
BufferedInputStream(new FileInputStream(zipFile)),
- new DeleteFile(zipFile));
-
- driftServer.sendChangesetZip(resourceId, zipFile.length(),
remoteInputStream(inputStream));
-
+ try {
+ driftServer.sendChangesetZip(resourceId, zipFile.length(),
remoteInputStream(new BufferedInputStream(
+ new FileInputStream(zipFile))));
} catch (IOException e) {
- log.error("An error occurred while trying to send changeset[resourceId:
" + resourceId
- + ", driftDefinition: " + driftDef.getName() + "]",
e);
+ throw new DriftDetectionException("Failed to set change set for " +
toString(resourceId, driftDefinition)
+ + " to server");
+ } catch (RuntimeException e) {
+ throw new DriftDetectionException("Failed to set change set for " +
toString(resourceId, driftDefinition)
+ + " to server");
}
}
@Override
- public void sendChangeSetContentToServer(int resourceId, String driftDefName, final
File contentDir) {
+ public void sendChangeSetContentToServer(int resourceId, String driftDefinitionName,
final File contentDir) {
try {
- String contentFileName = "content_" + System.currentTimeMillis() +
".zip";
+ String timestamp = Long.toString(System.currentTimeMillis());
+ String contentFileName = "content_" + timestamp +
".zip";
final File zipFile = new File(contentDir.getParentFile(), contentFileName);
ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
@@ -316,22 +362,13 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
stream.close();
- // We want to clean up after we send the zip file to the server. We do this
by
- // deleting the files in the content directory and the content zip itself.
They
- // are no longer needed after being sent to the server. We cannot
immediately
- // delete the content zip file though because it is sent asynchronously, and
we
- // wind up deleting it before it is sent. The following approach allows us
to
- // safely delete it when the comm layer closes the remote input stream.
- //
- // jsanda
- DriftInputStream inputStream = new DriftInputStream(new
BufferedInputStream(new FileInputStream(zipFile)),
- new DeleteFile(zipFile));
-
- DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
- driftServer.sendFilesZip(resourceId, zipFile.length(),
remoteInputStream(inputStream));
+ // DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ // driftServer.sendFilesZip(resourceId, driftDefinitionName,
timestamp, zipFile.length(),
+ // remoteInputStream(new BufferedInputStream(new
FileInputStream(zipFile))));
+ sendContentZipFile(resourceId, driftDefinitionName, zipFile);
} catch (IOException e) {
log.error("An error occurred while trying to send content for
changeset[resourceId: " + resourceId
- + ", driftDefinition: " + driftDefName + "]", e);
+ + ", driftDefinition: " + driftDefinitionName + "]",
e);
}
for (File file : contentDir.listFiles()) {
@@ -341,17 +378,34 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
+ private void sendContentZipFile(int resourceId, String driftDefName, File
contentZipFile) {
+ try {
+ int startIndex = "content_".length();
+ int endIndex = contentZipFile.getName().indexOf(".");
+ String token = contentZipFile.getName().substring(startIndex, endIndex);
+
+ DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ driftServer.sendFilesZip(resourceId, driftDefName, token,
contentZipFile.length(),
+ remoteInputStream(new BufferedInputStream(new
FileInputStream(contentZipFile))));
+ } catch (FileNotFoundException e) {
+ log.error("An error occurred while trying to send change set content zip
file " + contentZipFile.getPath()
+ + " to server.", e);
+ }
+ }
+
@Override
- public void detectDrift(int resourceId, DriftDefinition driftDef) {
+ public void detectDrift(int resourceId, DriftDefinition driftDefinition) {
if (log.isInfoEnabled()) {
log.info("Received request to schedule drift detection immediately for
[resourceId: " + resourceId
- + ", driftDefId: " + driftDef.getId() + ", driftDefName:
" + driftDef.getName() + "]");
+ + ", driftDefinitionId: " + driftDefinition.getId() + ",
driftDefinitionName: "
+ + driftDefinition.getName() + "]");
}
- DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId, driftDef);
+ DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId,
driftDefinition);
if (schedule == null) {
- log.warn("No schedule found in the queue for [resourceId: " +
resourceId + ", driftDefId: "
- + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"]. No " + " work will be scheduled.");
+ log.warn("No schedule found in the queue for [resourceId: " +
resourceId + ", driftDefinitionId: "
+ + driftDefinition.getId() + ", driftDefinitionName: " +
driftDefinition.getName() + "]. No "
+ + " work will be scheduled.");
return;
}
log.debug("Resetting " + schedule + " for immediate
detection.");
@@ -368,8 +422,8 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void scheduleDriftDetection(int resourceId, DriftDefinition driftDef) {
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId,
driftDef);
+ public void scheduleDriftDetection(int resourceId, DriftDefinition driftDefinition)
{
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId,
driftDefinition);
if (log.isInfoEnabled()) {
log.info("Scheduling drift detection for " + schedule);
}
@@ -381,7 +435,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
ResourceContainer container =
getInventoryManager().getResourceContainer(resourceId);
if (container != null) {
- container.addDriftDefinition(driftDef);
+ container.addDriftDefinition(driftDefinition);
}
} else {
log.warn("Failed to add " + schedule + " to " +
schedulesQueue);
@@ -391,8 +445,8 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
@Override
public boolean requestDriftFiles(int resourceId, Headers headers, List<? extends
DriftFile> driftFiles) {
if (log.isInfoEnabled()) {
- log.info("Server is requesting files for [resourceId: " +
resourceId + ", driftDefId: "
- + headers.getDriftDefinitionId() + ", driftDefName: " +
headers.getDriftDefinitionName() + "]");
+ log.info("Server is requesting files for [resourceId: " +
resourceId + ", driftDefinitionId: "
+ + headers.getDriftDefinitionId() + ", driftDefinitionName: " +
headers.getDriftDefinitionName() + "]");
}
DriftFilesSender sender = new DriftFilesSender();
sender.setResourceId(resourceId);
@@ -407,15 +461,16 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void unscheduleDriftDetection(final int resourceId, final DriftDefinition
driftDef) {
- log.info("Received request to unschedule drift detection for
[resourceId:" + resourceId + ", driftDefId: "
- + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"].");
+ public void unscheduleDriftDetection(final int resourceId, final DriftDefinition
driftDefinition) {
+ log.info("Received request to unschedule drift detection for
[resourceId:" + resourceId
+ + ", driftDefinitionId: " + driftDefinition.getId() + ",
driftDefinitionName: " + driftDefinition.getName()
+ + "].");
- DriftDetectionSchedule schedule = schedulesQueue.removeAndExecute(resourceId,
driftDef, new Runnable() {
+ DriftDetectionSchedule schedule = schedulesQueue.removeAndExecute(resourceId,
driftDefinition, new Runnable() {
@Override
public void run() {
File resourceDir = new File(changeSetsDir,
Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, driftDef.getName());
+ File changeSetDir = new File(resourceDir, driftDefinition.getName());
purge(changeSetDir, true);
log.debug("Removed change set directory " +
changeSetDir.getAbsolutePath());
@@ -435,12 +490,12 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void updateDriftDetection(int resourceId, DriftDefinition driftDef) {
- log.info("Received request to update schedule for [resourceId: " +
resourceId + ", driftDefId: "
- + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"]");
- DriftDetectionSchedule updatedSchedule = schedulesQueue.update(resourceId,
driftDef);
+ public void updateDriftDetection(int resourceId, DriftDefinition driftDefinition) {
+ log.info("Received request to update schedule for [resourceId: " +
resourceId + ", driftDefinitionId: "
+ + driftDefinition.getId() + ", driftDefinitionName: " +
driftDefinition.getName() + "]");
+ DriftDetectionSchedule updatedSchedule = schedulesQueue.update(resourceId,
driftDefinition);
if (updatedSchedule == null) {
- updatedSchedule = new DriftDetectionSchedule(resourceId, driftDef);
+ updatedSchedule = new DriftDetectionSchedule(resourceId, driftDefinition);
if (log.isInfoEnabled()) {
log.info("No matching schedule was found in the queue. This must be
a request to add a new "
+ "schedule. Adding " + updatedSchedule + " to "
+ schedulesQueue);
@@ -464,31 +519,75 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
InventoryManager inventoryMgr =
PluginContainer.getInstance().getInventoryManager();
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
if (container != null) {
- container.addDriftDefinition(driftDef);
+ container.addDriftDefinition(driftDefinition);
+ }
+ }
+
+ @Override
+ public void ackChangeSet(int resourceId, String driftDefName) {
+ log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftDefinition:" + driftDefName
+ + "]");
+
+ File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
+ File changeSetDir = new File(resourceDir, driftDefName);
+
+ if (!changeSetDir.exists()) {
+ log.warn("Cannot complete acknowledgement. Change set directory " +
changeSetDir.getPath()
+ + " does not exist.");
+ return;
+ }
+
+ File snapshot = changeSetMgr.findChangeSet(resourceId, driftDefName, COVERAGE);
+ File previousSnapshot = new File(snapshot.getParentFile(), snapshot.getName() +
".previous");
+
+ previousSnapshot.delete();
+ deleteZipFiles(changeSetDir, "changeset_");
+ }
+
+ @Override
+ public void ackChangeSetContent(int resourceId, String driftDefName, String token) {
+ log.info("Received server change set content ack for [resourceId: " +
resourceId + ", driftDefinitionName: "
+ + driftDefName + "]");
+
+ File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
+ File changeSetDir = new File(resourceDir, driftDefName);
+
+ if (!changeSetDir.exists()) {
+ log.warn("Cannot complete acknowledgement. Change set directory " +
changeSetDir.getPath()
+ + " does not exist.");
+ return;
+ }
+
+ deleteZipFiles(changeSetDir, "content_" + token);
+ }
+
+ private void deleteZipFiles(File dir, final String prefix) {
+ for (File file : dir.listFiles(new ZipFileNameFilter(prefix))) {
+ file.delete();
}
}
/**
- * Given a drift definition, this examines the config and its associated resource to
determine where exactly
+ * Given a drift definition, this examines the def and its associated resource to
determine where exactly
* the base directory is that should be monitoried.
*
- * @param resourceId The id of the resource to which the config belongs
- * @param driftDef describes what is to be monitored for drift
+ * @param resourceId The id of the resource to which the def belongs
+ * @param driftDefinition describes what is to be monitored for drift
*
- * @return absolute directory location where the drift definition base directory is
referring
+ * @return absolute directory location where the drift def base directory is
referring
*/
@Override
- public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition driftDef) {
+ public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition driftDefinition)
{
// get the resource entity stored in our local inventory
InventoryManager im = getInventoryManager();
ResourceContainer container = im.getResourceContainer(resourceId);
Resource resource = container.getResource();
- // find out the type of base location that is specified by the drift config
- DriftDefinition.BaseDirectory baseDir = driftDef.getBasedir();
+ // find out the type of base location that is specified by the drift def
+ DriftDefinition.BaseDirectory baseDir = driftDefinition.getBasedir();
if (baseDir == null) {
- throw new IllegalArgumentException("Missing basedir in drift
def");
+ throw new IllegalArgumentException("Missing basedir in drift
definition");
}
// based on the type of base location, determine the root base directory
@@ -562,17 +661,16 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
return PluginContainer.getInstance().getMeasurementManager();
}
- private static class DeleteFile implements Runnable {
+ private static class ZipFileNameFilter implements FilenameFilter {
+ private String prefix;
- private File file;
-
- public DeleteFile(File file) {
- this.file = file;
+ public ZipFileNameFilter(String prefix) {
+ this.prefix = prefix;
}
@Override
- public void run() {
- file.delete();
+ public boolean accept(File dir, String name) {
+ return name.startsWith(prefix) && name.endsWith(".zip");
}
}
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
index 35e62d8..b24849b 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
@@ -37,9 +37,9 @@ import org.rhq.core.pc.drift.DriftManager;
import org.rhq.core.pc.inventory.InventoryManager;
/**
- * This class handles syncing drift definitions during inventory sync. This class is
- * intended to server as the public interface (so to speak) to {@link InventoryManager}
for
- * syncing drift definitions.
+ * This class handles syncing drift definitions and drift content during inventory sync.
+ * This class is intended to server as the public interface (so to speak) to
+ * {@link InventoryManager} for syncing drift definitions and content.
* <br/><br/>
* Please review the docs for each of the setter methods to determine which properties
* should be set before invoking any business logic methods.
@@ -89,13 +89,19 @@ public class DriftSyncManager {
dataDir = dataDirectory;
}
- public void syncDefsWithServer(Set<Integer> resourceIds) {
- log.info("Starting server sync for drift definitions...");
- long startTime = System.currentTimeMillis();
-
- Map<Integer, List<DriftDefinition>> defs =
driftServer.getDriftDefinitions(resourceIds);
- DriftDefinitionComparator comparator = new DriftDefinitionComparator(
- BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
+ /**
+ * Synchronized both drift definitions and drift content with the server. The drift
+ * definition sync goes from server to agent in that the drift definitions in the
+ * local inventory are updated to match the drift definitions on the server
+ * inventory.
+ * <br/><br/>
+ * The content sync works as follows. Any change set content zip files found locally
+ * resent to the server under the assumption that the content has not been persisted
on
+ * the server.
+ *
+ * @param resourceIds The ids of resources that need to be synced.
+ */
+ public void syncWithServer(Set<Integer> resourceIds) {
DriftSynchronizerFactory synchronizerFactory = new DriftSynchronizerFactory();
DriftSynchronizer synchronizer;
@@ -105,18 +111,31 @@ public class DriftSyncManager {
synchronizer = synchronizerFactory.getRuntimeSynchronizer(driftMgr);
}
+ syncConfigs(synchronizer, resourceIds);
+ syncContent(synchronizer);
+ }
+
+ private void syncConfigs(DriftSynchronizer synchronizer, Set<Integer>
resourceIds) {
+ log.info("Starting server sync for drift definitions...");
+ long startTime = System.currentTimeMillis();
+
+ Map<Integer, List<DriftDefinition>> driftDefs =
driftServer.getDriftDefinitions(resourceIds);
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
+ BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
+
int totalDeleted = 0;
int totalAdded = 0;
- for (Integer resourceId : defs.keySet()) {
- Set<DriftDefinition> resourceDefsOnServer = new
TreeSet<DriftDefinition>(comparator);
- resourceDefsOnServer.addAll(defs.get(resourceId));
+ for (Integer resourceId : driftDefs.keySet()) {
+ Set<DriftDefinition> resourceConfigsOnServer = new
TreeSet<DriftDefinition>(comparator);
+ resourceConfigsOnServer.addAll(driftDefs.get(resourceId));
- List<DriftDefinition> deletedDefs =
synchronizer.getDeletedDefinitions(resourceId, resourceDefsOnServer);
+ List<DriftDefinition> deletedDefs =
synchronizer.getDeletedDefinitions(resourceId,
+ resourceConfigsOnServer);
totalDeleted += deletedDefs.size();
synchronizer.purgeFromLocalInventory(resourceId, deletedDefs);
- List<DriftDefinition> addedDefs =
synchronizer.getAddedDefinitions(resourceId, resourceDefsOnServer);
+ List<DriftDefinition> addedDefs =
synchronizer.getAddedDefinitions(resourceId, resourceConfigsOnServer);
totalAdded += addedDefs.size();
synchronizer.addToLocalInventory(resourceId, addedDefs);
}
@@ -128,6 +147,16 @@ public class DriftSyncManager {
}
}
+ private void syncContent(DriftSynchronizer synchronizer) {
+ log.info("Starting drift content sync...");
+ long startTime = System.currentTimeMillis();
+ synchronizer.syncChangeSetContent();
+ long endTime = System.currentTimeMillis();
+ if (log.isInfoEnabled()) {
+ log.info("Finished drift content sync in " + (endTime - startTime)
+ " ms");
+ }
+ }
+
/**
* This method determines whether or not this is a sync being done at start up (or
* more precisely during PC initialization). It does by checking to see if
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
index 99c7101..a637a51 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
@@ -2,29 +2,39 @@ package org.rhq.core.pc.drift;
import java.io.File;
-import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
class DriftClientTestStub implements DriftClient {
private File basedir;
- @Override
- public void sendChangeSetToServer(int resourceId, DriftDefinition
driftConfiguration,
- DriftChangeSetCategory type) {
+ private boolean failingOnSendChangeSet;
+ @Override
+ public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
+ if (failingOnSendChangeSet) {
+ throw new RuntimeException("Failed to send change set to server");
+ }
}
@Override
- public void sendChangeSetContentToServer(int resourceId, String
driftConfigurationName, File contentDir) {
+ public void sendChangeSetContentToServer(int resourceId, String driftDefinitionName,
File contentDir) {
}
@Override
- public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition
driftConfiguration) {
+ public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition driftDefinition)
{
return basedir;
}
public void setBaseDir(File basedir) {
this.basedir = basedir;
}
+
+ public boolean isFailingOnSendChangeSet() {
+ return failingOnSendChangeSet;
+ }
+
+ public void setFailingOnSendChangeSet(boolean failing) {
+ failingOnSendChangeSet = failing;
+ }
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
index 0a3b10c..50f2899 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
@@ -19,6 +19,20 @@
package org.rhq.core.pc.drift;
+import static java.util.Arrays.asList;
+import static java.util.Collections.emptyList;
+import static org.apache.commons.io.FileUtils.touch;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.common.drift.FileEntry.removedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
+import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
@@ -36,20 +50,6 @@ import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
-import static java.util.Arrays.asList;
-import static java.util.Collections.emptyList;
-import static org.apache.commons.io.FileUtils.touch;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
-import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
-import static org.rhq.test.AssertUtils.assertPropertiesMatch;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertTrue;
-
public class DriftDetectorTest extends DriftTest {
ScheduleQueue scheduleQueue;
@@ -80,7 +80,7 @@ public class DriftDetectorTest extends DriftTest {
// create an empty directory
File libDir = mkdir(resourceDir, "lib");
- DriftDefinition driftConfig = driftConfiguration("coverage-test",
resourceDir.getAbsolutePath());
+ DriftDefinition driftConfig = driftDefinition("coverage-test",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(),
driftConfig));
detector.run();
@@ -100,17 +100,16 @@ public class DriftDetectorTest extends DriftTest {
File server1Conf = createRandomFile(confDir, "server-1.conf");
File server2Conf = createRandomFile(confDir, "server-2.conf");
- DriftDefinition config = driftConfiguration("multiple-files-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("multiple-files-test",
resourceDir.getAbsolutePath());
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File changeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> entries = asList(
- addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
- addedFileEntry("conf/server-2.conf", sha256(server2Conf)));
+ File changeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> entries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
addedFileEntry(
+ "conf/server-2.conf", sha256(server2Conf)));
- assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
+ assertHeaderEquals(changeSet, createHeaders(def, COVERAGE));
assertFileEntriesMatch("Each file in a directory should be included in a
coverage change set", entries,
changeSet);
}
@@ -124,17 +123,16 @@ public class DriftDetectorTest extends DriftTest {
File libDir = mkdir(resourceDir, "lib");
File serverLib = createRandomFile(libDir, "server.jar");
- DriftDefinition config = driftConfiguration("sibling-dirs-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("sibling-dirs-test",
resourceDir.getAbsolutePath());
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File changeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> entries = asList(
- addedFileEntry("conf/server.conf", sha256(serverConf)),
- addedFileEntry("lib/server.jar", sha256(serverLib)));
+ File changeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> entries =
asList(addedFileEntry("conf/server.conf", sha256(serverConf)), addedFileEntry(
+ "lib/server.jar", sha256(serverLib)));
- assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
+ assertHeaderEquals(changeSet, createHeaders(def, COVERAGE));
assertFileEntriesMatch("A coverage change set should include files from
multiple, sibling directories",
entries, changeSet);
}
@@ -148,17 +146,16 @@ public class DriftDetectorTest extends DriftTest {
File subConfDir = mkdir(confDir, "subconf");
File server2Conf = createRandomFile(subConfDir, "server-2.conf");
- DriftDefinition config = driftConfiguration("nested-dirs-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("nested-dirs-test",
resourceDir.getAbsolutePath());
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File changeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> entries = asList(
- addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
- addedFileEntry("conf/subconf/server-2.conf",
sha256(server2Conf)));
+ File changeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> entries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
addedFileEntry(
+ "conf/subconf/server-2.conf", sha256(server2Conf)));
- assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
+ assertHeaderEquals(changeSet, createHeaders(def, COVERAGE));
assertFileEntriesMatch("A coverage change set should include files in nested
sub directories", entries,
changeSet);
}
@@ -169,23 +166,29 @@ public class DriftDetectorTest extends DriftTest {
File confDir = mkdir(resourceDir, "conf");
File serverConf = createRandomFile(confDir, "server.conf");
- DriftDefinition config = driftConfiguration("nothing-to-update",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("nothing-to-update",
resourceDir.getAbsolutePath());
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File changeSet = changeSet(config.getName(), COVERAGE);
+ File changeSet = changeSet(def.getName(), COVERAGE);
String originalHash = sha256(changeSet);
+ // Reset the schedule so that detection will run again the next time we call
+ // detection.run()
+ DriftDetectionSchedule schedule = scheduleQueue.remove(resourceId(), def);
+ schedule.resetSchedule();
+ scheduleQueue.addSchedule(schedule);
+
// Run the detector again. Note that nothing has changed so the snapshot should
// remain the same and no drift change set file should be generated.
detector.run();
String newHash = sha256(changeSet);
- assertEquals(newHash, originalHash, "The snapshot file should not have
changed since there was no drift.");
+ assertEquals(newHash, originalHash, "The snapshot file should not have
changed since there was no drift. ");
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
assertFalse(driftChangeSet.exists(), "A drift change set file should not
have been generated since there was "
+ "no drift");
@@ -193,63 +196,100 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
- public void skipScheduledThatHasConfigDisabled() throws Exception {
+ public void skipDetectionForScheduledThatIsDisabled() throws Exception {
detector.setDriftClient(new DriftClientTestStub() {
{
setBaseDir(resourceDir);
}
@Override
- public void sendChangeSetToServer(int resourceId, DriftDefinition
driftConfiguration,
- DriftChangeSetCategory type) {
+ public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
throw new RuntimeException("Should not invoke drift client when
drift configuration is disabled");
}
});
- DriftDefinition config = driftConfiguration("disabled-config-test",
resourceDir.getAbsolutePath());
- config.setEnabled(false);
+ DriftDefinition def = driftDefinition("disabled-config-test",
resourceDir.getAbsolutePath());
+ def.setEnabled(false);
File confDir = mkdir(resourceDir, "conf");
File server1Conf = new File(confDir, "server-1.conf");
touch(server1Conf);
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
}
@SuppressWarnings("unchecked")
@Test
+ public void skipDetectionWhenPreviousSnapshotFileExists() throws Exception {
+ // The presence of a previous snapshot file means that the server has
+ // not acknowledged that it has received and processed the change set.
+ DriftDefinition def = driftDefinition("previous-snapshot-test",
resourceDir.getAbsolutePath());
+
+ File confDir = mkdir(resourceDir, "conf");
+ createRandomFile(confDir, "server.conf");
+
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), def);
+ scheduleQueue.addSchedule(schedule);
+ detector.run();
+
+ // create some drift and generate a new snapshot
+ createRandomFile(confDir, "server-1.conf");
+ schedule.resetSchedule();
+ detector.run();
+
+ File snapshot = changeSet(def.getName(), COVERAGE);
+ String newHash = sha256(snapshot);
+ File previousSnapshot = previousChangeSet(def.getName());
+ String oldHash = sha256(previousSnapshot);
+
+ // create some drift and make sure drift detection does not run.
+ createRandomFile(confDir, "server-2.conf");
+ schedule.resetSchedule();
+ // Tell driftClient to throw an exception if detector attempts to send
+ // the change set report to the server. The detector should never call
+ // driftClient in this scenario.
+ driftClient.setFailingOnSendChangeSet(true);
+ detector.run();
+
+ assertEquals(sha256(snapshot), newHash, "The snapshot should not have
changed since the previous snapshot "
+ + "is still on disk.");
+ assertEquals(sha256(previousSnapshot), oldHash, "The previous snapshot
should not have changed since "
+ + "drift detection should not have run until the server acked the
previous snapshot.");
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
public void includeAddedFileInDriftChangeSet() throws Exception {
- DriftDefinition config = driftConfiguration("file-added-drift-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("file-added-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(config, COVERAGE));
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(def, COVERAGE));
writer.write(addedFileEntry("conf/server-1.conf",
sha256(server1Conf)));
writer.close();
// Create some drift
File server2Conf = createRandomFile(confDir, "server-2.conf");
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
List<FileEntry> driftEntries =
asList(addedFileEntry("conf/server-2.conf", sha256(server2Conf)));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> coverageEntries = asList(
- addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> coverageEntries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
addedFileEntry("conf/server-2.conf", sha256(server2Conf)));
// verify that the coverage change set was updated
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
coverageChangeSet);
}
@@ -257,13 +297,13 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeModifiedFileInDriftChangeSet() throws Exception {
- DriftDefinition config = driftConfiguration("file-modified-drift-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("file-modified-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
String oldHash = sha256(server1Conf);
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(config, COVERAGE));
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(def, COVERAGE));
writer.write(addedFileEntry("conf/server-1.conf", oldHash));
writer.close();
@@ -272,22 +312,22 @@ public class DriftDetectorTest extends DriftTest {
server1Conf = createRandomFile(confDir, "server-1.conf");
String newHash = sha256(server1Conf);
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
List<FileEntry> driftEntries =
asList(changedFileEntry("conf/server-1.conf", oldHash, newHash));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
List<FileEntry> coverageEntries =
asList(changedFileEntry("conf/server-1.conf", oldHash, newHash));
// verify that the coverage change set was updated
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
coverageChangeSet);
}
@@ -295,12 +335,12 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test(enabled = false)
public void includeFiledAddedInNewDirectoryInDriftChangeSet() throws Exception {
- DriftDefinition config = driftConfiguration("file-added-in-new-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("file-added-in-new-dir",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(config, COVERAGE));
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(def, COVERAGE));
writer.write(addedFileEntry("conf/server-1.conf",
sha256(server1Conf)));
writer.close();
@@ -308,24 +348,23 @@ public class DriftDetectorTest extends DriftTest {
File subconfDir = mkdir(confDir, "subconf");
File server2Conf = createRandomFile(subconfDir, "server-2.conf");
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
List<FileEntry> driftEntries =
asList(addedFileEntry("conf/subconf/server-2.conf", sha256(server2Conf)));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> coverageEntries = asList(
- addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> coverageEntries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)),
addedFileEntry("conf/subconf/server-2.conf",
sha256(server2Conf)));
// verify that the coverage change set was updated
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
coverageChangeSet);
}
@@ -333,7 +372,7 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeRemovedFileInDriftChangeSet() throws Exception {
- DriftDefinition config = driftConfiguration("file-removed-drift-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("file-removed-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -341,7 +380,7 @@ public class DriftDetectorTest extends DriftTest {
String server2ConfHash = sha256(server2Conf);
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(config, COVERAGE));
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(def, COVERAGE));
writer.write(addedFileEntry("conf/server-1.conf",
sha256(server1Conf)));
writer.write(addedFileEntry("conf/server-2.conf", server2ConfHash));
writer.close();
@@ -349,22 +388,22 @@ public class DriftDetectorTest extends DriftTest {
// create some drift
server2Conf.delete();
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
detector.run();
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
List<FileEntry> driftEntries =
asList(removedFileEntry("conf/server-2.conf", server2ConfHash));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
// verify that the coverage change set was updated
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
List<FileEntry> coverageEntries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)));
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
coverageChangeSet);
}
@@ -372,13 +411,13 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeFilesInRemovedDirectoryInDriftChangeSet() throws Exception {
- DriftDefinition config = driftConfiguration("dir-removed-test",
resourceDir.getAbsolutePath());
+ DriftDefinition def = driftDefinition("dir-removed-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
String server1Hash = sha256(server1Conf);
- ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(config, COVERAGE));
+ ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(),
createHeaders(def, COVERAGE));
writer.write(addedFileEntry("conf/server-1.conf", server1Hash));
writer.close();
@@ -386,22 +425,187 @@ public class DriftDetectorTest extends DriftTest {
server1Conf.delete();
confDir.delete();
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
+ detector.run();
+
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
+ List<FileEntry> driftEntries =
asList(removedFileEntry("conf/server-1.conf", server1Hash));
+
+ // verify that the drift change set was generated
+ assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
+ assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
+
+ // verify that the coverage change set was updated
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> coverageEntries = emptyList();
+
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
+ assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
+ coverageChangeSet);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void revertToPreviousSnapshotWhenSendingChangeSetFails() throws Exception {
+ DriftDefinition def = driftDefinition("revert-snapshot-test",
resourceDir.getAbsolutePath());
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), def);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server.conf");
+
+ scheduleQueue.addSchedule(schedule);
+ // generate the initial snapshot
+ detector.run();
+
+ // Now generate a drift change set
+ createRandomFile(confDir, "server-1.conf");
+ schedule.resetSchedule();
+ detector.run();
+
+ File changeSet = changeSet(def.getName(), COVERAGE);
+ String currentHash = sha256(changeSet);
+
+ // Need to delete the previous version snapshot file; otherwise, the
+ // next detection run will be skipped.
+ previousChangeSet(def.getName()).delete();
+
+ // generate some more drift, and fail on sending the change set
+ // to the server
+ createRandomFile(confDir, "server-2.conf");
+ schedule.resetSchedule();
+ driftClient.setFailingOnSendChangeSet(true);
+ try {
+ detector.run();
+ } catch (RuntimeException e) {
+ }
+
+ String newHash = sha256(changeSet);
+
+ assertEquals(newHash, currentHash, "The snapshot file should be reverted if
sending the new snapshot "
+ + "to the server fails.");
+ // The previous version file must be deleted on revert; otherwise, drift
+ // detection will not run for the schedule if the previous version file
+ // is found on disk.
+ assertFalse(previousChangeSet(def.getName()).exists(), "The copy of the
previous version snapshot file "
+ + "should be deleted once we have reverted back to it and have a new,
current snapsot file.");
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void purgeSnapshotWhenSendingInitialChangeSetFails() throws Exception {
+ // If we have just generated the initial change set and sending it to
+ // the server fails, then there is no prior snapshot version to which
+ // we can revert. We therefore need to purge the snapshot file and
+ // allow DriftDetector to simply regenerate the initial change set again.
+
+ DriftDefinition def = driftDefinition("purge-snapshot-test",
resourceDir.getAbsolutePath());
+
+ File confDir = mkdir(resourceDir, "conf");
+ createRandomFile(confDir, "server.conf");
+
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
+ driftClient.setFailingOnSendChangeSet(true);
+ try {
+ detector.run();
+ } catch (RuntimeException e) {
+ }
+
+ assertFalse(changeSet(def.getName(), COVERAGE).exists(), "Snapshot file
should be deleted when "
+ + "only the initial change set has been generated and sending change
send report to server fails");
+ }
+
+ @Test
+ public void ignoreFilesThatAreNotReadableForCoverageChangeSet() throws Exception {
+ DriftDefinition def = driftDefinition("nonreadable-files-coverage",
resourcesDir.getAbsolutePath());
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server-1.conf");
+ File server2Conf = createRandomFile(confDir, "server-2.conf");
+ assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
+
+ scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), def));
+ detector.run();
+
+ File changeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> entries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)));
+
+ assertHeaderEquals(changeSet, createHeaders(def, COVERAGE));
+ assertFileEntriesMatch("Files that are non-readable should be skipped but
other, readable file should still "
+ + "be included in the change set", entries, changeSet);
+ }
+
+ @Test
+ public void ignoreNewFilesThatAreNotReadableForDriftChangeSet() throws Exception {
+ DriftDefinition def = driftDefinition("nonreadable-files-drfit",
resourceDir.getAbsolutePath());
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), def);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server-1.conf");
+ String oldServer1Hash = sha256(server1Conf);
+
+ scheduleQueue.addSchedule(schedule);
+ detector.run();
+
+ // create some drift that includes a new file that is not readable
+ server1Conf.delete();
+ server1Conf = createRandomFile(confDir, "server-1.conf");
+ String newServer1Hash = sha256(server1Conf);
+
+ File server2Conf = createRandomFile(confDir, "server-2.conf");
+ assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
+
+ schedule.resetSchedule();
+ detector.run();
+
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
+ List<FileEntry> driftEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash, newServer1Hash));
+
+ // verify that the drift change set was generated
+ assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
+ assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
+
+ // verify that the coverage change set was updated
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
+ List<FileEntry> coverageEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash, newServer1Hash));
+
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
+ assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
+ coverageChangeSet);
+ }
+
+ @Test
+ public void markFileUnderDriftDetectionAsRemovedWhenItIsMadeNonReadable() throws
Exception {
+ DriftDefinition def = driftDefinition("file-made-nonreadable",
resourceDir.getAbsolutePath());
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), def);
+
+ File confDir = mkdir(resourceDir, "conf");
+ File server1Conf = createRandomFile(confDir, "server-1.conf");
+ String server1Hash = sha256(server1Conf);
+
+ scheduleQueue.addSchedule(schedule);
+ detector.run();
+
+ // make the file non-readable and run the detector again
+ assertTrue(server1Conf.setReadable(false), "Failed to make " +
server1Conf.getPath() + " write only");
+
+ schedule.resetSchedule();
detector.run();
- File driftChangeSet = changeSet(config.getName(), DRIFT);
+ File driftChangeSet = changeSet(def.getName(), DRIFT);
List<FileEntry> driftEntries =
asList(removedFileEntry("conf/server-1.conf", server1Hash));
// verify that the drift change set was generated
assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
+ assertHeaderEquals(driftChangeSet, createHeaders(def, DRIFT, 1));
assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
// verify that the coverage change set was updated
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
+ File coverageChangeSet = changeSet(def.getName(), COVERAGE);
List<FileEntry> coverageEntries = emptyList();
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
+ assertHeaderEquals(coverageChangeSet, createHeaders(def, COVERAGE, 1));
assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
coverageChangeSet);
}
@@ -409,8 +613,8 @@ public class DriftDetectorTest extends DriftTest {
void assertHeaderEquals(File changeSet, Headers expected) throws Exception {
ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new
FileReader(changeSet)));
Headers actual = reader.getHeaders();
- assertPropertiesMatch(expected, actual, "Headers for " +
changeSet.getPath() + " do not match " +
- "expected values");
+ assertPropertiesMatch(expected, actual, "Headers for " +
changeSet.getPath() + " do not match "
+ + "expected values");
}
void assertFileEntriesMatch(String msg, List<FileEntry> expected, File
changeSet) throws Exception {
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
index 696561a..319787c 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
@@ -19,6 +19,17 @@
package org.rhq.core.pc.drift;
+import static java.util.Arrays.asList;
+import static org.apache.commons.io.FileUtils.deleteDirectory;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.util.ZipUtil.unzipFile;
+import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
@@ -40,17 +51,6 @@ import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
-import static java.util.Arrays.asList;
-import static org.apache.commons.io.FileUtils.deleteDirectory;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.util.ZipUtil.unzipFile;
-import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-import static org.testng.Assert.fail;
-
public class DriftManagerTest extends DriftTest {
private File tmpDir;
@@ -75,32 +75,37 @@ public class DriftManagerTest extends DriftTest {
driftMgr = new TestDriftManager();
driftMgr.setConfiguration(pcConfig);
+ driftMgr.setChangeSetMgr(changeSetMgr);
}
@Test
public void writeChangeSetZipFileToChangeSetDirectory() throws Exception {
- final DriftDefinition config =
driftConfiguration("write-changeset-file", resourceDir.getAbsolutePath());
+ final DriftDefinition config = driftDefinition("write-changeset-file",
resourceDir.getAbsolutePath());
final File changeSetDir = changeSetDir(config.getName());
createRandomFile(changeSetDir, "changeset.txt");
setDriftServiceCallback(new DriftServiceCallback() {
@Override
public void execute() {
- assertThatZipFileExists(changeSetDir, "changeset_",
- "Expected to find change set zip file " +
- "in " + changeSetDir.getPath() + ". The file name
should follow the pattern " +
- "changeset_<integer_timestamp>.zip");
+ assertThatZipFileExists(changeSetDir, "changeset_",
"Expected to find change set zip file " + "in "
+ + changeSetDir.getPath() + ". The file name should follow the
pattern "
+ + "changeset_<integer_timestamp>.zip");
}
});
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+ DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
+ detectionSummary.setSchedule(schedule);
+ detectionSummary.setType(COVERAGE);
+
driftMgr.setChangeSetMgr(changeSetMgr);
- driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
- driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
+ driftMgr.getSchedulesQueue().addSchedule(schedule);
+ driftMgr.sendChangeSetToServer(detectionSummary);
}
@Test
public void sendChangeSetReportInZipFile() throws Exception {
- final DriftDefinition config =
driftConfiguration("send-changeset-in-zip", resourceDir.getAbsolutePath());
+ final DriftDefinition config = driftDefinition("send-changeset-in-zip",
resourceDir.getAbsolutePath());
final File changeSetDir = changeSetDir(config.getName());
final File changeSetFile = createRandomFile(changeSetDir,
"changeset.txt");
@@ -111,32 +116,31 @@ public class DriftManagerTest extends DriftTest {
}
});
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
+ DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
+ detectionSummary.setSchedule(schedule);
+ detectionSummary.setType(COVERAGE);
+
driftMgr.setChangeSetMgr(changeSetMgr);
driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
- driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
+ driftMgr.sendChangeSetToServer(detectionSummary);
}
@Test
- public void cleanUpAfterSendingChangeSetToServer() throws Exception {
- final DriftDefinition config =
driftConfiguration("send-changeset-in-zip", resourceDir.getAbsolutePath());
- final File changeSetDir = changeSetDir(config.getName());
- createRandomFile(changeSetDir, "changeset.txt");
-
- driftMgr.setChangeSetMgr(changeSetMgr);
- driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
- driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
-
- // clean up should not happen until after the input stream is closed. The remote
- // input stream is consumed asynchronously; so, we have to wait until the stream
- // is closed. We could otherwise disrupt the transmission of bits.
-
- File changeSetZip = assertThatZipFileExists(changeSetDir, "changeset_",
"Expected to find change set zip " +
- "zip file in " + changeSetDir.getPath() + ". The file name
should follow the pattern " +
- "changeset_<integer_timestamp>.zip");
+ public void cleanUpWhenServerAcksChangeSet() throws Exception {
+ DriftDefinition config =
driftDefinition("clean-up-when-server-acks-changeset",
resourceDir.getAbsolutePath());
+ File changeSetDir = changeSetDir(config.getName());
+ File snapshotFile = createRandomFile(changeSetDir, "changeset.txt");
+ File previousSnapshotFile = createRandomFile(changeSetDir,
"changeset.txt.previous");
+ File changeSetZipFile = createRandomFile(changeSetDir, "changeset_" +
System.currentTimeMillis() + ".zip");
- driftServerService.inputStream.close();
+ driftMgr.ackChangeSet(resourceId(), config.getName());
- assertFalse(changeSetZip.exists(), "The change set zip should be deleted
when the remote input stream is closed.");
+ assertTrue(snapshotFile.exists(), "Snapshot file should exist after server
acks change set");
+ assertFalse(previousSnapshotFile.exists(), "Previous version snapshot file
should be deleted when server "
+ + "acks change set");
+ assertEquals(findChangeSetZipFiles(changeSetDir).size(), 0, "All change set
zip files should be deleted when "
+ + "server acks change set");
}
@Test
@@ -151,9 +155,9 @@ public class DriftManagerTest extends DriftTest {
setDriftServiceCallback(new DriftServiceCallback() {
@Override
public void execute() {
- assertThatZipFileExists(changeSetDir, "content_",
"Expected to find content zip file in " +
- changeSetDir.getPath() + ". The file name should follow the
pattern " +
- "content_<integer_timestamp>.zip");
+ assertThatZipFileExists(changeSetDir, "content_",
"Expected to find content zip file in "
+ + changeSetDir.getPath() + ". The file name should follow the
pattern "
+ + "content_<integer_timestamp>.zip");
}
});
@@ -177,48 +181,42 @@ public class DriftManagerTest extends DriftTest {
});
driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir);
+
+ // verify that the content directory is purged
+ assertThatDirectoryIsEmpty(contentDir);
}
@Test
- public void cleanUpAfterSendingContentToServer() throws Exception {
- String configName = "clean-up-after-sending-content";
+ public void cleanUpWhenServerAcksChangeSetContent() throws Exception {
+ String configName = "cleanup-when-server-acks-content";
File changeSetDir = changeSetDir(configName);
File contentDir = mkdir(changeSetDir, "content");
- createRandomFile(contentDir, "content-1");
- createRandomFile(contentDir, "content-2");
-
- driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir);
-
- // clean up should not happen until after the input stream is closed. The remote
- // input stream is consumed asynchronously; so, we have to wait until the stream
- // is closed. We could otherwise disrupt the transmission of bits.
- File contentZipFile = assertThatZipFileExists(changeSetDir,
"content_",
- "Expected to find content zip file in " +
- changeSetDir.getPath() + ". The file name should have a pattern of
content_integer_timestamp>.zip");
+ String token = Long.toString(System.currentTimeMillis());
+ File contentZipFile = createRandomFile(changeSetDir, "content_" + token
+ ".zip");
- driftServerService.inputStream.close();
+ driftMgr.ackChangeSetContent(resourceId(), configName, token);
- assertFalse(contentZipFile.exists(), "The content zip should be deleted when
the remote input stream is closed");
- assertThatDirectoryIsEmpty(contentDir);
+ assertFalse(contentZipFile.exists(), "Content zip file should be purged
after server sends content ack");
}
@Test
public void unschedulingDetectionRemovesScheduleFromQueue() throws Exception {
- DriftDefinition config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftDefinition("remove-from-queue",
resourceDir.getAbsolutePath());
driftMgr.scheduleDriftDetection(resourceId(), config);
- driftMgr.scheduleDriftDetection(resourceId() + 5,
driftConfiguration("another-config", "."));
+ driftMgr.scheduleDriftDetection(resourceId() + 5,
driftDefinition("another-config", "."));
driftMgr.unscheduleDriftDetection(resourceId(), config);
- assertFalse(driftMgr.getSchedulesQueue().contains(resourceId(), config),
- new DriftDetectionSchedule(resourceId(), config) + " should have been
removed from the schedule queue");
+ assertFalse(driftMgr.getSchedulesQueue().contains(resourceId(), config), new
DriftDetectionSchedule(
+ resourceId(), config)
+ + " should have been removed from the schedule queue");
}
@Test
public void unschedulingDetectionRemovesDriftConfigFromResourceContainer() throws
Exception {
- DriftDefinition config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
- DriftDefinition config2 = driftConfiguration("do-not-remove",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftDefinition("remove-from-queue",
resourceDir.getAbsolutePath());
+ DriftDefinition config2 = driftDefinition("do-not-remove",
resourceDir.getAbsolutePath());
driftMgr.scheduleDriftDetection(resourceId(), config);
driftMgr.scheduleDriftDetection(resourceId(), config2);
@@ -232,7 +230,7 @@ public class DriftManagerTest extends DriftTest {
@Test
public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsNotActive()
throws Exception {
- DriftDefinition config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftDefinition("delete-changeset-dir",
resourceDir.getAbsolutePath());
File changeSetDir = changeSetDir(config.getName());
File contentDir = mkdir(changeSetDir, "content");
@@ -247,7 +245,7 @@ public class DriftManagerTest extends DriftTest {
@Test
public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsDeactivated()
throws Exception {
- DriftDefinition config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftDefinition("delete-changeset-dir",
resourceDir.getAbsolutePath());
File changeSetDir = changeSetDir(config.getName());
File contentDir = mkdir(changeSetDir, "content");
@@ -258,12 +256,22 @@ public class DriftManagerTest extends DriftTest {
driftMgr.getSchedulesQueue().getNextSchedule();
driftMgr.unscheduleDriftDetection(resourceId(), config);
- assertTrue(changeSetDir.exists(), "The change set directory should not be
deleted while the schedule is " +
- "still active.");
+ assertTrue(changeSetDir.exists(), "The change set directory should not be
deleted while the schedule is "
+ + "still active.");
driftMgr.getSchedulesQueue().deactivateSchedule();
- assertFalse(changeSetDir.exists(), "The change set directory should have
been deleted after the schedule is " +
- "deactivated.");
+ assertFalse(changeSetDir.exists(), "The change set directory should have
been deleted after the schedule is "
+ + "deactivated.");
+ }
+
+ private List<File> findChangeSetZipFiles(File dir) {
+ File[] files = dir.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.startsWith("changeset_") &&
name.endsWith(".zip");
+ }
+ });
+ return asList(files);
}
/**
@@ -295,8 +303,8 @@ public class DriftManagerTest extends DriftTest {
String expectedHash = sha256(expectedFile);
String actualHash = sha256(actualFile);
- assertEquals(actualHash, expectedHash, "The zip file content is wrong.
The SHA-256 hash does not match " +
- "for " + expectedFile.getName());
+ assertEquals(actualHash, expectedHash, "The zip file content is wrong.
The SHA-256 hash does not match "
+ + "for " + expectedFile.getName());
}
}
@@ -351,6 +359,8 @@ public class DriftManagerTest extends DriftTest {
private static class TestDriftServerService implements DriftServerService {
public int resourceId;
+ public String driftConfigName;
+ public String token;
public long fileSize;
public InputStream inputStream;
@@ -368,8 +378,11 @@ public class DriftManagerTest extends DriftTest {
}
@Override
- public void sendFilesZip(int resourceId, long zipSize, InputStream zipStream) {
+ public void sendFilesZip(int resourceId, String driftConfigName, String token,
long zipSize,
+ InputStream zipStream) {
this.resourceId = resourceId;
+ this.driftConfigName = driftConfigName;
+ this.token = token;
fileSize = zipSize;
inputStream = zipStream;
@@ -384,7 +397,7 @@ public class DriftManagerTest extends DriftTest {
}
@Override
- public DriftSnapshot getCurrentSnapshot(int driftConfigurationId) {
+ public DriftSnapshot getCurrentSnapshot(int driftDefinitionId) {
return null;
}
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
index ad32251..1d39499 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
@@ -19,6 +19,13 @@
package org.rhq.core.pc.drift;
+import static java.util.Arrays.asList;
+import static org.apache.commons.io.FileUtils.deleteDirectory;
+import static org.apache.commons.io.IOUtils.write;
+import static org.apache.commons.io.IOUtils.writeLines;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static
org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem;
+
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
@@ -34,13 +41,6 @@ import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.util.MessageDigestGenerator;
-import static java.util.Arrays.asList;
-import static org.apache.commons.io.FileUtils.deleteDirectory;
-import static org.apache.commons.io.IOUtils.write;
-import static org.apache.commons.io.IOUtils.writeLines;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static
org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem;
-
/**
* A base test class that provides a framework for drift related tests. DriftTest sets
up
* directories for change sets and for fake resources. Before each test method is run, a
@@ -104,10 +104,10 @@ public class DriftTest {
protected File resourceDir;
/**
- * The default interval assigned to drift configurations created using
- * {@link #driftConfiguration(String, String)}
+ * The default interval assigned to drift definitions created using
+ * {@link #driftDefinition(String, String)}
*/
- protected long defaultInterval = 1800L; // 30 minutes;
+ protected long defaultInterval = 1800L; // 30 minutes;
private MessageDigestGenerator digestGenerator;
@@ -178,11 +178,11 @@ public class DriftTest {
}
/**
- * Returns the change set file for the specified drift configuration for the
resource
+ * Returns the change set file for the specified drift definition for the resource
* with the id that can be obtained from {@link #resourceId}. The type argument
* determines whether a coverage or drift change set file is returned.
*
- * @param config The drift configuration name
+ * @param config The drift definition name
* @param type Determines whether a coverage or drift change set file is to be
returned
* @return The change set file
* @throws IOException
@@ -192,10 +192,10 @@ public class DriftTest {
}
/**
- * Returns the previous snapshot file for the specified drift configuration for the
+ * Returns the previous snapshot file for the specified drift definition for the
* resource with the id that can be obtained from {@link #resourceId()}.
*
- * @param config The drift configuration name
+ * @param config The drift definition name
* @return The previous snapshot file
* @throws Exception
*/
@@ -247,11 +247,11 @@ public class DriftTest {
* used as the context for the basedir which means the path specified is used as is.
* The interval property is set to {@link #defaultInterval}.
*
- * @param name The configuration name
+ * @param name The definition name
* @param basedir An absolute path of the base directory
- * @return The drift configuration object
+ * @return The drift definition object
*/
- protected DriftDefinition driftConfiguration(String name, String basedir) {
+ protected DriftDefinition driftDefinition(String name, String basedir) {
DriftDefinition config = new DriftDefinition(new Configuration());
config.setName(name);
config.setBasedir(new DriftDefinition.BaseDirectory(fileSystem, basedir));
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
index 0e57f71..eb1df17 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
@@ -37,6 +37,7 @@ import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.util.PageList;
+import org.rhq.core.domain.util.PageOrdering;
public class DriftServerServiceImpl implements DriftServerService {
@Override
@@ -50,10 +51,11 @@ public class DriftServerServiceImpl implements DriftServerService {
}
@Override
- public void sendFilesZip(int resourceId, long zipSize, InputStream zipStream) {
+ public void sendFilesZip(int resourceId, String driftDefinitionName, String token,
long zipSize,
+ InputStream zipStream) {
try {
DriftManagerLocal driftManager = getDriftManager();
- driftManager.addFiles(resourceId, zipSize, zipStream);
+ driftManager.addFiles(resourceId, driftDefinitionName, token, zipSize,
zipStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -66,13 +68,13 @@ public class DriftServerServiceImpl implements DriftServerService {
criteria.fetchConfiguration(true);
Subject overlord = getSubjectManager().getOverlord();
- PageList<DriftDefinition> configs =
getDriftManager().findDriftDefinitionsByCriteria(overlord, criteria);
+ PageList<DriftDefinition> definitions =
getDriftManager().findDriftDefinitionsByCriteria(overlord, criteria);
Map<Integer, List<DriftDefinition>> map = new HashMap<Integer,
List<DriftDefinition>>();
for (Integer resourceId : resourceIds) {
map.put(resourceId, new ArrayList<DriftDefinition>());
}
- for (DriftDefinition c : configs) {
+ for (DriftDefinition c : definitions) {
List<DriftDefinition> list = map.get(c.getResource().getId());
list.add(c);
map.put(c.getResource().getId(), list);
@@ -82,9 +84,10 @@ public class DriftServerServiceImpl implements DriftServerService {
}
@Override
- public DriftSnapshot getCurrentSnapshot(int driftConfigurationId) {
+ public DriftSnapshot getCurrentSnapshot(int driftDefinitionId) {
DriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
- criteria.addFilterDriftDefinitionId(driftConfigurationId);
+ criteria.addFilterDriftDefinitionId(driftDefinitionId);
+ criteria.addSortVersion(PageOrdering.ASC);
Subject overlord = getSubjectManager().getOverlord();
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
index 575fd74..54d5967 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
@@ -299,7 +299,7 @@ public class JPADriftServerBean implements JPADriftServerLocal {
AgentClient agentClient =
agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
DriftAgentService service = agentClient.getDriftAgentService();
- service.ackChangeSet(resourceId,
reader.getHeaders().getDriftConfigurationName());
+ service.ackChangeSet(resourceId,
reader.getHeaders().getDriftDefinitionName());
// send a message to the agent requesting the empty JPADriftFile
content
if (!emptyDriftFiles.isEmpty()) {
commit e68f4218873c954e24a6c15939b7d89cf7c276bc
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Thu Sep 29 20:13:56 2011 -0400
First pass at Drift Carousel view, this is a work in progress!
- New generic Carousel base class view, somewhat analogous to Table
- New DriftCarousel view which serves as the default detail view for a
drift definition.
- Tweaked title handling in Table as it was confusing, now Carousel and
Table title handling is basically the same. This touched a few files
with minor refactor changes.
- It was too confusing, so I pushed terminology change from Drift
Configuration to Drift [Detection] Definition through the code layer
(painfully huge refactor). Previously it was only pushed through the
presentation layer (I18N mainly). DB layer is still a TODO.
- note, a few classname changes were part of this
diff --git
a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java
b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java
index b8c383a..5da6078 100644
--- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java
+++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java
@@ -95,8 +95,8 @@ public class ChangeSetReaderImpl implements ChangeSetReader {
headers = new Headers();
try {
headers.setResourceId(Integer.parseInt(reader.readLine()));
- headers.setDriftCofigurationId(Integer.parseInt(reader.readLine()));
- headers.setDriftConfigurationName(reader.readLine());
+ headers.setDriftDefinitionId(Integer.parseInt(reader.readLine()));
+ headers.setDriftDefinitionName(reader.readLine());
headers.setBasedir(reader.readLine());
headers.setType(DriftChangeSetCategory.fromCode(reader.readLine()));
headers.setVersion(Integer.parseInt(reader.readLine()));
diff --git
a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java
b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java
index fb6d7c3..c0fdf50 100644
--- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java
+++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java
@@ -47,8 +47,8 @@ public class ChangeSetWriterImpl implements ChangeSetWriter {
private void writeHeaders(Headers headers) throws IOException {
writer.write(headers.getResourceId() + "\n");
- writer.write(headers.getDriftCofigurationId() + "\n");
- writer.write(headers.getDriftConfigurationName() + "\n");
+ writer.write(headers.getDriftDefinitionId() + "\n");
+ writer.write(headers.getDriftDefinitionName() + "\n");
writer.write(headers.getBasedir() + "\n");
writer.write(headers.getType().code() + "\n");
writer.write(headers.getVersion() + "\n");
diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/Headers.java
b/modules/common/drift/src/main/java/org/rhq/common/drift/Headers.java
index f482ccb..fb13e94 100644
--- a/modules/common/drift/src/main/java/org/rhq/common/drift/Headers.java
+++ b/modules/common/drift/src/main/java/org/rhq/common/drift/Headers.java
@@ -32,9 +32,9 @@ public class Headers implements Serializable {
private static final long serialVersionUID = 1L;
- private int driftCofigurationId;
+ private int driftDefinitionId;
- private String driftConfigurationName;
+ private String driftDefinitionName;
private String basedir;
@@ -59,31 +59,31 @@ public class Headers implements Serializable {
}
/**
- * @return The id of the drift configuration to which the change set belongs.
+ * @return The id of the drift definition to which the change set belongs.
*/
- public int getDriftCofigurationId() {
- return driftCofigurationId;
+ public int getDriftDefinitionId() {
+ return driftDefinitionId;
}
/**
- * @param driftCofigurationId The id of the drift configuration to which the change
set belongs
+ * @param driftDefinitionId The id of the drift def to which the change set belongs
*/
- public void setDriftCofigurationId(int driftCofigurationId) {
- this.driftCofigurationId = driftCofigurationId;
+ public void setDriftDefinitionId(int driftDefinitionId) {
+ this.driftDefinitionId = driftDefinitionId;
}
/**
- * @return The name of the drift configuration to which the change set belongs
+ * @return The name of the drift def to which the change set belongs
*/
- public String getDriftConfigurationName() {
- return driftConfigurationName;
+ public String getDriftDefinitionName() {
+ return driftDefinitionName;
}
/**
- * @param name The name of the drift configuration to which the change set belongs
+ * @param name The name of the drift def to which the change set belongs
*/
- public void setDriftConfigurationName(String name) {
- driftConfigurationName = name;
+ public void setDriftDefinitionName(String name) {
+ driftDefinitionName = name;
}
/**
diff --git
a/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java
b/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java
index 6df07f0..5df79fa 100644
---
a/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java
+++
b/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java
@@ -31,8 +31,8 @@ public class ChangeSetReaderImplTest {
Headers actualHeaders = reader.getHeaders();
Headers expectedHeaders = new Headers();
expectedHeaders.setResourceId(1);
- expectedHeaders.setDriftCofigurationId(1);
- expectedHeaders.setDriftConfigurationName("file-added-test");
+ expectedHeaders.setDriftDefinitionId(1);
+ expectedHeaders.setDriftDefinitionName("file-added-test");
expectedHeaders.setBasedir("myresource");
expectedHeaders.setType(COVERAGE);
expectedHeaders.setVersion(1);
@@ -63,8 +63,8 @@ public class ChangeSetReaderImplTest {
Headers actualHeaders = reader.getHeaders();
Headers expectedHeaders = new Headers();
expectedHeaders.setResourceId(1);
- expectedHeaders.setDriftCofigurationId(1);
- expectedHeaders.setDriftConfigurationName("file-removed-test");
+ expectedHeaders.setDriftDefinitionId(1);
+ expectedHeaders.setDriftDefinitionName("file-removed-test");
expectedHeaders.setBasedir("myresource");
expectedHeaders.setType(COVERAGE);
expectedHeaders.setVersion(1);
@@ -96,8 +96,8 @@ public class ChangeSetReaderImplTest {
Headers actualHeaders = reader.getHeaders();
Headers expectedHeaders = new Headers();
expectedHeaders.setResourceId(1);
- expectedHeaders.setDriftCofigurationId(1);
- expectedHeaders.setDriftConfigurationName("file-changed-test");
+ expectedHeaders.setDriftDefinitionId(1);
+ expectedHeaders.setDriftDefinitionName("file-changed-test");
expectedHeaders.setBasedir("myresource");
expectedHeaders.setType(COVERAGE);
expectedHeaders.setVersion(1);
@@ -128,8 +128,8 @@ public class ChangeSetReaderImplTest {
Headers actualHeaders = reader.getHeaders();
Headers expectedHeaders = new Headers();
expectedHeaders.setResourceId(1);
- expectedHeaders.setDriftCofigurationId(1);
- expectedHeaders.setDriftConfigurationName("file-name-test");
+ expectedHeaders.setDriftDefinitionId(1);
+ expectedHeaders.setDriftDefinitionName("file-name-test");
expectedHeaders.setBasedir("myresource");
expectedHeaders.setType(COVERAGE);
expectedHeaders.setVersion(1);
diff --git
a/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java
b/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java
index 40fff48..251021a 100644
---
a/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java
+++
b/modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java
@@ -63,8 +63,8 @@ public class ChangeSetWriterImplTest {
Headers headers = new Headers();
headers.setResourceId(1);
- headers.setDriftCofigurationId(2);
- headers.setDriftConfigurationName("add-file-test");
+ headers.setDriftDefinitionId(2);
+ headers.setDriftDefinitionName("add-file-test");
headers.setBasedir(resourceDir.getAbsolutePath());
headers.setType(COVERAGE);
headers.setVersion(1);
@@ -91,8 +91,8 @@ public class ChangeSetWriterImplTest {
File changeSetFile = new File(changeSetsDir, "removed-file-test");
Headers headers = new Headers();
headers.setResourceId(1);
- headers.setDriftCofigurationId(2);
- headers.setDriftConfigurationName("removed-file-test");
+ headers.setDriftDefinitionId(2);
+ headers.setDriftDefinitionName("removed-file-test");
headers.setBasedir(resourceDir.getAbsolutePath());
headers.setType(COVERAGE);
headers.setVersion(1);
@@ -119,8 +119,8 @@ public class ChangeSetWriterImplTest {
File changeSetFile = new File(changeSetsDir, "changed-file-test");
Headers headers = new Headers();
headers.setResourceId(1);
- headers.setDriftCofigurationId(2);
- headers.setDriftConfigurationName("changed-file-test");
+ headers.setDriftDefinitionId(2);
+ headers.setDriftDefinitionName("changed-file-test");
headers.setBasedir(resourceDir.getAbsolutePath());
headers.setType(COVERAGE);
headers.setVersion(1);
@@ -149,9 +149,9 @@ public class ChangeSetWriterImplTest {
void assertHeadersEquals(List<String> lines, Headers headers) {
assertEquals(lines.get(0), Integer.toString(headers.getResourceId()), "The
first header entry should be the " +
"resurce id.");
- assertEquals(lines.get(1), Integer.toString(headers.getDriftCofigurationId()),
"The second header entry " +
+ assertEquals(lines.get(1), Integer.toString(headers.getDriftDefinitionId()),
"The second header entry " +
"should be the drift configuration id.");
- assertEquals(lines.get(2), headers.getDriftConfigurationName(), "The third
header entry should be the drift " +
+ assertEquals(lines.get(2), headers.getDriftDefinitionName(), "The third
header entry should be the drift " +
"configuration name.");
assertEquals(lines.get(3), headers.getBasedir(), "The fourth header entry
should be the drift configuration " +
"base directory.");
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
index d58c766..c121cfa 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/drift/DriftAgentService.java
@@ -22,7 +22,7 @@ package org.rhq.core.clientapi.agent.drift;
import java.util.List;
import org.rhq.common.drift.Headers;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
/**
@@ -67,7 +67,7 @@ public interface DriftAgentService {
* @param driftConfiguration Specifies how the detection should be carried out. This
* includes any filtering rules that should be applied.
*/
- void detectDrift(int resourceId, DriftConfiguration driftConfiguration);
+ void detectDrift(int resourceId, DriftDefinition driftConfiguration);
/**
* Requests that the agent start performing drift detection for a resource with the
@@ -80,9 +80,9 @@ public interface DriftAgentService {
*
* @param resourceId The id of the resource for which the request is being made
* @param driftConfiguration Specifies how and when the detection should be carried
out
- * @see DriftConfiguration
+ * @see DriftDefinition
*/
- void scheduleDriftDetection(int resourceId, DriftConfiguration driftConfiguration);
+ void scheduleDriftDetection(int resourceId, DriftDefinition driftConfiguration);
/**
* Requests that the agent stop performing the specified drift detection for the
resource. (In
@@ -90,9 +90,9 @@ public interface DriftAgentService {
*
* @param resourceId The id of the resource for which the request is being made
* @param driftConfiguration The doomed drift config
- * @see DriftConfiguration
+ * @see DriftDefinition
*/
- void unscheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration);
+ void unscheduleDriftDetection(int resourceId, DriftDefinition driftConfiguration);
/**
* Requests that the agent update its processing of the specified driftConfiguration.
The filters
@@ -100,9 +100,9 @@ public interface DriftAgentService {
*
* @param resourceId The id of the resource for which the request is being made
* @param driftConfiguration The updated driftConfiguration.
- * @see DriftConfiguration
+ * @see DriftDefinition
*/
- void updateDriftDetection(int resourceId, DriftConfiguration driftConfiguration);
+ void updateDriftDetection(int resourceId, DriftDefinition driftConfiguration);
/**
* This method is invoked to inform the agent that the server has successfully
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataParser.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataParser.java
index e856e2b..08b2180 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataParser.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataParser.java
@@ -499,7 +499,7 @@ public class PluginMetadataParser {
+ descriptor.getName() + "]");
}
driftConfigNames.add(descriptor.getName());
-
resourceType.addDriftConfigurationTemplate(driftMetadataParser.parseDriftMetadata(descriptor));
+
resourceType.addDriftDefinitionTemplate(driftMetadataParser.parseDriftMetadata(descriptor));
}
driftConfigNames = null; // don't need this anymore
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
index 4f1deef..c7c88ef 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/drift/DriftServerService.java
@@ -25,7 +25,7 @@ import java.util.Map;
import java.util.Set;
import org.rhq.core.communications.command.annotation.Asynchronous;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftSnapshot;
/**
@@ -117,7 +117,7 @@ public interface DriftServerService {
@Asynchronous(guaranteedDelivery = true)
void sendFilesZip(int resourceId, String driftConfigName, String token, long zipSize,
InputStream zipStream);
- Map<Integer, List<DriftConfiguration>>
getDriftConfigurations(Set<Integer> resourceIds);
+ Map<Integer, List<DriftDefinition>>
getDriftDefinitions(Set<Integer> resourceIds);
DriftSnapshot getCurrentSnapshot(int driftConfigurationId);
}
diff --git
a/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java
b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java
index 7adf6fa..6f134d2 100644
---
a/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java
+++
b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java
@@ -40,9 +40,9 @@ import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
import org.rhq.core.domain.configuration.definition.ConfigurationFormat;
import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftConfigurationDefinition;
-import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
+import org.rhq.core.domain.drift.DriftDefinition.BaseDirectory;
import org.rhq.core.domain.drift.Filter;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
import org.rhq.core.domain.resource.ResourceType;
@@ -379,7 +379,7 @@ public class PluginMetadataParserTest {
verifyDriftConfiguration(descriptor, "TestServer", "test1",
new AssertDriftTemplateRunnable() {
@Override
public void assertDriftTemplate(ConfigurationTemplate driftTemplate) throws
Exception {
- DriftConfiguration dc = new
DriftConfiguration(driftTemplate.getConfiguration());
+ DriftDefinition dc = new
DriftDefinition(driftTemplate.getConfiguration());
BaseDirectory basedir = dc.getBasedir();
assertEquals(basedir.getValueContext(),
BaseDirValueContext.pluginConfiguration, "Bad value context");
assertEquals(basedir.getValueName(), "var.lib.test1", "Bad
value name");
@@ -638,7 +638,7 @@ public class PluginMetadataParserTest {
@Override
public void assertDriftTemplate(ConfigurationTemplate driftTemplate) throws
Exception {
Configuration config = driftTemplate.getConfiguration();
- DriftConfiguration dconfig = new DriftConfiguration(config);
+ DriftDefinition dconfig = new DriftDefinition(config);
assertEquals(dconfig.getInterval(), 11111L);
assertEquals(dconfig.getBasedir().getValueContext(),
BaseDirValueContext.pluginConfiguration);
@@ -678,7 +678,7 @@ public class PluginMetadataParserTest {
@Override
public void assertDriftTemplate(ConfigurationTemplate driftTemplate) throws
Exception {
Configuration config = driftTemplate.getConfiguration();
- DriftConfiguration dconfig = new DriftConfiguration(config);
+ DriftDefinition dconfig = new DriftDefinition(config);
assertEquals(dconfig.getInterval(), 22222L);
assertEquals(dconfig.getBasedir().getValueContext(),
BaseDirValueContext.resourceConfiguration);
@@ -718,7 +718,7 @@ public class PluginMetadataParserTest {
@Override
public void assertDriftTemplate(ConfigurationTemplate driftTemplate) throws
Exception {
Configuration config = driftTemplate.getConfiguration();
- DriftConfiguration dconfig = new DriftConfiguration(config);
+ DriftDefinition dconfig = new DriftDefinition(config);
assertEquals(dconfig.getInterval(), 33333L);
assertEquals(dconfig.getBasedir().getValueContext(),
BaseDirValueContext.measurementTrait);
@@ -780,7 +780,7 @@ public class PluginMetadataParserTest {
@Override
public void assertDriftTemplate(ConfigurationTemplate driftTemplate) throws
Exception {
Configuration config = driftTemplate.getConfiguration();
- DriftConfiguration dconfig = new DriftConfiguration(config);
+ DriftDefinition dconfig = new DriftDefinition(config);
assertEquals(dconfig.getInterval(), 44444L);
assertEquals(dconfig.getBasedir().getValueContext(),
BaseDirValueContext.fileSystem);
@@ -805,7 +805,7 @@ public class PluginMetadataParserTest {
Map<String, PluginMetadataParser> parsersByPlugin = new HashMap<String,
PluginMetadataParser>(0);
PluginMetadataParser parser = new PluginMetadataParser(descriptor,
parsersByPlugin);
ResourceType resourceType = findResourceType(parser, resourceTypeName);
- Set<ConfigurationTemplate> driftTemplates =
resourceType.getDriftConfigurationTemplates();
+ Set<ConfigurationTemplate> driftTemplates =
resourceType.getDriftDefinitionTemplates();
ConfigurationTemplate driftTemplate = null;
for (ConfigurationTemplate template : driftTemplates) {
if (template.getName().equals(driftConfigName)) {
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetCriteria.java
index a3c61a6..8a7df2d 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetCriteria.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetCriteria.java
@@ -58,9 +58,9 @@ public interface DriftChangeSetCriteria extends BaseCriteria {
Integer getFilterResourceId();
- void addFilterDriftConfigurationId(Integer filterDriftConfigId);
+ void addFilterDriftDefinitionId(Integer filterDriftDefId);
- Integer getFilterDriftConfigurationId();
+ Integer getFilterDriftDefintionId();
void addFilterCategory(DriftChangeSetCategory filterCategory);
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftConfigurationCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftConfigurationCriteria.java
deleted file mode 100644
index e2ed959..0000000
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftConfigurationCriteria.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.core.domain.criteria;
-
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.util.CriteriaUtils;
-import org.rhq.core.domain.util.PageOrdering;
-
-/**
- * RHQ Criteria query support for DriftConfiguration. This is not drift server plugin
supported, DriftConfiguration
- * is a native entity.
- *
- * @author Jay Shaughnessy
- */
-@XmlRootElement
-(a)XmlAccessorType(XmlAccessType.FIELD)
-@SuppressWarnings("unused")
-public class DriftConfigurationCriteria extends Criteria {
- private static final long serialVersionUID = 1L;
-
- private Integer filterId;
- private String filterName;
- private List<Integer> filterResourceIds; // needs override
-
- private Boolean fetchConfiguration;
- private Boolean fetchResource;
-
- private PageOrdering sortName;
-
- public DriftConfigurationCriteria() {
- filterOverrides.put("resourceIds", "resource.id IN ( ? )");
- }
-
- @Override
- public Class<DriftConfiguration> getPersistentClass() {
- return DriftConfiguration.class;
- }
-
- public void addFilterId(String filterId) {
- if (filterId != null) {
- this.filterId = Integer.parseInt(filterId);
- }
- }
-
- public void addFilterName(String name) {
- this.filterName = name;
- }
-
- public void addFilterResourceIds(Integer... filterResourceIds) {
- this.filterResourceIds = CriteriaUtils.getListIgnoringNulls(filterResourceIds);
- }
-
- public void fetchConfiguration(Boolean fetchConfiguration) {
- this.fetchConfiguration = fetchConfiguration;
- }
-
- public void fetchResource(Boolean fetchResource) {
- this.fetchResource = fetchResource;
- }
-
- public void addSortName(PageOrdering sortName) {
- addSortField("name");
- this.sortName = sortName;
- }
-}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftDefinitionCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftDefinitionCriteria.java
new file mode 100644
index 0000000..d5bb40c
--- /dev/null
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftDefinitionCriteria.java
@@ -0,0 +1,85 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.core.domain.criteria;
+
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.util.CriteriaUtils;
+import org.rhq.core.domain.util.PageOrdering;
+
+/**
+ * RHQ Criteria query support for @{link DriftDefinition}. This is not drift server
plugin supported,
+ * DriftDefintition is a native entity.
+ *
+ * @author Jay Shaughnessy
+ */
+@XmlRootElement
+(a)XmlAccessorType(XmlAccessType.FIELD)
+@SuppressWarnings("unused")
+public class DriftDefinitionCriteria extends Criteria {
+ private static final long serialVersionUID = 1L;
+
+ private Integer filterId;
+ private String filterName;
+ private List<Integer> filterResourceIds; // needs override
+
+ private Boolean fetchConfiguration;
+ private Boolean fetchResource;
+
+ private PageOrdering sortName;
+
+ public DriftDefinitionCriteria() {
+ filterOverrides.put("resourceIds", "resource.id IN ( ? )");
+ }
+
+ @Override
+ public Class<DriftDefinition> getPersistentClass() {
+ return DriftDefinition.class;
+ }
+
+ public void addFilterId(Integer filterId) {
+ this.filterId = filterId;
+ }
+
+ public void addFilterName(String name) {
+ this.filterName = name;
+ }
+
+ public void addFilterResourceIds(Integer... filterResourceIds) {
+ this.filterResourceIds = CriteriaUtils.getListIgnoringNulls(filterResourceIds);
+ }
+
+ public void fetchConfiguration(Boolean fetchConfiguration) {
+ this.fetchConfiguration = fetchConfiguration;
+ }
+
+ public void fetchResource(Boolean fetchResource) {
+ this.fetchResource = fetchResource;
+ }
+
+ public void addSortName(PageOrdering sortName) {
+ addSortField("name");
+ this.sortName = sortName;
+ }
+}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java
index 073d89e..a4b4255 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java
@@ -52,7 +52,7 @@ public class GenericDriftChangeSetCriteria implements Serializable,
DriftChangeS
private Integer filterResourceId;
- private Integer filterDriftConfigId;
+ private Integer filterDriftDefId;
private DriftChangeSetCategory filterCategory;
@@ -133,13 +133,13 @@ public class GenericDriftChangeSetCriteria implements Serializable,
DriftChangeS
}
@Override
- public void addFilterDriftConfigurationId(Integer filterDriftConfigId) {
- this.filterDriftConfigId = filterDriftConfigId;
+ public void addFilterDriftDefinitionId(Integer filterDriftDefId) {
+ this.filterDriftDefId = filterDriftDefId;
}
@Override
- public Integer getFilterDriftConfigurationId() {
- return filterDriftConfigId;
+ public Integer getFilterDriftDefintionId() {
+ return filterDriftDefId;
}
@Override
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java
index a7262a2..c522996 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java
@@ -41,7 +41,7 @@ public class JPADriftChangeSetCriteria extends Criteria implements
DriftChangeSe
private Integer filterId;
private Integer filterInitial; // needs override
private Integer filterResourceId; // needs override
- private Integer filterDriftConfigurationId; // needs override
+ private Integer filterDriftDefinitionId; // needs override
private Integer filterVersion;
private Integer filterStartVersion;
private Integer filterEndVersion;
@@ -49,7 +49,7 @@ public class JPADriftChangeSetCriteria extends Criteria implements
DriftChangeSe
private Long filterCreatedBefore;
private DriftChangeSetCategory filterCategory;
private Boolean fetchDrifts;
- private Boolean fetchDriftConfiguration;
+ private Boolean fetchDriftDefinition;
private PageOrdering sortVersion;
@@ -64,13 +64,13 @@ public class JPADriftChangeSetCriteria extends Criteria implements
DriftChangeSe
filterOverrides.put("endVersion", "version <= ?");
filterOverrides.put("createdAfter", "ctime >= ?");
filterOverrides.put("createdBefore", "ctime <= ?");
- filterOverrides.put("driftConfigurationId", "driftConfiguration.id
= ?");
+ filterOverrides.put("driftDefinitionId", "driftDefinition.id =
?");
if (null != changeSetCriteria) {
this.addFilterCategory(changeSetCriteria.getFilterCategory());
this.addFilterCreatedAfter(changeSetCriteria.getFilterCreatedAfter());
this.addFilterCreatedBefore(changeSetCriteria.getFilterCreatedBefore());
-
this.addFilterDriftConfigurationId(changeSetCriteria.getFilterDriftConfigurationId());
+
this.addFilterDriftDefinitionId(changeSetCriteria.getFilterDriftDefintionId());
this.addFilterEndVersion(changeSetCriteria.getFilterEndVersion());
this.addFilterId(changeSetCriteria.getFilterId());
this.addFilterResourceId(changeSetCriteria.getFilterResourceId());
@@ -164,13 +164,13 @@ public class JPADriftChangeSetCriteria extends Criteria implements
DriftChangeSe
}
@Override
- public void addFilterDriftConfigurationId(Integer filterDriftConfigId) {
- this.filterDriftConfigurationId = filterDriftConfigId;
+ public void addFilterDriftDefinitionId(Integer filterDriftDefId) {
+ this.filterDriftDefinitionId = filterDriftDefId;
}
@Override
- public Integer getFilterDriftConfigurationId() {
- return filterDriftConfigurationId;
+ public Integer getFilterDriftDefintionId() {
+ return filterDriftDefinitionId;
}
public void addFilterCategory(DriftChangeSetCategory filterCategory) {
@@ -191,8 +191,8 @@ public class JPADriftChangeSetCriteria extends Criteria implements
DriftChangeSe
return fetchDrifts;
}
- public void fetchDriftConfiguration(boolean fetchDriftConfiguration) {
- this.fetchDriftConfiguration = fetchDriftConfiguration;
+ public void fetchDriftDefinition(boolean fetchDriftDefinition) {
+ this.fetchDriftDefinition = fetchDriftDefinition;
}
public void addSortVersion(PageOrdering sortVersion) {
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java
index 87e1d8f..0386ea3 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceCriteria.java
@@ -90,7 +90,7 @@ public class ResourceCriteria extends TaggedCriteria {
private boolean fetchResourceErrors;
private boolean fetchEventSources;
private boolean fetchProductVersion;
- private boolean fetchDriftConfigurations;
+ private boolean fetchDriftDefinitions;
private PageOrdering sortName;
private PageOrdering sortInventoryStatus;
@@ -331,8 +331,8 @@ public class ResourceCriteria extends TaggedCriteria {
this.fetchProductVersion = fetchProductVersion;
}
- public void fetchDriftConfigurations(boolean fetchDriftConfigurations) {
- this.fetchDriftConfigurations = fetchDriftConfigurations;
+ public void fetchDriftDefinitions(boolean fetchDriftDefinitions) {
+ this.fetchDriftDefinitions = fetchDriftDefinitions;
}
public void addSortName(PageOrdering sortName) {
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java
index 2cf1025..7abb782 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java
@@ -74,7 +74,7 @@ public class ResourceTypeCriteria extends Criteria {
private boolean fetchProductVersions;
private boolean fetchBundleType;
private boolean fetchResources;
- private boolean fetchDriftConfigurationTemplates;
+ private boolean fetchDriftDefinitionTemplates;
private boolean fetchBundleConfiguration;
private PageOrdering sortName;
@@ -204,8 +204,8 @@ public class ResourceTypeCriteria extends Criteria {
this.fetchResources = fetchResources;
}
- public void fetchDriftConfigurationTemplates(boolean
fetchDriftConfigurationTemplates) {
- this.fetchDriftConfigurationTemplates = fetchDriftConfigurationTemplates;
+ public void fetchDriftDefinitionTemplates(boolean fetchDriftDefinitionTemplates) {
+ this.fetchDriftDefinitionTemplates = fetchDriftDefinitionTemplates;
}
public void fetchBundleConfiguration(boolean fetchBundleConfiguration) {
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSet.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSet.java
index 5ad5796..a5a5e3c 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSet.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSet.java
@@ -31,10 +31,10 @@ import
org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
* the contract required for defining and persisting a DriftChangeSet. Drift server
plugins
* are responsible for managing persistence.
* <p/>
- * Each DriftChangeSet belongs to a particular {@link DriftConfiguration} which
specifies
- * the rules for how drift detection is performed (by the agent). A DriftConfiguration
is
+ * Each DriftChangeSet belongs to a particular {@link DriftDefinition} which specifies
+ * the rules for how drift detection is performed (by the agent). A DriftDefinition is
* in turn owned by a {@link org.rhq.core.domain.resource.Resource Resource} and a
resource
- * can have multiple drift configurations.
+ * can have multiple drift definitions.
*
* @param <D> A server plugin's Drift implementation
*
@@ -64,18 +64,18 @@ public interface DriftChangeSet<D extends Drift<?, ?>> {
/**
* Every change set must be assigned a version that is unique within the context of
the
- * owning {@link DriftConfiguration}. This is analgous to a revision number in a
+ * owning {@link DriftDefinition}. This is analgous to a revision number in a
* version control system like SVN.
*
* @return The change set version number that is unique within the context of its
- * owning {@link DriftConfiguration}.
+ * owning {@link DriftDefinition}.
*/
int getVersion();
/**
* Sets the change set version number. Note that change set version numbers
* <strong>must</strong> be unique within the context of the owning
- * {@link DriftConfiguration}. Change sets should be assigned version numbers in
+ * {@link DriftDefinition}. Change sets should be assigned version numbers in
* increasing order. The first change set saved should have a version of N, the
second
* should have a value of N + 1, etc.
*
@@ -99,49 +99,49 @@ public interface DriftChangeSet<D extends Drift<?, ?>> {
void setCategory(DriftChangeSetCategory category);
/**
- * Returns the drift handling mode of the owning drift configuration at the time of
change
- * set creation. Because the value set on the owning drift configuration can change,
the
+ * Returns the drift handling mode of the owning drift definition at the time of
change
+ * set creation. Because the value set on the owning drift definition can change,
the
* value must be stored with the change set such that it can be applied consistently
when
* handling the associated drift.
*
- * @return The {@link DriftConfiguration.DriftHandlingMode} mode
+ * @return The {@link DriftDefinition.DriftHandlingMode} mode
*/
DriftHandlingMode getDriftHandlingMode();
/**
* Sets the drift handling mode for the change set. It should be set to the owning
drift
- * configuration's drift handling mode at the time of change set creation.
Because the
- * value set on the owning drift configuration can change, the value must be stored
with
+ * definition's drift handling mode at the time of change set creation. Because
the
+ * value set on the owning drift definition can change, the value must be stored with
* the change set such that it can be applied consistently when handling the
associated drift.
*
- * @param driftHandlingMode The {@link DriftConfiguration.DriftHandlingMode} mode
+ * @param driftHandlingMode The {@link DriftDefinition.DriftHandlingMode} mode
*/
void setDriftHandlingMode(DriftHandlingMode driftHandlingMode);
/**
- * Returns the id of the owning drift configuration. Note that while server plugins
are
+ * Returns the id of the owning drift definition. Note that while server plugins are
* responsible for managing the persistence of change sets, the RHQ server manages
the
- * persistence of the owning drift configuration.
+ * persistence of the owning drift definition.
*
- * @return The {@link DriftConfiguration} id
+ * @return The {@link DriftDefinition} id
*/
- int getDriftConfigurationId();
+ int getDriftDefinitionId();
/**
- * Sets the id of the owning drift configuration. Note that while server plugins are
+ * Sets the id of the owning drift definition. Note that while server plugins are
* responsible for managing the persistence of change sets, the RHQ server manages
the
- * persistence of the drift configuration.
+ * persistence of the drift definition.
*
- * @param id The {@link DriftConfiguration} id
+ * @param id The {@link DriftDefinition} id
*/
- void setDriftConfigurationId(int id);
+ void setDriftDefinitionId(int id);
/**
- * Returns the id of the resource to which the drift configuration is assigned. Note
+ * Returns the id of the resource to which the drift definition is assigned. Note
* that the RHQ server and not drift server plugins manage the persistence of the
* resource.
*
- * @return The id of the resource to which the drift configuration belongs
+ * @return The id of the resource to which the drift definition belongs
*/
int getResourceId();
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftComposite.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftComposite.java
index 072f432..5dbd57a 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftComposite.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftComposite.java
@@ -39,7 +39,7 @@ public class DriftComposite implements Serializable {
this.resource = resource;
}
- public String getDriftConfigName() {
+ public String getDriftDefinitionName() {
return driftConfigName;
}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
deleted file mode 100644
index d7ac85a..0000000
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.core.domain.drift;
-
-import static java.util.Collections.emptyList;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.Enumerated;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.PrePersist;
-import javax.persistence.SequenceGenerator;
-import javax.persistence.Table;
-
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.Property;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
-import org.rhq.core.domain.resource.Resource;
-
-/**
- * This is a convienence wrapper around a Configuration object whose schema is that
- * of {@link DriftConfigurationDefinition}.
- *
- * Note that this is not an actual Configuration object - it's got a HAS-A
relationship
- * with Configuration.
- *
- * This object also has an optional relationship with a Resource.
- *
- * @author John Sanda
- * @author John Mazzitelli
- * @author Jay Shaughnessy
- */
-@Entity
-@Table(name = "RHQ_DRIFT_CONFIG")
-@SequenceGenerator(name = "SEQ", sequenceName =
"RHQ_DRIFT_CONFIG_ID_SEQ")
-public class DriftConfiguration implements Serializable {
- private static final long serialVersionUID = 1L;
-
- @Column(name = "ID", nullable = false)
- @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
- @Id
- private int id;
-
- @Column(name = "CTIME", nullable = false)
- private Long ctime = -1L;
-
- @Column(name = "NAME", nullable = false)
- private String name;
-
- @Column(name = "IS_ENABLED", nullable = false)
- private boolean isEnabled;
-
- @Column(name = "DRIFT_HANDLING_MODE", nullable = false)
- @Enumerated(EnumType.STRING)
- private DriftHandlingMode driftHandlingMode;
-
- // unit = millis
- @Column(name = "INTERVAL", nullable = false)
- private long interval;
-
- @JoinColumn(name = "CONFIG_ID", referencedColumnName = "ID",
nullable = false)
- @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
- private Configuration configuration;
-
- @JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID",
nullable = true)
- @ManyToOne(optional = true)
- private Resource resource = null;
-
- // required for jaxb/web services stuff
- protected DriftConfiguration() {
- }
-
- public DriftConfiguration(Configuration c) {
- this.setConfiguration(c);
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public Long getCtime() {
- return ctime;
- }
-
- @PrePersist
- void onPersist() {
- this.ctime = System.currentTimeMillis();
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- if (null == name) {
- throw new IllegalArgumentException("Drift congig name can not be
null");
- }
-
- this.name = name;
- this.setNameProperty(name);
- }
-
- public boolean isEnabled() {
- return isEnabled;
- }
-
- /**
- * If null set to default
- * @param isEnabled
- */
- public void setEnabled(Boolean isEnabled) {
- if (isEnabled == null) {
- isEnabled = DriftConfigurationDefinition.DEFAULT_ENABLED;
- }
-
- this.isEnabled = isEnabled;
- this.setEnabledProperty(isEnabled);
- }
-
- public DriftHandlingMode getDriftHandlingMode() {
- return driftHandlingMode;
- }
-
- public void setDriftHandlingMode(DriftHandlingMode driftHandlingMode) {
- if (null == driftHandlingMode) {
- driftHandlingMode =
DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE;
- }
-
- this.driftHandlingMode = driftHandlingMode;
- this.setDriftHandlingModeProperty(driftHandlingMode);
- }
-
- public long getInterval() {
- return interval;
- }
-
- /**
- * If null, set to default.
- * @param interval
- */
- public void setInterval(Long interval) {
- if (interval == null) {
- interval = DriftConfigurationDefinition.DEFAULT_INTERVAL;
- }
-
- this.interval = interval;
- this.setIntervalProperty(interval);
- }
-
- public Configuration getConfiguration() {
- return configuration;
- }
-
- public void setConfiguration(Configuration configuration) {
- this.configuration = configuration;
- this.name = this.getNameProperty();
- this.isEnabled = this.getIsEnabledProperty();
- this.interval = this.getIntervalProperty();
- this.driftHandlingMode = this.getDriftHandlingModeProperty();
- }
-
- public Resource getResource() {
- return resource;
- }
-
- public void setResource(Resource resource) {
- this.resource = resource;
- if (this.resource != null) {
- this.resource.getDriftConfigurations().add(this);
- }
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("DriftConfiguration [id=").append(id).append(",
name=").append(name).append(", enabled=")
- .append(isEnabled).append(",
interval=").append(interval).append(",
resource=").append(resource).append(
- ", basedir=").append(getBasedir()).append(",
includes=").append(getIncludes()).append(", excludes=")
- .append(getExcludes()).append("]");
- return builder.toString();
- }
-
- public static class BaseDirectory implements Serializable {
- private static final long serialVersionUID = 1L;
- private BaseDirValueContext context;
- private String name;
-
- // required for jaxb/web services remoting
- protected BaseDirectory() {
- }
-
- public BaseDirectory(BaseDirValueContext context, String name) {
- this.context = context;
- this.name = name;
- }
-
- public BaseDirValueContext getValueContext() {
- return context;
- }
-
- public String getValueName() {
- return name;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("BaseDirectory
[context=").append(context).append(",
name=").append(name).append("]");
- return builder.toString();
- }
-
- @Override
- public int hashCode() {
- int result = 1;
- result = 31 * result + ((context == null) ? 0 : context.hashCode());
- result = 31 * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof BaseDirectory)) {
- return false;
- }
- BaseDirectory other = (BaseDirectory) obj;
- if (context == null) {
- if (other.context != null) {
- return false;
- }
- } else if (!context.equals(other.context)) {
- return false;
- }
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- return true;
- }
- }
-
- private String getNameProperty() {
- return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME,
null);
- }
-
- private void setNameProperty(String name) {
- if (name == null) {
- throw new IllegalArgumentException("name is null");
- }
- configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_NAME,
name));
- }
-
- public BaseDirectory getBasedir() {
- PropertyMap map =
configuration.getMap(DriftConfigurationDefinition.PROP_BASEDIR);
- if (map == null) {
- return null;
- }
-
- String valueContext =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, null);
- String valueName =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, null);
-
- BaseDirValueContext valueContextEnum;
-
- if (valueContext == null) {
- throw new NullPointerException("valueContext is null");
- } else {
- try {
- valueContextEnum = BaseDirValueContext.valueOf(valueContext);
- } catch (Exception e) {
- throw new IllegalArgumentException("Invalid valueContext: " +
valueContext);
- }
- }
-
- if (valueName == null) {
- throw new NullPointerException("valueName is null");
- }
-
- return new BaseDirectory(valueContextEnum, valueName);
- }
-
- public void setBasedir(BaseDirectory basedir) {
- if (basedir == null) {
- throw new NullPointerException("basedir is null");
- }
- if (basedir.getValueContext() == null) {
- throw new NullPointerException("valueContext is null");
- }
- if (basedir.getValueName() == null) {
- throw new NullPointerException("valueName is null");
- }
-
- String valueContext = basedir.getValueContext().name();
- String valueName = basedir.getValueName();
-
- PropertyMap basedirMap = new
PropertyMap(DriftConfigurationDefinition.PROP_BASEDIR);
- basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, valueContext));
- basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, valueName));
-
- configuration.put(basedirMap);
- }
-
- private Long getIntervalProperty() {
- return
Long.parseLong(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_INTERVAL,
String
- .valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL)));
- }
-
- private void setIntervalProperty(Long interval) {
- configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL,
interval.toString()));
- }
-
- private DriftHandlingMode getDriftHandlingModeProperty() {
- return DriftHandlingMode.valueOf(configuration.getSimpleValue(
- DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE,
- DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE.name()));
- }
-
- private void setDriftHandlingModeProperty(DriftHandlingMode mode) {
- configuration.put(new
PropertySimple(DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE, mode.name()));
- }
-
- private boolean getIsEnabledProperty() {
- return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_ENABLED,
-
String.valueOf(DriftConfigurationDefinition.DEFAULT_ENABLED)).equals("true");
- }
-
- private void setEnabledProperty(boolean enabled) {
- configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_ENABLED,
String.valueOf(enabled)));
- }
-
- public List<Filter> getIncludes() {
- return getFilters(DriftConfigurationDefinition.PROP_INCLUDES);
- }
-
- public List<Filter> getExcludes() {
- return getFilters(DriftConfigurationDefinition.PROP_EXCLUDES);
- }
-
- public void addInclude(Filter filter) {
- PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_INCLUDES);
- if (filtersList == null) {
- // this is going to be our first include filter - make sure we create an
initial list and put it in the config
- filtersList = new PropertyList(DriftConfigurationDefinition.PROP_INCLUDES);
- configuration.put(filtersList);
- }
-
- PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_INCLUDES_INCLUDE);
- filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
- filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
- filtersList.add(filterMap);
- }
-
- public void addExclude(Filter filter) {
- PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_EXCLUDES);
- if (filtersList == null) {
- // this is going to be our first include filter - make sure we create an
initial list and put it in the config
- filtersList = new PropertyList(DriftConfigurationDefinition.PROP_EXCLUDES);
- configuration.put(filtersList);
- }
-
- PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_EXCLUDES_EXCLUDE);
- filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
- filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
- filtersList.add(filterMap);
- }
-
- private List<Filter> getFilters(String type) {
- PropertyList filtersListProperty = configuration.getList(type);
- if (filtersListProperty == null) {
- return emptyList();
- }
-
- List<Filter> filters = new ArrayList<Filter>();
- for (Property property : filtersListProperty.getList()) {
- PropertyMap filter = (PropertyMap) property;
- filters.add(new
Filter(filter.getSimpleValue(DriftConfigurationDefinition.PROP_PATH, ""),
filter
- .getSimpleValue(DriftConfigurationDefinition.PROP_PATTERN,
"")));
- }
-
- return filters;
- }
-}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java
deleted file mode 100644
index d530ab4..0000000
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.core.domain.drift;
-
-import java.util.Comparator;
-import java.util.List;
-
-/**
- * Compares two {@link DriftConfiguration} objects. The comparison can either
- * compare basedir/includes-excludes filters or ignore them. Will also compare
- * name, interval, enabled flag.
- *
- * @author John Mazzitelli
- */
-public class DriftConfigurationComparator implements Comparator<DriftConfiguration>
{
-
- public enum CompareMode {
- /**
- * The comparator will only check the base information: name, enabled, interval,
driftHandlingMode
- * The basedir/includes-excludes filters will be ignored.
- */
- ONLY_BASE_INFO,
-
- /**
- * The comparator will only check the basedir/includes-excludes filters.
- * The base information will be ignored (see {@link #ONLY_BASE_INFO} for what
those are).
- */
- ONLY_DIRECTORY_SPECIFICATIONS,
-
- /**
- * The comparator will check both the basedir/includes-excludes filters and
- * the base information (see {@link #ONLY_BASE_INFO} for what those are).
- */
- BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
- };
-
- private final CompareMode compareMode;
-
- public DriftConfigurationComparator(CompareMode mode) {
- this.compareMode = mode;
- }
-
- @Override
- public int compare(DriftConfiguration dc1, DriftConfiguration dc2) {
- if (compareMode != CompareMode.ONLY_DIRECTORY_SPECIFICATIONS) {
- if (dc1.getName() != null) {
- if (dc2.getName() != null) {
- int results = dc1.getName().compareTo(dc2.getName());
- if (results != 0) {
- return results;
- }
- } else {
- return 1; // dc1's name is not null, but dc2's name is null,
not equal!
- }
- } else if (dc2.getName() != null) {
- return -1; // dc1's name is null, but dc2's name is not null, not
equal!
- }
-
- if (dc1.getInterval() != dc2.getInterval()) {
- return dc1.getInterval() < dc2.getInterval() ? -1 : 1;
- }
-
- if (dc1.getDriftHandlingMode() != dc2.getDriftHandlingMode()) {
- return dc1.getDriftHandlingMode().ordinal() <
dc2.getDriftHandlingMode().ordinal() ? -1 : 1;
- }
-
- if (dc1.isEnabled() != dc2.isEnabled()) {
- return dc1.isEnabled() ? 1 : -1; // so false sorts before true, seems
logical to me
- }
- }
-
- if (compareMode != CompareMode.ONLY_BASE_INFO) {
- if (dc1.getBasedir() != null) {
- if (!dc1.getBasedir().equals(dc2.getBasedir())) {
- int hash1 = dc1.getBasedir().hashCode();
- int hash2 = (dc2.getBasedir() != null) ? dc2.getBasedir().hashCode()
: 0;
- return hash1 < hash2 ? -1 : 1;
- }
- } else if (dc2.getBasedir() != null) {
- return -1; // dc1's basedir is null, but dc2's basedir is not
null, not equal!
- }
-
- List<Filter> filters1 = dc1.getIncludes();
- List<Filter> filters2 = dc2.getIncludes();
- int results = compareFilters(filters1, filters2);
- if (results != 0) {
- return results;
- }
-
- filters1 = dc1.getExcludes();
- filters2 = dc2.getExcludes();
- results = compareFilters(filters1, filters2);
- if (results != 0) {
- return results;
- }
- }
-
- return 0;
- }
-
- private int compareFilters(List<Filter> filters1, List<Filter> filters2)
{
- if (filters1 == null) {
- return (filters2 == null) ? 0 : -1;
- } else if (filters2 == null) {
- return 1;
- }
-
- // at this point, we know both filters1 and filters2 are non-null
- // let's do the next easiest check - size. If the lists are different sizes,
then clearly they are different
- if (filters1.size() != filters2.size()) {
- return (filters1.size() < filters2.size()) ? -1 : 1;
- }
-
- // they are the same size, let's see if they have the same items. We only
need to see if one contains
- // all of the other; because they are the same size, if filters1 contains all the
filters2 items,
- // then clearly the other way is true too (filters2 contains all of filters1
items).
- if (!filters1.containsAll(filters2)) {
- return -1; // unsure if we need to do further anaylsis to determine if -1 or
1 should be returned; for now, don't worry about it
- }
-
- return 0;
- }
-}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
new file mode 100644
index 0000000..33bb483
--- /dev/null
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinition.java
@@ -0,0 +1,421 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.core.domain.drift;
+
+import static java.util.Collections.emptyList;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.PrePersist;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.resource.Resource;
+
+/**
+ * This is a convienence wrapper around a Configuration object whose schema is that
+ * of {@link DriftConfigurationDefinition}.
+ *
+ * Note that this is not an actual Configuration object - it's got a HAS-A
relationship
+ * with Configuration.
+ *
+ * This object also has an optional relationship with a Resource.
+ *
+ * @author John Sanda
+ * @author John Mazzitelli
+ * @author Jay Shaughnessy
+ */
+@Entity
+@Table(name = "RHQ_DRIFT_CONFIG")
+@SequenceGenerator(name = "SEQ", sequenceName =
"RHQ_DRIFT_CONFIG_ID_SEQ")
+public class DriftDefinition implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Column(name = "ID", nullable = false)
+ @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
+ @Id
+ private int id;
+
+ @Column(name = "CTIME", nullable = false)
+ private Long ctime = -1L;
+
+ @Column(name = "NAME", nullable = false)
+ private String name;
+
+ @Column(name = "IS_ENABLED", nullable = false)
+ private boolean isEnabled;
+
+ @Column(name = "DRIFT_HANDLING_MODE", nullable = false)
+ @Enumerated(EnumType.STRING)
+ private DriftHandlingMode driftHandlingMode;
+
+ // unit = millis
+ @Column(name = "INTERVAL", nullable = false)
+ private long interval;
+
+ @JoinColumn(name = "CONFIG_ID", referencedColumnName = "ID",
nullable = false)
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
+ private Configuration configuration;
+
+ @JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID",
nullable = true)
+ @ManyToOne(optional = true)
+ private Resource resource = null;
+
+ // required for jaxb/web services stuff
+ protected DriftDefinition() {
+ }
+
+ public DriftDefinition(Configuration c) {
+ this.setConfiguration(c);
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public Long getCtime() {
+ return ctime;
+ }
+
+ @PrePersist
+ void onPersist() {
+ this.ctime = System.currentTimeMillis();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ if (null == name) {
+ throw new IllegalArgumentException("Drift congig name can not be
null");
+ }
+
+ this.name = name;
+ this.setNameProperty(name);
+ }
+
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ /**
+ * If null set to default
+ * @param isEnabled
+ */
+ public void setEnabled(Boolean isEnabled) {
+ if (isEnabled == null) {
+ isEnabled = DriftConfigurationDefinition.DEFAULT_ENABLED;
+ }
+
+ this.isEnabled = isEnabled;
+ this.setEnabledProperty(isEnabled);
+ }
+
+ public DriftHandlingMode getDriftHandlingMode() {
+ return driftHandlingMode;
+ }
+
+ public void setDriftHandlingMode(DriftHandlingMode driftHandlingMode) {
+ if (null == driftHandlingMode) {
+ driftHandlingMode =
DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE;
+ }
+
+ this.driftHandlingMode = driftHandlingMode;
+ this.setDriftHandlingModeProperty(driftHandlingMode);
+ }
+
+ public long getInterval() {
+ return interval;
+ }
+
+ /**
+ * If null, set to default.
+ * @param interval
+ */
+ public void setInterval(Long interval) {
+ if (interval == null) {
+ interval = DriftConfigurationDefinition.DEFAULT_INTERVAL;
+ }
+
+ this.interval = interval;
+ this.setIntervalProperty(interval);
+ }
+
+ public Configuration getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(Configuration configuration) {
+ this.configuration = configuration;
+ this.name = this.getNameProperty();
+ this.isEnabled = this.getIsEnabledProperty();
+ this.interval = this.getIntervalProperty();
+ this.driftHandlingMode = this.getDriftHandlingModeProperty();
+ }
+
+ public Resource getResource() {
+ return resource;
+ }
+
+ public void setResource(Resource resource) {
+ this.resource = resource;
+ if (this.resource != null) {
+ this.resource.getDriftDefinitions().add(this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("DriftDefinition [id=").append(id).append(",
name=").append(name).append(", enabled=").append(
+ isEnabled).append(", interval=").append(interval).append(",
resource=").append(resource).append(
+ ", basedir=").append(getBasedir()).append(",
includes=").append(getIncludes()).append(", excludes=")
+ .append(getExcludes()).append("]");
+ return builder.toString();
+ }
+
+ public static class BaseDirectory implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private BaseDirValueContext context;
+ private String name;
+
+ // required for jaxb/web services remoting
+ protected BaseDirectory() {
+ }
+
+ public BaseDirectory(BaseDirValueContext context, String name) {
+ this.context = context;
+ this.name = name;
+ }
+
+ public BaseDirValueContext getValueContext() {
+ return context;
+ }
+
+ public String getValueName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("BaseDirectory
[context=").append(context).append(",
name=").append(name).append("]");
+ return builder.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 1;
+ result = 31 * result + ((context == null) ? 0 : context.hashCode());
+ result = 31 * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof BaseDirectory)) {
+ return false;
+ }
+ BaseDirectory other = (BaseDirectory) obj;
+ if (context == null) {
+ if (other.context != null) {
+ return false;
+ }
+ } else if (!context.equals(other.context)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+ }
+
+ private String getNameProperty() {
+ return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME,
null);
+ }
+
+ private void setNameProperty(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("name is null");
+ }
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_NAME,
name));
+ }
+
+ public BaseDirectory getBasedir() {
+ PropertyMap map =
configuration.getMap(DriftConfigurationDefinition.PROP_BASEDIR);
+ if (map == null) {
+ return null;
+ }
+
+ String valueContext =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, null);
+ String valueName =
map.getSimpleValue(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, null);
+
+ BaseDirValueContext valueContextEnum;
+
+ if (valueContext == null) {
+ throw new NullPointerException("valueContext is null");
+ } else {
+ try {
+ valueContextEnum = BaseDirValueContext.valueOf(valueContext);
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Invalid valueContext: " +
valueContext);
+ }
+ }
+
+ if (valueName == null) {
+ throw new NullPointerException("valueName is null");
+ }
+
+ return new BaseDirectory(valueContextEnum, valueName);
+ }
+
+ public void setBasedir(BaseDirectory basedir) {
+ if (basedir == null) {
+ throw new NullPointerException("basedir is null");
+ }
+ if (basedir.getValueContext() == null) {
+ throw new NullPointerException("valueContext is null");
+ }
+ if (basedir.getValueName() == null) {
+ throw new NullPointerException("valueName is null");
+ }
+
+ String valueContext = basedir.getValueContext().name();
+ String valueName = basedir.getValueName();
+
+ PropertyMap basedirMap = new
PropertyMap(DriftConfigurationDefinition.PROP_BASEDIR);
+ basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT, valueContext));
+ basedirMap.put(new
PropertySimple(DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME, valueName));
+
+ configuration.put(basedirMap);
+ }
+
+ private Long getIntervalProperty() {
+ return
Long.parseLong(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_INTERVAL,
String
+ .valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL)));
+ }
+
+ private void setIntervalProperty(Long interval) {
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL,
interval.toString()));
+ }
+
+ private DriftHandlingMode getDriftHandlingModeProperty() {
+ return DriftHandlingMode.valueOf(configuration.getSimpleValue(
+ DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE,
+ DriftConfigurationDefinition.DEFAULT_DRIFT_HANDLING_MODE.name()));
+ }
+
+ private void setDriftHandlingModeProperty(DriftHandlingMode mode) {
+ configuration.put(new
PropertySimple(DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE, mode.name()));
+ }
+
+ private boolean getIsEnabledProperty() {
+ return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_ENABLED,
+
String.valueOf(DriftConfigurationDefinition.DEFAULT_ENABLED)).equals("true");
+ }
+
+ private void setEnabledProperty(boolean enabled) {
+ configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_ENABLED,
String.valueOf(enabled)));
+ }
+
+ public List<Filter> getIncludes() {
+ return getFilters(DriftConfigurationDefinition.PROP_INCLUDES);
+ }
+
+ public List<Filter> getExcludes() {
+ return getFilters(DriftConfigurationDefinition.PROP_EXCLUDES);
+ }
+
+ public void addInclude(Filter filter) {
+ PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_INCLUDES);
+ if (filtersList == null) {
+ // this is going to be our first include filter - make sure we create an
initial list and put it in the config
+ filtersList = new PropertyList(DriftConfigurationDefinition.PROP_INCLUDES);
+ configuration.put(filtersList);
+ }
+
+ PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_INCLUDES_INCLUDE);
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
+ filtersList.add(filterMap);
+ }
+
+ public void addExclude(Filter filter) {
+ PropertyList filtersList =
configuration.getList(DriftConfigurationDefinition.PROP_EXCLUDES);
+ if (filtersList == null) {
+ // this is going to be our first include filter - make sure we create an
initial list and put it in the config
+ filtersList = new PropertyList(DriftConfigurationDefinition.PROP_EXCLUDES);
+ configuration.put(filtersList);
+ }
+
+ PropertyMap filterMap = new
PropertyMap(DriftConfigurationDefinition.PROP_EXCLUDES_EXCLUDE);
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATH,
filter.getPath()));
+ filterMap.put(new PropertySimple(DriftConfigurationDefinition.PROP_PATTERN,
filter.getPattern()));
+ filtersList.add(filterMap);
+ }
+
+ private List<Filter> getFilters(String type) {
+ PropertyList filtersListProperty = configuration.getList(type);
+ if (filtersListProperty == null) {
+ return emptyList();
+ }
+
+ List<Filter> filters = new ArrayList<Filter>();
+ for (Property property : filtersListProperty.getList()) {
+ PropertyMap filter = (PropertyMap) property;
+ filters.add(new
Filter(filter.getSimpleValue(DriftConfigurationDefinition.PROP_PATH, ""),
filter
+ .getSimpleValue(DriftConfigurationDefinition.PROP_PATTERN,
"")));
+ }
+
+ return filters;
+ }
+}
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinitionComparator.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinitionComparator.java
new file mode 100644
index 0000000..ac3d069
--- /dev/null
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDefinitionComparator.java
@@ -0,0 +1,140 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.core.domain.drift;
+
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Compares two {@link DriftDefinition} objects. The comparison can either
+ * compare basedir/includes-excludes filters or ignore them. Will also compare
+ * name, interval, enabled flag.
+ *
+ * @author John Mazzitelli
+ */
+public class DriftDefinitionComparator implements Comparator<DriftDefinition> {
+
+ public enum CompareMode {
+ /**
+ * The comparator will only check the base information: name, enabled, interval,
driftHandlingMode
+ * The basedir/includes-excludes filters will be ignored.
+ */
+ ONLY_BASE_INFO,
+
+ /**
+ * The comparator will only check the basedir/includes-excludes filters.
+ * The base information will be ignored (see {@link #ONLY_BASE_INFO} for what
those are).
+ */
+ ONLY_DIRECTORY_SPECIFICATIONS,
+
+ /**
+ * The comparator will check both the basedir/includes-excludes filters and
+ * the base information (see {@link #ONLY_BASE_INFO} for what those are).
+ */
+ BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
+ };
+
+ private final CompareMode compareMode;
+
+ public DriftDefinitionComparator(CompareMode mode) {
+ this.compareMode = mode;
+ }
+
+ @Override
+ public int compare(DriftDefinition dc1, DriftDefinition dc2) {
+ if (compareMode != CompareMode.ONLY_DIRECTORY_SPECIFICATIONS) {
+ if (dc1.getName() != null) {
+ if (dc2.getName() != null) {
+ int results = dc1.getName().compareTo(dc2.getName());
+ if (results != 0) {
+ return results;
+ }
+ } else {
+ return 1; // dc1's name is not null, but dc2's name is null,
not equal!
+ }
+ } else if (dc2.getName() != null) {
+ return -1; // dc1's name is null, but dc2's name is not null, not
equal!
+ }
+
+ if (dc1.getInterval() != dc2.getInterval()) {
+ return dc1.getInterval() < dc2.getInterval() ? -1 : 1;
+ }
+
+ if (dc1.getDriftHandlingMode() != dc2.getDriftHandlingMode()) {
+ return dc1.getDriftHandlingMode().ordinal() <
dc2.getDriftHandlingMode().ordinal() ? -1 : 1;
+ }
+
+ if (dc1.isEnabled() != dc2.isEnabled()) {
+ return dc1.isEnabled() ? 1 : -1; // so false sorts before true, seems
logical to me
+ }
+ }
+
+ if (compareMode != CompareMode.ONLY_BASE_INFO) {
+ if (dc1.getBasedir() != null) {
+ if (!dc1.getBasedir().equals(dc2.getBasedir())) {
+ int hash1 = dc1.getBasedir().hashCode();
+ int hash2 = (dc2.getBasedir() != null) ? dc2.getBasedir().hashCode()
: 0;
+ return hash1 < hash2 ? -1 : 1;
+ }
+ } else if (dc2.getBasedir() != null) {
+ return -1; // dc1's basedir is null, but dc2's basedir is not
null, not equal!
+ }
+
+ List<Filter> filters1 = dc1.getIncludes();
+ List<Filter> filters2 = dc2.getIncludes();
+ int results = compareFilters(filters1, filters2);
+ if (results != 0) {
+ return results;
+ }
+
+ filters1 = dc1.getExcludes();
+ filters2 = dc2.getExcludes();
+ results = compareFilters(filters1, filters2);
+ if (results != 0) {
+ return results;
+ }
+ }
+
+ return 0;
+ }
+
+ private int compareFilters(List<Filter> filters1, List<Filter> filters2)
{
+ if (filters1 == null) {
+ return (filters2 == null) ? 0 : -1;
+ } else if (filters2 == null) {
+ return 1;
+ }
+
+ // at this point, we know both filters1 and filters2 are non-null
+ // let's do the next easiest check - size. If the lists are different sizes,
then clearly they are different
+ if (filters1.size() != filters2.size()) {
+ return (filters1.size() < filters2.size()) ? -1 : 1;
+ }
+
+ // they are the same size, let's see if they have the same items. We only
need to see if one contains
+ // all of the other; because they are the same size, if filters1 contains all the
filters2 items,
+ // then clearly the other way is true too (filters2 contains all of filters1
items).
+ if (!filters1.containsAll(filters2)) {
+ return -1; // unsure if we need to do further anaylsis to determine if -1 or
1 should be returned; for now, don't worry about it
+ }
+
+ return 0;
+ }
+}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java
index b56597e..c9fb8c3 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java
@@ -50,19 +50,19 @@ import javax.persistence.Table;
@NamedQueries( { @NamedQuery(name = JPADrift.QUERY_DELETE_BY_RESOURCES, query =
"" //
+ "DELETE FROM JPADrift d " //
+ " WHERE d.changeSet IN ( SELECT dcs FROM JPADriftChangeSet dcs WHERE
dcs.resource.id IN ( :resourceIds ) ) )"), //
- @NamedQuery(name = JPADrift.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE, query =
"" //
+ @NamedQuery(name = JPADrift.QUERY_DELETE_BY_DRIFTDEF_RESOURCE, query = ""
//
+ "DELETE FROM JPADrift d " //
+ " WHERE d.changeSet.id IN " //
+ " (SELECT dcs.id " //
+ " FROM JPADriftChangeSet dcs " //
- + " WHERE dcs.driftConfiguration.name = :driftConfigurationName AND
dcs.resource.id = :resourceId)") })
+ + " WHERE dcs.driftDefinition.name = :driftDefinitionName AND
dcs.resource.id = :resourceId)") })
@Table(name = "RHQ_DRIFT")
@SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DRIFT_ID_SEQ")
public class JPADrift implements Serializable, Drift<JPADriftChangeSet,
JPADriftFile> {
private static final long serialVersionUID = 1L;
public static final String QUERY_DELETE_BY_RESOURCES =
"JPADrift.deleteByResources";
- public static final String QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE =
"JPADrift.deleteByDriftConfigResource";
+ public static final String QUERY_DELETE_BY_DRIFTDEF_RESOURCE =
"JPADrift.deleteByDriftDefResource";
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java
index 1f82848..79ef691 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java
@@ -57,13 +57,13 @@ import org.rhq.core.domain.resource.Resource;
@NamedQueries( { @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_RESOURCES, query =
"" //
+ "DELETE FROM JPADriftChangeSet dcs " //
+ " WHERE dcs.resource.id IN ( :resourceIds )"), //
- @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE, query =
"" //
+ @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_DRIFTDEF_RESOURCE, query =
"" //
+ "DELETE FROM JPADriftChangeSet dcs " //
+ " WHERE dcs.resource.id = :resourceId " //
- + " AND dcs.driftConfiguration.id IN " //
+ + " AND dcs.driftDefinition.id IN " //
+ " (SELECT dc.id " //
- + " FROM DriftConfiguration dc " //
- + " WHERE dc.resource.id = :resourceId AND dc.name =
:driftConfigurationName)" //
+ + " FROM DriftDefinition dc " //
+ + " WHERE dc.resource.id = :resourceId AND dc.name =
:driftDefinitionName)" //
) })
@Table(name = "RHQ_DRIFT_CHANGE_SET")
@SequenceGenerator(name = "SEQ", sequenceName =
"RHQ_DRIFT_CHANGE_SET_ID_SEQ")
@@ -71,7 +71,7 @@ public class JPADriftChangeSet implements Serializable,
DriftChangeSet<JPADrift>
private static final long serialVersionUID = 1L;
public static final String QUERY_DELETE_BY_RESOURCES =
"JPADriftChangeSet.deleteByResources";
- public static final String QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE =
"JPADriftChangeSet.deleteByDriftConfigResource";
+ public static final String QUERY_DELETE_BY_DRIFTDEF_RESOURCE =
"JPADriftChangeSet.deleteByDriftDefResource";
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
@@ -93,9 +93,9 @@ public class JPADriftChangeSet implements Serializable,
DriftChangeSet<JPADrift>
// @ManyToOne(optional = false)
// TODO: remove this eager load, the drift tree build should be written to not need
this
@ManyToOne(fetch = FetchType.EAGER, optional = false)
- private DriftConfiguration driftConfiguration;
+ private DriftDefinition driftDefinition;
- // Note, this is mode at the time of the changeset processing. We cant use
driftConfiguration.mode because
+ // Note, this is mode at the time of the changeset processing. We cant use
driftDefinition.mode because
// that is the "live" setting.
@Column(name = "DRIFT_CONFIG_MODE", nullable = false)
@Enumerated(EnumType.STRING)
@@ -112,12 +112,12 @@ public class JPADriftChangeSet implements Serializable,
DriftChangeSet<JPADrift>
}
public JPADriftChangeSet(Resource resource, int version, DriftChangeSetCategory
category,
- DriftConfiguration driftConfiguration) {
+ DriftDefinition driftDefinition) {
this.resource = resource;
this.version = version;
this.category = category;
- this.driftConfiguration = driftConfiguration;
- this.driftHandlingMode = driftConfiguration.getDriftHandlingMode();
+ this.driftDefinition = driftDefinition;
+ this.driftHandlingMode = driftDefinition.getDriftHandlingMode();
}
@Override
@@ -173,12 +173,12 @@ public class JPADriftChangeSet implements Serializable,
DriftChangeSet<JPADrift>
this.resource = resource;
}
- public DriftConfiguration getDriftConfiguration() {
- return driftConfiguration;
+ public DriftDefinition getDriftDefinition() {
+ return driftDefinition;
}
- public void setDriftConfiguration(DriftConfiguration driftConfiguration) {
- this.driftConfiguration = driftConfiguration;
+ public void setDriftDefinition(DriftDefinition driftDefinition) {
+ this.driftDefinition = driftDefinition;
}
public DriftHandlingMode getDriftHandlingMode() {
@@ -190,13 +190,13 @@ public class JPADriftChangeSet implements Serializable,
DriftChangeSet<JPADrift>
}
@Override
- public int getDriftConfigurationId() {
- return this.driftConfiguration.getId();
+ public int getDriftDefinitionId() {
+ return this.driftDefinition.getId();
}
@Override
- public void setDriftConfigurationId(int id) {
- this.driftConfiguration.setId(id);
+ public void setDriftDefinitionId(int id) {
+ this.driftDefinition.setId(id);
}
@Override
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
index 8912791..304b90e 100644
---
a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
+++
b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
@@ -68,12 +68,12 @@ public class DriftChangeSetDTO implements
DriftChangeSet<DriftDTO>, Serializable
}
@Override
- public int getDriftConfigurationId() {
+ public int getDriftDefinitionId() {
return configId;
}
@Override
- public void setDriftConfigurationId(int id) {
+ public void setDriftDefinitionId(int id) {
configId = id;
}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
index 1eb495e..933f158 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
@@ -69,7 +69,7 @@ import org.rhq.core.domain.content.InstalledPackageHistory;
import org.rhq.core.domain.content.Repo;
import org.rhq.core.domain.content.ResourceRepo;
import org.rhq.core.domain.dashboard.Dashboard;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.event.EventSource;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.MeasurementSchedule;
@@ -1077,7 +1077,7 @@ public class Resource implements Comparable<Resource>,
Serializable {
@OneToMany(mappedBy = "resource", fetch = FetchType.LAZY, cascade = {
CascadeType.ALL })
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
- private Set<DriftConfiguration> driftConfigurations = null;
+ private Set<DriftDefinition> driftDefinitions = null;
public Resource() {
}
@@ -1747,21 +1747,21 @@ public class Resource implements Comparable<Resource>,
Serializable {
this.dashboards = dashboards;
}
- public Set<DriftConfiguration> getDriftConfigurations() {
- if (this.driftConfigurations == null) {
- this.driftConfigurations = new LinkedHashSet<DriftConfiguration>();
+ public Set<DriftDefinition> getDriftDefinitions() {
+ if (this.driftDefinitions == null) {
+ this.driftDefinitions = new LinkedHashSet<DriftDefinition>();
}
- return driftConfigurations;
+ return driftDefinitions;
}
- public void setDriftConfigurations(Set<DriftConfiguration> driftConfigurations)
{
- this.driftConfigurations = driftConfigurations;
+ public void setDriftDefinitions(Set<DriftDefinition> driftDefinitions) {
+ this.driftDefinitions = driftDefinitions;
}
- public void addDriftConfiguration(DriftConfiguration driftConfiguration) {
- getDriftConfigurations().add(driftConfiguration);
- driftConfiguration.setResource(this);
+ public void addDriftDefinition(DriftDefinition driftDefinition) {
+ getDriftDefinitions().add(driftDefinition);
+ driftDefinition.setResource(this);
}
public int compareTo(Resource that) {
diff --git
a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java
b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java
index 6fcdcc5..240b703 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java
@@ -177,7 +177,7 @@ import org.rhq.core.domain.util.Summary;
+ " (SELECT COUNT(packageType) FROM rt.packageTypes
packageType)," // content
+ " (SELECT COUNT(metricDef) FROM rt.metricDefinitions metricDef
WHERE metricDef.dataType = 3)," // calltime
+ " (SELECT COUNT(propDef) FROM rt.pluginConfigurationDefinition
pluginConfig JOIN pluginConfig.propertyDefinitions propDef WHERE propDef.name =
'snapshotLogEnabled')," //
- + " (SELECT COUNT(driftConfig) FROM rt.driftConfigurationTemplates
driftConfig)," // drift
+ + " (SELECT COUNT(driftDef) FROM rt.driftDefinitionTemplates
driftDef)," // drift
+ " (SELECT COUNT(bundleConfig) FROM rt.bundleConfiguration
bundleConfig)" // bundle
+ " ) " //
+ " FROM ResourceType rt " //
@@ -400,7 +400,7 @@ public class ResourceType implements Serializable,
Comparable<ResourceType> {
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "RHQ_DRIFT_TEMPLATE_MAP", joinColumns = @JoinColumn(name
= "RESOURCE_TYPE_ID", nullable = false), inverseJoinColumns = @JoinColumn(name =
"CONFIG_TEMPLATE_ID", nullable = false))
- private Set<ConfigurationTemplate> driftConfigurationTemplates = new
HashSet<ConfigurationTemplate>();
+ private Set<ConfigurationTemplate> driftDefinitionTemplates = new
HashSet<ConfigurationTemplate>();
// note that this is mapped to a Configuration entity, which is what it really is.
However, our getter/setter
// only provides access to this via ResourceTypeBundleConfiguration to encapsulate
the innards of this implementation
@@ -829,15 +829,15 @@ public class ResourceType implements Serializable,
Comparable<ResourceType> {
}
// this must return the actual set, not a copy - see the metadata manager SLSB for
when we update plugin metadata
- public Set<ConfigurationTemplate> getDriftConfigurationTemplates() {
- return driftConfigurationTemplates;
+ public Set<ConfigurationTemplate> getDriftDefinitionTemplates() {
+ return driftDefinitionTemplates;
}
- public void addDriftConfigurationTemplate(ConfigurationTemplate template) {
- if (driftConfigurationTemplates == null) {
- driftConfigurationTemplates = new HashSet<ConfigurationTemplate>(1);
+ public void addDriftDefinitionTemplate(ConfigurationTemplate template) {
+ if (driftDefinitionTemplates == null) {
+ driftDefinitionTemplates = new HashSet<ConfigurationTemplate>(1);
}
- driftConfigurationTemplates.add(template);
+ driftDefinitionTemplates.add(template);
}
@Override
diff --git
a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java
b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java
index 3540b29..ddf1ffe 100644
---
a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java
+++
b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java
@@ -15,17 +15,17 @@ import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.PropertyList;
import org.rhq.core.domain.configuration.PropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode;
+import org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
public class DriftConfigurationTest {
@Test
public void getCompareIgnoreIncludesExcludes() {
- DriftConfigurationComparator comparator = new
DriftConfigurationComparator(CompareMode.ONLY_BASE_INFO);
+ DriftDefinitionComparator comparator = new
DriftDefinitionComparator(CompareMode.ONLY_BASE_INFO);
- DriftConfiguration dc1 = new DriftConfiguration(new Configuration());
- DriftConfiguration dc2 = new DriftConfiguration(new Configuration());
+ DriftDefinition dc1 = new DriftDefinition(new Configuration());
+ DriftDefinition dc2 = new DriftDefinition(new Configuration());
// make sure our comparator can deal with all the nulls that are in empty
configs
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " +
dc2;
@@ -66,8 +66,8 @@ public class DriftConfigurationTest {
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " +
dc2; // sanity check - we should be back to equals
// add some includes and excludes that are different and test that they are
ignored by our comparator
- dc1.setBasedir(new
DriftConfiguration.BaseDirectory(BaseDirValueContext.fileSystem, "/foo"));
- dc2.setBasedir(new
DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"blah"));
+ dc1.setBasedir(new DriftDefinition.BaseDirectory(BaseDirValueContext.fileSystem,
"/foo"));
+ dc2.setBasedir(new
DriftDefinition.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"blah"));
dc1.addInclude(new Filter("ipath1", "ipattern1"));
dc2.addInclude(new Filter("ipath2", "ipattern2"));
dc1.addExclude(new Filter("epath1", "epattern1"));
@@ -76,18 +76,18 @@ public class DriftConfigurationTest {
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal (ignoring
basedir/includes/excludes) " + dc2;
// now show that our non-ignoring comparator would detect a different
- comparator = new
DriftConfigurationComparator(CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
+ comparator = new
DriftDefinitionComparator(CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal (not
ignoring basedir/includes/excludes) "
+ dc2;
}
@Test
public void getCompareBaseInfoAndIncludesExcludes() {
- DriftConfigurationComparator comparator = new DriftConfigurationComparator(
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
- DriftConfiguration dc1 = new DriftConfiguration(new Configuration());
- DriftConfiguration dc2 = new DriftConfiguration(new Configuration());
+ DriftDefinition dc1 = new DriftDefinition(new Configuration());
+ DriftDefinition dc2 = new DriftDefinition(new Configuration());
dc1.setEnabled(true);
dc1.setInterval(1000L);
@@ -104,11 +104,11 @@ public class DriftConfigurationTest {
@Test
public void getCompareOnlyIncludesExcludes() {
- DriftConfigurationComparator comparator = new DriftConfigurationComparator(
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
CompareMode.ONLY_DIRECTORY_SPECIFICATIONS);
- DriftConfiguration dc1 = new DriftConfiguration(new Configuration());
- DriftConfiguration dc2 = new DriftConfiguration(new Configuration());
+ DriftDefinition dc1 = new DriftDefinition(new Configuration());
+ DriftDefinition dc2 = new DriftDefinition(new Configuration());
dc1.setEnabled(false);
dc1.setInterval(1111L);
@@ -135,16 +135,16 @@ public class DriftConfigurationTest {
* @param dc1 the initial drift config1 to test
* @param dc2 the initial drift config2 to test
*/
- private void getCompareBaseInfoAndIncludesExcludes(DriftConfigurationComparator
comparator, DriftConfiguration dc1,
- DriftConfiguration dc2) {
+ private void getCompareBaseInfoAndIncludesExcludes(DriftDefinitionComparator
comparator, DriftDefinition dc1,
+ DriftDefinition dc2) {
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " +
dc2; // sanity check
- dc1.setBasedir(new
DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"hello.world"));
+ dc1.setBasedir(new
DriftDefinition.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"hello.world"));
assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " +
dc2;
assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " +
dc1;
- dc2.setBasedir(new
DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"hello.world"));
+ dc2.setBasedir(new
DriftDefinition.BaseDirectory(BaseDirValueContext.pluginConfiguration,
"hello.world"));
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal
" + dc2;
assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal
" + dc1;
@@ -201,8 +201,8 @@ public class DriftConfigurationTest {
assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " +
dc1;
// we don't provide an API to clear filters, so just create new drift configs
and test different excludes
- dc1 = new DriftConfiguration(new Configuration());
- dc2 = new DriftConfiguration(new Configuration());
+ dc1 = new DriftDefinition(new Configuration());
+ dc2 = new DriftDefinition(new Configuration());
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " +
dc2; // sanity check
dc1.addExclude(new Filter("epathA", "epatternA"));
dc2.addExclude(new Filter("epathZ", "epatternZ"));
@@ -216,7 +216,7 @@ public class DriftConfigurationTest {
Configuration config = new Configuration();
config.put(new PropertySimple("name", name));
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
assertEquals(driftConfig.getName(), name, "Failed to get drift configuration
name");
}
@@ -232,7 +232,7 @@ public class DriftConfigurationTest {
config.put(map);
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
assertEquals(driftConfig.getBasedir().getValueName(), basedir,
"Failed to get drift configuration base directory");
@@ -244,7 +244,7 @@ public class DriftConfigurationTest {
Configuration config = new Configuration();
config.put(new PropertySimple("interval", interval));
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
assertEquals(driftConfig.getInterval(), interval, "Failed to get drift
configuration interval");
}
@@ -254,7 +254,7 @@ public class DriftConfigurationTest {
DriftHandlingMode mode = DriftHandlingMode.normal;
Configuration config = new Configuration();
config.put(new
PropertySimple(DriftConfigurationDefinition.PROP_DRIFT_HANDLING_MODE, mode.name()));
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
assertEquals(driftConfig.getDriftHandlingMode(), mode, "Failed to get drift
configuration drift handling mode");
mode = DriftHandlingMode.plannedChanges;
@@ -278,7 +278,7 @@ public class DriftConfigurationTest {
config.put(includes);
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
List<Filter> actual = driftConfig.getIncludes();
List<Filter> expected = asList(new Filter(path1, pattern1), new
Filter(path2, pattern2));
@@ -303,7 +303,7 @@ public class DriftConfigurationTest {
config.put(excludes);
- DriftConfiguration driftConfig = new DriftConfiguration(config);
+ DriftDefinition driftConfig = new DriftDefinition(config);
List<Filter> actual = driftConfig.getExcludes();
List<Filter> expected = asList(new Filter(path1, pattern1), new
Filter(path2, pattern2));
diff --git
a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftSnapshotTest.java
b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftSnapshotTest.java
index 97f7faa..077f01b 100644
--- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftSnapshotTest.java
+++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftSnapshotTest.java
@@ -211,12 +211,12 @@ public class DriftSnapshotTest {
}
@Override
- public int getDriftConfigurationId() {
+ public int getDriftDefinitionId() {
return configId;
}
@Override
- public void setDriftConfigurationId(int id) {
+ public void setDriftDefinitionId(int id) {
configId = id;
}
diff --git
a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/ResourceTypeTest.java
b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/ResourceTypeTest.java
index 6a6ba13..a1f4340 100644
---
a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/ResourceTypeTest.java
+++
b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/ResourceTypeTest.java
@@ -89,7 +89,7 @@ public class ResourceTypeTest extends UnitilsTestNG {
public void findDriftConfigurationTemplates() {
ResourceType type = entityMgr.find(ResourceType.class, -8);
- assertEquals(type.getDriftConfigurationTemplates().size(), 2);
+ assertEquals(type.getDriftDefinitionTemplates().size(), 2);
}
void assertDeletedTypesIgnored(List<ResourceType> types) {
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManager.java
index f7787ad..1fc9fe9 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManager.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManager.java
@@ -26,7 +26,7 @@ import org.rhq.common.drift.ChangeSetReader;
import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
public interface ChangeSetManager {
@@ -34,32 +34,32 @@ public interface ChangeSetManager {
/**
* Locates the latest coverage change set for the specified resource id and drift
- * configuration.
+ * definition.
*
* @param resourceId The id of the resource to which the change set belongs
- * @param driftConfigurationName The name of the drift configuration for which the
+ * @param driftDefinitionName The name of the drift definition for which the
* change set was generated
* @return The change set file or null if it is not found
* @throws IOException
*/
- File findChangeSet(int resourceId, String driftConfigurationName) throws
IOException;
+ File findChangeSet(int resourceId, String driftDefinitionName) throws IOException;
File findChangeSet(int resourceId, String name, DriftChangeSetCategory type);
/**
- * Locates the latest change set for the given resource and drift configuration and
+ * Locates the latest change set for the given resource and drift definition and
* returns a ChangeSetReader for that change set. Note that a resource can have
- * multiple drift configurations; so, both the resource id and the drift
configuration
+ * multiple drift definitions; so, both the resource id and the drift definition
* are required to uniquely identify a particular change set.
*
* @param resourceId The id of the resource to which the change set belongs
- * @param driftConfigurationName The name of the drift configuration for which the
+ * @param driftDefinitionName The name of the drift definition for which the
* change set was generated
* @return A ChangeSetReader that is open on the change set identified by resourceId
- * and driftConfiguration. Returns null if no change set has previously been
generated.
+ * and driftDefinition. Returns null if no change set has previously been generated.
* @see ChangeSetReader
*/
- ChangeSetReader getChangeSetReader(int resourceId, String driftConfigurationName)
throws IOException;
+ ChangeSetReader getChangeSetReader(int resourceId, String driftDefinitionName) throws
IOException;
ChangeSetReader getChangeSetReader(File changeSetFile) throws IOException;
@@ -71,6 +71,6 @@ public interface ChangeSetManager {
void updateChangeSet(int resourceId, Headers headers) throws IOException;
- void addFileToChangeSet(int resourceId, DriftConfiguration driftConfiguration, File
file);
+ void addFileToChangeSet(int resourceId, DriftDefinition driftDefinition, File file);
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManagerImpl.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManagerImpl.java
index 6cc5e6d..132a7ca 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManagerImpl.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ChangeSetManagerImpl.java
@@ -19,6 +19,8 @@
package org.rhq.core.pc.drift;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -32,11 +34,9 @@ import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.ChangeSetWriterImpl;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.util.stream.StreamUtil;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-
public class ChangeSetManagerImpl implements ChangeSetManager {
private File changeSetsDir;
@@ -47,7 +47,7 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
@Override
public boolean changeSetExists(int resourceId, Headers headers) {
- File changeSetDir = findChangeSetDir(resourceId,
headers.getDriftConfigurationName());
+ File changeSetDir = findChangeSetDir(resourceId,
headers.getDriftDefinitionName());
if (changeSetDir == null || !changeSetDir.exists()) {
return false;
}
@@ -55,8 +55,8 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
}
@Override
- public File findChangeSet(int resourceId, String driftConfigurationName) throws
IOException {
- File changeSetDir = findChangeSetDir(resourceId, driftConfigurationName);
+ public File findChangeSet(int resourceId, String driftDefinitionName) throws
IOException {
+ File changeSetDir = findChangeSetDir(resourceId, driftDefinitionName);
File changeSetFile = new File(changeSetDir, "changeset.txt");
if (changeSetFile.exists()) {
@@ -85,9 +85,8 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
}
@Override
- public ChangeSetReader getChangeSetReader(int resourceId, String
driftConfigurationName)
- throws IOException {
- File changeSetFile = findChangeSet(resourceId, driftConfigurationName);
+ public ChangeSetReader getChangeSetReader(int resourceId, String driftDefinitionName)
throws IOException {
+ File changeSetFile = findChangeSet(resourceId, driftDefinitionName);
if (changeSetFile == null) {
return null;
@@ -104,7 +103,7 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
@Override
public ChangeSetWriter getChangeSetWriter(int resourceId, Headers headers) throws
IOException {
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, headers.getDriftConfigurationName());
+ File changeSetDir = new File(resourceDir, headers.getDriftDefinitionName());
if (!changeSetDir.exists()) {
changeSetDir.mkdirs();
@@ -127,7 +126,7 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
@Override
public ChangeSetWriter getChangeSetWriterForUpdate(int resourceId, Headers headers)
throws IOException {
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, headers.getDriftConfigurationName());
+ File changeSetDir = new File(resourceDir, headers.getDriftDefinitionName());
return new ChangeSetWriterImpl(new File(changeSetDir,
"changeset.working"), headers);
}
@@ -135,7 +134,7 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
@Override
public void updateChangeSet(int resourceId, Headers headers) throws IOException {
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, headers.getDriftConfigurationName());
+ File changeSetDir = new File(resourceDir, headers.getDriftDefinitionName());
File newChangeSet = new File(changeSetDir, "changeset.working");
File changeSet = new File(changeSetDir, "changeset.txt");
@@ -145,21 +144,21 @@ public class ChangeSetManagerImpl implements ChangeSetManager {
changeSet.delete();
- StreamUtil.copy(new BufferedInputStream(new FileInputStream(newChangeSet)),
- new BufferedOutputStream(new FileOutputStream(changeSet)));
+ StreamUtil.copy(new BufferedInputStream(new FileInputStream(newChangeSet)), new
BufferedOutputStream(
+ new FileOutputStream(changeSet)));
}
@Override
- public void addFileToChangeSet(int resourceId, DriftConfiguration driftConfiguration,
File file) {
+ public void addFileToChangeSet(int resourceId, DriftDefinition driftDefinition, File
file) {
}
- private File findChangeSetDir(int resourceId, String driftConfigurationName) {
+ private File findChangeSetDir(int resourceId, String driftDefinitionName) {
File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
if (!resourceDir.exists()) {
return null;
}
- return new File(resourceDir, driftConfigurationName);
+ return new File(resourceDir, driftDefinitionName);
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java
index 33d859f..8cbf2fc 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java
@@ -2,7 +2,7 @@ package org.rhq.core.pc.drift;
import java.io.File;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
/**
* This is a client interface to the server that drift-related tasks call to interact
with
@@ -18,11 +18,11 @@ public interface DriftClient {
* server, the content directory is purged.
*
* @param resourceId
- * @param driftConfigurationName
+ * @param driftDefinitionName
* @param contentDir
*/
- void sendChangeSetContentToServer(int resourceId, String driftConfigurationName, File
contentDir);
+ void sendChangeSetContentToServer(int resourceId, String driftDefinitionName, File
contentDir);
- File getAbsoluteBaseDirectory(int resourceId, DriftConfiguration
driftConfiguration);
+ File getAbsoluteBaseDirectory(int resourceId, DriftDefinition driftDefinition);
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionSchedule.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionSchedule.java
index 65e4b72..8ddfc03 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionSchedule.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionSchedule.java
@@ -2,7 +2,7 @@ package org.rhq.core.pc.drift;
import java.io.Serializable;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
public class DriftDetectionSchedule implements Comparable<DriftDetectionSchedule>,
Serializable {
@@ -10,13 +10,13 @@ public class DriftDetectionSchedule implements
Comparable<DriftDetectionSchedule
private int resourceId;
- private DriftConfiguration driftConfig;
+ private DriftDefinition driftDef;
private long nextScan;
- public DriftDetectionSchedule(int resourceId, DriftConfiguration configuration) {
+ public DriftDetectionSchedule(int resourceId, DriftDefinition definition) {
this.resourceId = resourceId;
- driftConfig = configuration;
+ this.driftDef = definition;
nextScan = -1;
}
@@ -24,8 +24,8 @@ public class DriftDetectionSchedule implements
Comparable<DriftDetectionSchedule
return resourceId;
}
- public DriftConfiguration getDriftConfiguration() {
- return driftConfig;
+ public DriftDefinition getDriftDefinition() {
+ return driftDef;
}
public long getNextScan() {
@@ -33,7 +33,7 @@ public class DriftDetectionSchedule implements
Comparable<DriftDetectionSchedule
}
public void updateShedule() {
- nextScan = System.currentTimeMillis() + (driftConfig.getInterval() * 1000);
+ nextScan = System.currentTimeMillis() + (driftDef.getInterval() * 1000);
}
public void resetSchedule() {
@@ -41,8 +41,8 @@ public class DriftDetectionSchedule implements
Comparable<DriftDetectionSchedule
}
public DriftDetectionSchedule copy() {
- DriftDetectionSchedule copy = new DriftDetectionSchedule(resourceId,
- new
DriftConfiguration(driftConfig.getConfiguration().deepCopyWithoutProxies()));
+ DriftDetectionSchedule copy = new DriftDetectionSchedule(resourceId, new
DriftDefinition(driftDef
+ .getConfiguration().deepCopyWithoutProxies()));
copy.nextScan = nextScan;
return copy;
}
@@ -85,7 +85,7 @@ public class DriftDetectionSchedule implements
Comparable<DriftDetectionSchedule
@Override
public String toString() {
- return getClass().getSimpleName() + "[resourceId: " + resourceId +
", driftConfigurationId: " +
- driftConfig.getId() + ", driftConfigurationName: " +
driftConfig.getName() + "]";
+ return getClass().getSimpleName() + "[resourceId: " + resourceId +
", driftDefinitionId: " + driftDef.getId()
+ + ", driftDefinitionName: " + driftDef.getName() + "]";
}
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
index 1aedea3..cba943f 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java
@@ -19,8 +19,15 @@
package org.rhq.core.pc.drift;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.common.drift.FileEntry.removedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+import static org.rhq.core.util.file.FileUtil.copyFile;
+import static org.rhq.core.util.file.FileUtil.forEachFile;
+
import java.io.File;
-import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
@@ -35,18 +42,10 @@ import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.file.FileVisitor;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
-import static org.rhq.core.util.file.FileUtil.copyFile;
-import static org.rhq.core.util.file.FileUtil.forEachFile;
-
public class DriftDetector implements Runnable {
private Log log = LogFactory.getLog(DriftDetector.class);
@@ -72,7 +71,7 @@ public class DriftDetector implements Runnable {
@Override
public void run() {
- log.debug("Starting drift detection...");
+ log.debug("Starting drift detection..");
long startTime = System.currentTimeMillis();
try {
if (log.isDebugEnabled()) {
@@ -95,35 +94,30 @@ public class DriftDetector implements Runnable {
return;
}
- if (!schedule.getDriftConfiguration().isEnabled()) {
- log.debug("Skipping " + schedule + " because the drift
configuration is disabled.");
+ if (!schedule.getDriftDefinition().isEnabled()) {
+ log.debug("Skipping " + schedule + " because the drift
definition is disabled.");
return;
}
- if (previousSnapshotExists(schedule)) {
- log.debug("Skipping " + schedule + " because server has
not yet acked previous change set");
- return;
- }
+ DriftDefinition driftDef = schedule.getDriftDefinition();
+ DriftChangeSetCategory changeSetType = null;
+ int changes = 0;
- DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
- detectionSummary.setSchedule(schedule);
try {
if (changeSetMgr.changeSetExists(schedule.getResourceId(),
createHeaders(schedule, COVERAGE, 0))) {
- detectionSummary.setType(DRIFT);
- generateDriftChangeSet(detectionSummary);
+ changeSetType = DRIFT;
+ changes = generateDriftChangeSet(schedule);
} else {
- detectionSummary.setType(COVERAGE);
- generateSnapshot(detectionSummary);
- }
- if (detectionSummary.getType() == COVERAGE ||
detectionSummary.getDriftChangeSet() != null) {
- driftClient.sendChangeSetToServer(detectionSummary);
+ changeSetType = COVERAGE;
+ generateSnapshot(schedule);
}
} catch (IOException e) {
- log.error("Drift detection failed: " + e.getMessage(), e);
- revertSnapshot(detectionSummary);
- } catch (RuntimeException e) {
- log.error("Drift detection failed: " + e.getMessage(), e);
- revertSnapshot(detectionSummary);
+ // TODO Call ChangeSetManager here to rollback any thing that was written
to disk.
+ log.error("An error occurred while scanning for drift", e);
+ }
+
+ if (changeSetType == COVERAGE || changes > 0) {
+ driftClient.sendChangeSetToServer(schedule.getResourceId(), driftDef,
changeSetType);
}
} catch (Throwable t) {
Throwable cause = t.getCause();
@@ -144,22 +138,12 @@ public class DriftDetector implements Runnable {
}
}
- private boolean previousSnapshotExists(DriftDetectionSchedule schedule) {
- File snapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), COVERAGE);
- File previousSnapshot = new File(snapshot.getParentFile(), snapshot.getName() +
".previous");
- return previousSnapshot.exists();
- }
-
- private void generateDriftChangeSet(DriftDetectionSummary summary) throws IOException
{
- final DriftDetectionSchedule schedule = summary.getSchedule();
-
+ private int generateDriftChangeSet(final DriftDetectionSchedule schedule) throws
IOException {
log.debug("Generating drift change set for " + schedule);
- final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftConfiguration()));
- File currentSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), COVERAGE);
- final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(currentSnapshot);
+ final File basedir = new File(basedir(schedule.getResourceId(),
schedule.getDriftDefinition()));
+ final ChangeSetReader coverageReader =
changeSetMgr.getChangeSetReader(schedule.getResourceId(), schedule
+ .getDriftDefinition().getName());
final Set<File> processedFiles = new HashSet<File>();
final List<FileEntry> snapshotEntries = new LinkedList<FileEntry>();
final List<FileEntry> deltaEntries = new LinkedList<FileEntry>();
@@ -170,22 +154,16 @@ public class DriftDetector implements Runnable {
File file = new File(basedir, entry.getFile());
if (!file.exists()) {
// The file has been deleted since the last scan
- if (log.isDebugEnabled()) {
- log.debug("Detected deleted file for " + schedule + "
--> " + file.getAbsolutePath());
- }
- deltaEntries.add(removedFileEntry(entry.getFile(), entry.getNewSHA()));
- } else if (!file.canRead()) {
- processedFiles.add(file);
- if (log.isDebugEnabled()) {
- log.debug(file.getPath() + " is no longer readable. Treating it
as a deleted file.");
+ if (log.isInfoEnabled()) {
+ log.info("Detected deleted file for " + schedule + "
--> " + file.getAbsolutePath());
}
deltaEntries.add(removedFileEntry(entry.getFile(), entry.getNewSHA()));
} else {
processedFiles.add(file);
String currentSHA = sha256(file);
if (!currentSHA.equals(entry.getNewSHA())) {
- if (log.isDebugEnabled()) {
- log.debug("Detected modified file for " + schedule +
" --> " + file.getAbsolutePath());
+ if (log.isInfoEnabled()) {
+ log.info("Detected modified file for " + schedule +
" --> " + file.getAbsolutePath());
}
FileEntry modifiedEntry = changedFileEntry(entry.getFile(),
entry.getNewSHA(), currentSHA);
deltaEntries.add(modifiedEntry);
@@ -200,100 +178,79 @@ public class DriftDetector implements Runnable {
// If the basedir is still valid we need to do a directory tree scan to look for
newly added files
if (basedir.isDirectory()) {
- forEachFile(basedir, new FilterFileVisitor(basedir,
schedule.getDriftConfiguration().getIncludes(),
- schedule.getDriftConfiguration().getExcludes(), new FileVisitor() {
- @Override
- public void visit(File file) {
- try {
- if (processedFiles.contains(file)) {
- return;
- }
-
- if (!file.canRead()) {
- if (log.isDebugEnabled()) {
- log.debug("Skipping " + file.getPath() +
" since it is not readable.");
- return;
- }
- }
-
- if (log.isInfoEnabled()) {
- log.info("Detected added file for " + schedule
+ " --> " + file.getAbsolutePath());
- }
+ forEachFile(basedir, new FilterFileVisitor(basedir,
schedule.getDriftDefinition().getIncludes(), schedule
+ .getDriftDefinition().getExcludes(), new FileVisitor() {
+ @Override
+ public void visit(File file) {
+ try {
+ if (processedFiles.contains(file)) {
+ return;
+ }
- FileEntry newEntry = addedFileEntry(relativePath(basedir,
file), sha256(file));
- deltaEntries.add(newEntry);
- snapshotEntries.add(newEntry);
- } catch (IOException e) {
- log.error("An error occurred while generating a drift
change set for " + schedule + ": "
- + e.getMessage());
- throw new DriftDetectionException("An error occurred
while generating a drift change set",
- e);
+ if (log.isInfoEnabled()) {
+ log.info("Detected added file for " + schedule +
" --> " + file.getAbsolutePath());
}
+
+ FileEntry newEntry = addedFileEntry(relativePath(basedir, file),
sha256(file));
+ deltaEntries.add(newEntry);
+ snapshotEntries.add(newEntry);
+ } catch (IOException e) {
+ log.error("An error occurred while generating a drift change
set for " + schedule + ": "
+ + e.getMessage());
+ throw new DriftDetectionException("An error occurred while
generating a drift change set", e);
}
- }));
+ }
+ }));
}
if (deltaEntries.isEmpty()) {
// If nothing has changed, there is no need to add/update any files
- summary.setNewSnapshot(currentSnapshot);
- } else {
- File oldSnapshot = new File(currentSnapshot.getParentFile(),
currentSnapshot.getName() +
- ".previous");
- copyFile(currentSnapshot, oldSnapshot);
- currentSnapshot.delete();
-
- Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
- Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
-
- File driftChangeSet = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), DRIFT);
- ChangeSetWriter deltaWriter = changeSetMgr.getChangeSetWriter(driftChangeSet,
deltaHeaders);
-
- File newSnapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
- schedule.getDriftConfiguration().getName(), COVERAGE);
- ChangeSetWriter newSnapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(),
- snapshotHeaders);
-
- summary.setDriftChangeSet(driftChangeSet);
- summary.setNewSnapshot(newSnapshot);
- summary.setOldSnapshot(oldSnapshot);
-
- for (FileEntry entry : deltaEntries) {
- deltaWriter.write(entry);
- }
- deltaWriter.close();
+ return 0;
+ }
- for (FileEntry entry : snapshotEntries) {
- newSnapshotWriter.write(entry);
- }
- newSnapshotWriter.close();
+ File snapshotFile = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftDefinition()
+ .getName(), COVERAGE);
+ File backupSnapshotFile = new File(snapshotFile.getParentFile(),
snapshotFile.getName() + ".bak");
+ copyFile(snapshotFile, snapshotFile);
+
+ Headers deltaHeaders = createHeaders(schedule, DRIFT, newVersion);
+ Headers snapshotHeaders = createHeaders(schedule, COVERAGE, newVersion);
+
+ ChangeSetWriter deltaWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), deltaHeaders);
+ ChangeSetWriter snapshotWriter =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), snapshotHeaders);
+
+ for (FileEntry entry : deltaEntries) {
+ deltaWriter.write(entry);
+ }
+ deltaWriter.close();
+
+ for (FileEntry entry : snapshotEntries) {
+ snapshotWriter.write(entry);
}
+ snapshotWriter.close();
+ backupSnapshotFile.delete();
+
+ return deltaEntries.size();
}
- private void generateSnapshot(DriftDetectionSummary summary) throws IOException {
- final DriftDetectionSchedule schedule = summary.getSchedule();
+ private void generateSnapshot(final DriftDetectionSchedule schedule) throws
IOException {
log.debug("Generating coverage change set for " + schedule);
- File snapshot = changeSetMgr.findChangeSet(schedule.getResourceId(),
schedule.getDriftConfiguration().getName(),
- COVERAGE);
- final ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(snapshot,
createHeaders(schedule, COVERAGE, 0));
- final DriftConfiguration config = schedule.getDriftConfiguration();
- final File basedir = new File(basedir(schedule.getResourceId(), config));
+ final ChangeSetWriter writer =
changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(
+ schedule, COVERAGE, 0));
+ final DriftDefinition driftDef = schedule.getDriftDefinition();
+ final File basedir = new File(basedir(schedule.getResourceId(), driftDef));
if (basedir.isDirectory()) {
- forEachFile(basedir, new FilterFileVisitor(basedir, config.getIncludes(),
config.getExcludes(),
+ forEachFile(basedir, new FilterFileVisitor(basedir, driftDef.getIncludes(),
driftDef.getExcludes(),
new FileVisitor() {
@Override
public void visit(File file) {
try {
- if (!file.canRead()) {
- if (log.isDebugEnabled()) {
- log.debug("Skipping " + file.getPath() +
" since it is not readable.");
- }
- return;
- }
- if (log.isDebugEnabled()) {
- log.debug("Adding " + file.getPath() + "
to coverage change set for " + schedule);
+ if (log.isInfoEnabled()) {
+ log
+ .info("Adding " + file.getAbsolutePath() +
" to coverage change set for "
+ + schedule);
}
writer.write(addedFileEntry(relativePath(basedir, file),
sha256(file)));
} catch (IOException e) {
@@ -306,7 +263,6 @@ public class DriftDetector implements Runnable {
}));
}
writer.close();
- summary.setNewSnapshot(snapshot);
}
private String relativePath(File basedir, File file) {
@@ -320,66 +276,20 @@ public class DriftDetector implements Runnable {
return digestGenerator.calcDigestString(file);
}
- private String basedir(int resourceId, DriftConfiguration driftConfig) {
- return driftClient.getAbsoluteBaseDirectory(resourceId,
driftConfig).getAbsolutePath();
+ private String basedir(int resourceId, DriftDefinition driftDef) {
+ return driftClient.getAbsoluteBaseDirectory(resourceId,
driftDef).getAbsolutePath();
}
private Headers createHeaders(DriftDetectionSchedule schedule, DriftChangeSetCategory
type, int version) {
Headers headers = new Headers();
headers.setResourceId(schedule.getResourceId());
- headers.setDriftCofigurationId(schedule.getDriftConfiguration().getId());
- headers.setDriftConfigurationName(schedule.getDriftConfiguration().getName());
- headers.setBasedir(basedir(schedule.getResourceId(),
schedule.getDriftConfiguration()));
+ headers.setDriftDefinitionId(schedule.getDriftDefinition().getId());
+ headers.setDriftDefinitionName(schedule.getDriftDefinition().getName());
+ headers.setBasedir(basedir(schedule.getResourceId(),
schedule.getDriftDefinition()));
headers.setType(type);
headers.setVersion(version);
return headers;
}
- private void revertSnapshot(DriftDetectionSummary summary) throws IOException {
- log.info("Reverting snapshot for " + summary.getSchedule());
-
- DriftDetectionSchedule scheudle = summary.getSchedule();
- File newSnapshot = changeSetMgr.findChangeSet(scheudle.getResourceId(),
- scheudle.getDriftConfiguration().getName(), COVERAGE);
-
- // We want to delete the snapshot file regardless of whether the drift detection
- // was for an initial coverage change set or for a drift change set. We do not
know
- // the state of the snapshot file so we have to delete it. If we have only
generated
- // the initial coverage change set, then it will get regenerated.
- newSnapshot.delete();
-
- if (summary.getType() == DRIFT) {
- File oldSnapshotBackup = summary.getOldSnapshot();
- // If we generated a drift change set, we need to check for a back up of the
- // previous snapshot. We revert to the back up. If no back up is found, we
log
- // an error.
- if (oldSnapshotBackup != null && oldSnapshotBackup.exists()) {
- copyFile(oldSnapshotBackup, newSnapshot);
- // We have to delete to the previous version snapshot file; otherwise,
- // subsequent detection runs will be skipped.
- oldSnapshotBackup.delete();
- } else {
- // TODO Should we throw an exception and/or disable detection?
- // If we fall into this else block, that means we were not able to
revert
- // to the previous snapshot version, and we may be in an inconsistent
state.
- log.error("Cannot revert snapshot to previous version for " +
summary.getSchedule() +
- ". Snapshot back up file not found.");
- }
- }
- deleteZipFiles(newSnapshot.getParentFile());
- }
-
- private void deleteZipFiles(File dir) {
- File[] files = dir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.endsWith(".zip");
- }
- });
- for (File file : files) {
- file.delete();
- }
- }
-
}
\ No newline at end of file
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java
index 5cd4d4b..9bfd900 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java
@@ -51,7 +51,7 @@ public class DriftFilesSender implements Runnable {
@Override
public void run() {
try {
- File changeSet = changeSetMgr.findChangeSet(resourceId,
headers.getDriftConfigurationName());
+ File changeSet = changeSetMgr.findChangeSet(resourceId,
headers.getDriftDefinitionName());
File contentDir = new File(changeSet.getParentFile(), "content");
contentDir.mkdir();
@@ -63,14 +63,14 @@ public class DriftFilesSender implements Runnable {
copyFile(file, new File(contentDir, driftFile.getHashId()));
}
}
- driftClient.sendChangeSetContentToServer(resourceId,
headers.getDriftConfigurationName(), contentDir);
+ driftClient.sendChangeSetContentToServer(resourceId,
headers.getDriftDefinitionName(), contentDir);
} catch (IOException e) {
log.error("Failed to send drift files.", e);
}
}
private File find(DriftFile driftFile) throws IOException {
- ChangeSetReader reader = changeSetMgr.getChangeSetReader(resourceId,
headers.getDriftConfigurationName());
+ ChangeSetReader reader = changeSetMgr.getChangeSetReader(resourceId,
headers.getDriftDefinitionName());
for (FileEntry entry : reader) {
if (entry.getNewSHA().equals(driftFile.getHashId())) {
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
index 8fd065f..f655dd7 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java
@@ -19,13 +19,17 @@
package org.rhq.core.pc.drift;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.common.drift.FileEntry.removedFileEntry;
+import static
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
+import static org.rhq.core.util.file.FileUtil.purge;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
-import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -42,7 +46,9 @@ import org.rhq.core.clientapi.agent.drift.DriftAgentService;
import org.rhq.core.clientapi.server.drift.DriftServerService;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.drift.Drift;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftChangeSetCategory;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.resource.Resource;
@@ -55,12 +61,6 @@ import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.measurement.MeasurementManager;
import org.rhq.core.util.stream.StreamUtil;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.common.drift.FileEntry.removedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.util.file.FileUtil.purge;
-
public class DriftManager extends AgentService implements DriftAgentService, DriftClient,
ContainerService {
private final Log log = LogFactory.getLog(DriftManager.class);
@@ -94,7 +94,6 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
@Override
public void initialize() {
- long initStartTime = System.currentTimeMillis();
changeSetsDir.mkdir();
changeSetMgr = new ChangeSetManagerImpl(changeSetsDir);
@@ -107,13 +106,9 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
long startTime = System.currentTimeMillis();
initSchedules(inventoryMgr.getPlatform(), inventoryMgr);
long endTime = System.currentTimeMillis();
+ log.info("Finished initializing drift detection schedules in " +
(endTime - startTime) + " ms");
- if (log.isInfoEnabled()) {
- log.info("Finished initializing drift detection schedules in " +
(endTime - startTime) + " ms");
- }
-
- scanForContentToResend();
- purgeDeletedDriftConfigDirs();
+ purgeDeletedDriftDefDirs();
driftThreadPool = new ScheduledThreadPoolExecutor(5);
@@ -127,10 +122,6 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
initialized = true;
- long initEndTime = System.currentTimeMillis();
- if (log.isInfoEnabled()) {
- log.info("Finished initialization in " + (initEndTime -
initStartTime) + " ms");
- }
}
private void initSchedules(Resource r, InventoryManager inventoryMgr) {
@@ -146,13 +137,13 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
log.debug("Rescheduling drift detection for " + r);
- for (DriftConfiguration c : container.getDriftConfigurations()) {
+ for (DriftDefinition c : container.getDriftDefinitions()) {
try {
syncWithServer(r, c);
schedulesQueue.addSchedule(new DriftDetectionSchedule(r.getId(), c));
} catch (IOException e) {
- log.error("Failed to sync with server for " + toString(r, c) +
". Drift detection will not be " +
- "scheduled.", e);
+ log.error("Failed to sync with server for " + toString(r, c) +
". Drift detection will not be "
+ + "scheduled.", e);
}
}
@@ -161,101 +152,78 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
- private void syncWithServer(Resource resource, DriftConfiguration configuration)
throws IOException {
- Headers headers = createHeaders(resource, configuration);
+ private void syncWithServer(Resource resource, DriftDefinition driftDef) throws
IOException {
+ Headers headers = createHeaders(resource, driftDef);
if (!changeSetMgr.changeSetExists(resource.getId(), headers)) {
- log.info("No snapshot found for " + toString(resource,
configuration) + ". Downloading snapshot from " +
- "server");
+ log.info("No snapshot found for " + toString(resource, driftDef) +
". Downloading snapshot from "
+ + "server");
DriftSnapshot snapshot =
pluginContainerConfiguration.getServerServices().getDriftServerService()
- .getCurrentSnapshot(configuration.getId());
+ .getCurrentSnapshot(driftDef.getId());
if (snapshot.getVersion() == -1) {
// A version of -1 indicates that no change sets have been reported
- // for this configuration. This can occur when a user creates a
- // drift configuration while the agent is offline for example. At
+ // for this def. This can occur when a user creates a
+ // drift def while the agent is offline for example. At
// this point we just return and allow the agent to generate the
// initial snapshot file.
if (log.isDebugEnabled()) {
- log.debug("The server does not have any change sets for " +
toString(resource, configuration) +
- ". An initial snapshot needs to be generated.");
+ log.debug("The server does not have any change sets for " +
toString(resource, driftDef)
+ + ". An initial snapshot needs to be generated.");
}
return;
}
- headers.setVersion(snapshot.getVersion());
-
- log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for " +
- toString(resource, configuration));
+ log.info("Preparing to write snapshot at version " +
snapshot.getVersion() + " to disk for "
+ + toString(resource, driftDef));
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resource.getId(),
headers);
for (Drift drift : snapshot.getEntries()) {
switch (drift.getCategory()) {
- case FILE_ADDED:
- writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
- break;
- case FILE_CHANGED:
- writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(),
- drift.getNewDriftFile().getHashId()));
- break;
- default: // FILE_REMOVED
- writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
+ case FILE_ADDED:
+ writer.write(addedFileEntry(drift.getPath(),
drift.getNewDriftFile().getHashId()));
+ break;
+ case FILE_CHANGED:
+ writer.write(changedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId(), drift
+ .getNewDriftFile().getHashId()));
+ break;
+ default: // FILE_REMOVED
+ writer.write(removedFileEntry(drift.getPath(),
drift.getOldDriftFile().getHashId()));
}
}
writer.close();
}
}
- private void purgeDeletedDriftConfigDirs() {
- log.info("Checking for deleted drift configurations");
+ private void purgeDeletedDriftDefDirs() {
+ log.info("Checking for deleted drift definitions");
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
+ BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
for (File resourceDir : changeSetsDir.listFiles()) {
int resourceId = Integer.parseInt(resourceDir.getName());
- for (File configDir : resourceDir.listFiles()) {
- DriftConfiguration config = new DriftConfiguration(new Configuration());
- config.setName(configDir.getName());
- if (!schedulesQueue.contains(resourceId, config)) {
- log.info("Detected deleted drift configuration,
DriftConfiguration[name: " + config.getName() +
- ", resourceId: " + resourceId + "]");
- log.info("Deleting drift configuration directory " +
configDir.getPath());
- purge(configDir, true);
- }
- }
- }
- }
-
- /**
- * Scans the changesets directory for any change set content zip files. This method
- * assumes that any content zip files found have not been received or persisted by
the
- * server. Each content zip file is resent to the server.
- */
- public void scanForContentToResend() {
- log.info("Scanning for change set content to resend...");
- for (File resourceDir : changeSetsDir.listFiles()) {
- for (File configDir : resourceDir.listFiles()) {
- for (File contentZipFile : configDir.listFiles(new
ZipFileNameFilter("content_"))) {
- if (log.isDebugEnabled()) {
- log.debug("Resending " + contentZipFile.getPath());
- }
- sendContentZipFile(Integer.parseInt(resourceDir.getName()),
configDir.getName(), contentZipFile);
+ for (File defDir : resourceDir.listFiles()) {
+ DriftDefinition def = new DriftDefinition(new Configuration());
+ def.setName(defDir.getName());
+ if (!schedulesQueue.contains(resourceId, def)) {
+ log.info("Detected deleted drift definition,
DriftDefinition[name: " + def.getName()
+ + ", resourceId: " + resourceId + "]");
+ log.info("Deleting drift definition directory " +
defDir.getPath());
+ purge(defDir, true);
}
}
}
}
- private String toString(Resource r, DriftConfiguration c) {
- return toString(r.getId(), c);
+ private String toString(Resource r, DriftDefinition c) {
+ return "DriftDefinition[id: " + c.getId() + ", resourceId: "
+ r.getId() + ", name: " + c.getName() + "]";
}
- private String toString(int resourceId, DriftConfiguration c) {
- return "DriftConfiguration[id: " + c.getId() + ", resourceId:
" + resourceId + ", name: " + c.getName() + "]";
- }
-
- private Headers createHeaders(Resource resource, DriftConfiguration configuration) {
+ private Headers createHeaders(Resource resource, DriftDefinition driftDef) {
Headers headers = new Headers();
headers.setResourceId(resource.getId());
- headers.setDriftCofigurationId(configuration.getId());
- headers.setType(COVERAGE);
- headers.setDriftConfigurationName(configuration.getName());
- headers.setBasedir(getAbsoluteBaseDirectory(resource.getId(),
configuration).getAbsolutePath());
+ headers.setDriftDefinitionId(driftDef.getId());
+ headers.setType(DriftChangeSetCategory.COVERAGE);
+ headers.setDriftDefinitionName(driftDef.getName());
+ headers.setBasedir(getAbsoluteBaseDirectory(resource.getId(),
driftDef).getAbsolutePath());
return headers;
}
@@ -288,70 +256,55 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
- int resourceId = detectionSummary.getSchedule().getResourceId();
- DriftConfiguration driftConfiguration =
detectionSummary.getSchedule().getDriftConfiguration();
-
- if (!schedulesQueue.contains(resourceId, driftConfiguration)) {
- return;
- }
+ public void sendChangeSetToServer(int resourceId, DriftDefinition driftDef,
DriftChangeSetCategory type) {
+ try {
+ if (!schedulesQueue.contains(resourceId, driftDef)) {
+ return;
+ }
- File changeSetFile;
- if (detectionSummary.getType() == COVERAGE) {
- changeSetFile = detectionSummary.getNewSnapshot();
- } else {
- changeSetFile = detectionSummary.getDriftChangeSet();
- }
- if (changeSetFile == null) {
- log.warn("changeset[resourceId: " + resourceId + ",
driftConfiguration: " +
- driftConfiguration.getName() + "] was not found. Cancelling request
to send change set " +
- "to server");
- return;
- }
+ File changeSetFile = changeSetMgr.findChangeSet(resourceId,
driftDef.getName(), type);
+ if (changeSetFile == null) {
+ log.warn("changeset[resourceId: " + resourceId + ",
driftDefinition: " + driftDef.getName()
+ + "] was not found. Cancelling request to send change set "
+ "to server");
+ return;
+ }
- DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
- String fileName = "changeset_" + System.currentTimeMillis() +
".zip";
- final File zipFile = new File(changeSetFile.getParentFile(), fileName);
- ZipOutputStream stream = null;
+ // TODO Include the version in the change set file name to ensure the file
name is unique
+ String fileName = "changeset_" + System.currentTimeMillis() +
".zip";
+ final File zipFile = new File(changeSetFile.getParentFile(), fileName);
+ ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
- try {
- stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
FileInputStream fis = new FileInputStream(changeSetFile);
stream.putNextEntry(new ZipEntry(changeSetFile.getName()));
StreamUtil.copy(fis, stream, false);
fis.close();
stream.close();
- } catch (IOException e) {
- zipFile.delete();
- throw new DriftDetectionException("Failed to create change set zip file
" + zipFile.getPath(), e);
- } finally {
- try {
- if (stream != null) {
- stream.close();
- }
- } catch (IOException e) {
- log.warn("An error occurred while trying to close change set zip
file output stream", e);
- }
- }
- try {
- driftServer.sendChangesetZip(resourceId, zipFile.length(),
remoteInputStream(new BufferedInputStream(
- new FileInputStream(zipFile))));
+ // We want to clean up after we send the zip file to the server. We do this
by
+ // deleting the files in the content directory and the content zip itself.
They
+ // are no longer needed after being sent to the server. We cannot
immediately
+ // delete the content zip file though because it is sent asynchronously, and
we
+ // wind up deleting it before it is sent. The following approach allows us
to
+ // safely delete it when the comm layer closes the remote input stream.
+ //
+ // jsanda
+ DriftInputStream inputStream = new DriftInputStream(new
BufferedInputStream(new FileInputStream(zipFile)),
+ new DeleteFile(zipFile));
+
+ driftServer.sendChangesetZip(resourceId, zipFile.length(),
remoteInputStream(inputStream));
+
} catch (IOException e) {
- throw new DriftDetectionException("Failed to set change set for "
+
- toString(resourceId, driftConfiguration) + " to server");
- } catch (RuntimeException e) {
- throw new DriftDetectionException("Failed to set change set for "
+
- toString(resourceId, driftConfiguration) + " to server");
+ log.error("An error occurred while trying to send changeset[resourceId:
" + resourceId
+ + ", driftDefinition: " + driftDef.getName() + "]",
e);
}
}
@Override
- public void sendChangeSetContentToServer(int resourceId, String
driftConfigurationName, final File contentDir) {
+ public void sendChangeSetContentToServer(int resourceId, String driftDefName, final
File contentDir) {
try {
- String timestamp = Long.toString(System.currentTimeMillis());
- String contentFileName = "content_" + timestamp +
".zip";
+ String contentFileName = "content_" + System.currentTimeMillis() +
".zip";
final File zipFile = new File(contentDir.getParentFile(), contentFileName);
ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new
FileOutputStream(zipFile)));
@@ -363,13 +316,22 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
stream.close();
-// DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
-// driftServer.sendFilesZip(resourceId, driftConfigurationName, timestamp,
zipFile.length(),
-// remoteInputStream(new BufferedInputStream(new
FileInputStream(zipFile))));
- sendContentZipFile(resourceId, driftConfigurationName, zipFile);
+ // We want to clean up after we send the zip file to the server. We do this
by
+ // deleting the files in the content directory and the content zip itself.
They
+ // are no longer needed after being sent to the server. We cannot
immediately
+ // delete the content zip file though because it is sent asynchronously, and
we
+ // wind up deleting it before it is sent. The following approach allows us
to
+ // safely delete it when the comm layer closes the remote input stream.
+ //
+ // jsanda
+ DriftInputStream inputStream = new DriftInputStream(new
BufferedInputStream(new FileInputStream(zipFile)),
+ new DeleteFile(zipFile));
+
+ DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
+ driftServer.sendFilesZip(resourceId, zipFile.length(),
remoteInputStream(inputStream));
} catch (IOException e) {
log.error("An error occurred while trying to send content for
changeset[resourceId: " + resourceId
- + ", driftConfiguration: " + driftConfigurationName +
"]", e);
+ + ", driftDefinition: " + driftDefName + "]", e);
}
for (File file : contentDir.listFiles()) {
@@ -379,34 +341,17 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
}
- private void sendContentZipFile(int resourceId, String driftConfigName, File
contentZipFile) {
- try {
- int startIndex = "content_".length();
- int endIndex = contentZipFile.getName().indexOf(".");
- String token = contentZipFile.getName().substring(startIndex, endIndex);
-
- DriftServerService driftServer =
pluginContainerConfiguration.getServerServices().getDriftServerService();
- driftServer.sendFilesZip(resourceId, driftConfigName, token,
contentZipFile.length(),
- remoteInputStream(new BufferedInputStream(new
FileInputStream(contentZipFile))));
- } catch (FileNotFoundException e) {
- log.error("An error occurred while trying to send change set content zip
file " +
- contentZipFile.getPath() + " to server.", e);
- }
- }
-
@Override
- public void detectDrift(int resourceId, DriftConfiguration driftConfiguration) {
+ public void detectDrift(int resourceId, DriftDefinition driftDef) {
if (log.isInfoEnabled()) {
log.info("Received request to schedule drift detection immediately for
[resourceId: " + resourceId
- + ", driftConfigurationId: " + driftConfiguration.getId() +
", driftConfigurationName: "
- + driftConfiguration.getName() + "]");
+ + ", driftDefId: " + driftDef.getId() + ", driftDefName:
" + driftDef.getName() + "]");
}
- DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId,
driftConfiguration);
+ DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId, driftDef);
if (schedule == null) {
- log.warn("No schedule found in the queue for [resourceId: " +
resourceId + ", driftConfigurationId: "
- + driftConfiguration.getId() + ", driftConfigurationName: " +
driftConfiguration.getName() + "]. No "
- + " work will be scheduled.");
+ log.warn("No schedule found in the queue for [resourceId: " +
resourceId + ", driftDefId: "
+ + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"]. No " + " work will be scheduled.");
return;
}
log.debug("Resetting " + schedule + " for immediate
detection.");
@@ -423,8 +368,8 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void scheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId,
driftConfiguration);
+ public void scheduleDriftDetection(int resourceId, DriftDefinition driftDef) {
+ DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId,
driftDef);
if (log.isInfoEnabled()) {
log.info("Scheduling drift detection for " + schedule);
}
@@ -436,7 +381,7 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
ResourceContainer container =
getInventoryManager().getResourceContainer(resourceId);
if (container != null) {
- container.addDriftConfiguration(driftConfiguration);
+ container.addDriftDefinition(driftDef);
}
} else {
log.warn("Failed to add " + schedule + " to " +
schedulesQueue);
@@ -446,9 +391,8 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
@Override
public boolean requestDriftFiles(int resourceId, Headers headers, List<? extends
DriftFile> driftFiles) {
if (log.isInfoEnabled()) {
- log.info("Server is requesting files for [resourceId: " +
resourceId + ", driftConfigurationId: " +
- headers.getDriftCofigurationId() + ", driftConfigurationName: "
+ headers.getDriftConfigurationName() +
- "]");
+ log.info("Server is requesting files for [resourceId: " +
resourceId + ", driftDefId: "
+ + headers.getDriftDefinitionId() + ", driftDefName: " +
headers.getDriftDefinitionName() + "]");
}
DriftFilesSender sender = new DriftFilesSender();
sender.setResourceId(resourceId);
@@ -463,26 +407,24 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void unscheduleDriftDetection(final int resourceId, final DriftConfiguration
driftConfiguration) {
- log.info("Received request to unschedule drift detection for
[resourceId:" + resourceId +
- ", driftConfigurationId: " + driftConfiguration.getId() + ",
driftConfigurationName: " +
- driftConfiguration.getName() + "].");
-
- DriftDetectionSchedule schedule = schedulesQueue.removeAndExecute(resourceId,
driftConfiguration,
- new Runnable() {
- @Override
- public void run() {
- File resourceDir = new File(changeSetsDir,
Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir,
driftConfiguration.getName());
- purge(changeSetDir, true);
-
- log.debug("Removed change set directory " +
changeSetDir.getAbsolutePath());
- }
- });
+ public void unscheduleDriftDetection(final int resourceId, final DriftDefinition
driftDef) {
+ log.info("Received request to unschedule drift detection for
[resourceId:" + resourceId + ", driftDefId: "
+ + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"].");
+
+ DriftDetectionSchedule schedule = schedulesQueue.removeAndExecute(resourceId,
driftDef, new Runnable() {
+ @Override
+ public void run() {
+ File resourceDir = new File(changeSetsDir,
Integer.toString(resourceId));
+ File changeSetDir = new File(resourceDir, driftDef.getName());
+ purge(changeSetDir, true);
+
+ log.debug("Removed change set directory " +
changeSetDir.getAbsolutePath());
+ }
+ });
if (schedule != null) {
ResourceContainer container =
getInventoryManager().getResourceContainer(resourceId);
if (container != null) {
- container.removeDriftConfiguration(schedule.getDriftConfiguration());
+ container.removeDriftDefinition(schedule.getDriftDefinition());
}
}
@@ -493,15 +435,15 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
}
@Override
- public void updateDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
- log.info("Received request to update schedule for [resourceId: " +
resourceId + ", driftConfigurationId: " +
- driftConfiguration.getId() + ", driftConfigurationName: " +
driftConfiguration.getName() + "]");
- DriftDetectionSchedule updatedSchedule = schedulesQueue.update(resourceId,
driftConfiguration);
+ public void updateDriftDetection(int resourceId, DriftDefinition driftDef) {
+ log.info("Received request to update schedule for [resourceId: " +
resourceId + ", driftDefId: "
+ + driftDef.getId() + ", driftDefName: " + driftDef.getName() +
"]");
+ DriftDetectionSchedule updatedSchedule = schedulesQueue.update(resourceId,
driftDef);
if (updatedSchedule == null) {
- updatedSchedule = new DriftDetectionSchedule(resourceId,
driftConfiguration);
+ updatedSchedule = new DriftDetectionSchedule(resourceId, driftDef);
if (log.isInfoEnabled()) {
- log.info("No matching schedule was found in the queue. This must be
a request to add a new " +
- "schedule. Adding " + updatedSchedule + " to " +
schedulesQueue);
+ log.info("No matching schedule was found in the queue. This must be
a request to add a new "
+ + "schedule. Adding " + updatedSchedule + " to "
+ schedulesQueue);
}
boolean added = schedulesQueue.addSchedule(updatedSchedule);
if (added) {
@@ -522,65 +464,21 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
InventoryManager inventoryMgr =
PluginContainer.getInstance().getInventoryManager();
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
if (container != null) {
- container.addDriftConfiguration(driftConfiguration);
- }
- }
-
- @Override
- public void ackChangeSet(int resourceId, String driftConfigName) {
- log.info("Received server change set ack for [resourceId: " +
resourceId + ", driftConfiguration:" +
- driftConfigName + "]");
-
- File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, driftConfigName);
-
- if (!changeSetDir.exists()) {
- log.warn("Cannot complete acknowledgement. Change set directory " +
changeSetDir.getPath() +
- " does not exist.");
- return;
- }
-
- File snapshot = changeSetMgr.findChangeSet(resourceId, driftConfigName,
COVERAGE);
- File previousSnapshot = new File(snapshot.getParentFile(), snapshot.getName() +
".previous");
-
- previousSnapshot.delete();
- deleteZipFiles(changeSetDir, "changeset_");
- }
-
- @Override
- public void ackChangeSetContent(int resourceId, String driftConfigName, String token)
{
- log.info("Received server change set content ack for [resourceId: " +
resourceId +
- ", driftConfigurationName: " + driftConfigName + "]");
-
- File resourceDir = new File(changeSetsDir, Integer.toString(resourceId));
- File changeSetDir = new File(resourceDir, driftConfigName);
-
- if (!changeSetDir.exists()) {
- log.warn("Cannot complete acknowledgement. Change set directory " +
changeSetDir.getPath() +
- " does not exist.");
- return;
- }
-
- deleteZipFiles(changeSetDir, "content_" + token);
- }
-
- private void deleteZipFiles(File dir, final String prefix) {
- for (File file : dir.listFiles(new ZipFileNameFilter(prefix))) {
- file.delete();
+ container.addDriftDefinition(driftDef);
}
}
/**
- * Given a drift configuration, this examines the config and its associated resource
to determine where exactly
+ * Given a drift definition, this examines the config and its associated resource to
determine where exactly
* the base directory is that should be monitoried.
*
* @param resourceId The id of the resource to which the config belongs
- * @param driftConfiguration describes what is to be monitored for drift
+ * @param driftDef describes what is to be monitored for drift
*
- * @return absolute directory location where the drift configuration base directory
is referring
+ * @return absolute directory location where the drift definition base directory is
referring
*/
@Override
- public File getAbsoluteBaseDirectory(int resourceId, DriftConfiguration
driftConfiguration) {
+ public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition driftDef) {
// get the resource entity stored in our local inventory
InventoryManager im = getInventoryManager();
@@ -588,9 +486,9 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
Resource resource = container.getResource();
// find out the type of base location that is specified by the drift config
- DriftConfiguration.BaseDirectory baseDir = driftConfiguration.getBasedir();
+ DriftDefinition.BaseDirectory baseDir = driftDef.getBasedir();
if (baseDir == null) {
- throw new IllegalArgumentException("Missing basedir in drift
config");
+ throw new IllegalArgumentException("Missing basedir in drift
def");
}
// based on the type of base location, determine the root base directory
@@ -664,16 +562,17 @@ public class DriftManager extends AgentService implements
DriftAgentService, Dri
return PluginContainer.getInstance().getMeasurementManager();
}
- private static class ZipFileNameFilter implements FilenameFilter {
- private String prefix;
+ private static class DeleteFile implements Runnable {
- public ZipFileNameFilter(String prefix) {
- this.prefix = prefix;
+ private File file;
+
+ public DeleteFile(File file) {
+ this.file = file;
}
@Override
- public boolean accept(File dir, String name) {
- return name.startsWith(prefix) && name.endsWith(".zip");
+ public void run() {
+ file.delete();
}
}
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
index a453f74..8d45b75 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java
@@ -1,20 +1,20 @@
package org.rhq.core.pc.drift;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationComparator;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
/**
* Manages the drift detection schedules that are processed by the drift detector. The
* queue has a concept of the currently "active" schedule. This is identified
simply as
* the schedule returned from {@link #getNextSchedule()} which is the previous head of
the
* queue. A reference to the active schedule needs to be maintained because at any point
in
- * time the server can send a request to update the drift configuration that is attached
to
+ * time the server can send a request to update the drift definition that is attached to
* a schedule. That schedule will either be on the queue waiting to be processed or in
the
* "active" state meaning it is currently being processed by the drift
detector.
*/
public interface ScheduleQueue {
- DriftDetectionSchedule[] toArray();
+ DriftDetectionSchedule[] toArray();
/**
* Removes the head of the queue and returns a copy of the schedule that was
removed.
@@ -46,49 +46,49 @@ public interface ScheduleQueue {
boolean addSchedule(DriftDetectionSchedule schedule);
/**
- * Checks the queue for a schedule with specified resource id and drift
configuration
- * whose name matches the specified configuration.
+ * Checks the queue for a schedule with specified resource id and drift definition
+ * whose name matches the specified definition.
*
* @param resourceId The resource id of the schedule
- * @param config The drift configuration of the schedule
+ * @param driftDef The drift definition of the schedule
* @return true if the queue contains a schedule with the specified resource id and
a
- * drift configuration whose name matches the name of the specified configuration.
+ * drift definition whose name matches the name of the specified definition.
*/
- boolean contains(int resourceId, DriftConfiguration config);
+ boolean contains(int resourceId, DriftDefinition driftDef);
- boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator);
+ boolean contains(int resourceId, DriftDefinition driftDef, DriftDefinitionComparator
comparator);
/**
* This method attempts to update the schedule identified by the resource id the and
- * the drift configuration. More specifically, the schedule is identified by a
- * combination of resource id and drift configuraiton name. If the schedule to be
+ * the drift definition. More specifically, the schedule is identified by a
+ * combination of resource id and drift definition name. If the schedule to be
* updated is the active schedule, it is immediately updated and then placed back on
* the queue the next time {@link #deactivateSchedule()} is called. If the schedule
* is on the queue, it is removed, updated, and then added back onto the queue.
*
* @param resourceId The resource id
- * @param config A {@link DriftConfiguration} belonging the resource with the
specified id
+ * @param driftDef A {@link DriftDefinition} belonging the resource with the
specified id
* @return A copy of the updated schedule or null if no update was performed
*/
- DriftDetectionSchedule update(int resourceId, DriftConfiguration config);
+ DriftDetectionSchedule update(int resourceId, DriftDefinition driftDef);
/**
- * Removes the schedule identified by the resource id and the drift configuration.
More
+ * Removes the schedule identified by the resource id and the drift definition. More
* specifically, the schedule is identified by a combination of resource id drift
- * configuration name. This method can remove either the active schedule or a
schedule
+ * definition name. This method can remove either the active schedule or a schedule
* on the queue.
*
* @param resourceId The resource id
*
- * @param config A {@link DriftConfiguration} belonging the resource with the
specified id
+ * @param driftDef A {@link DriftDefinition} belonging the resource with the
specified id
*
* @return The {@link DriftDetectionSchedule} that is removed or null if no matching
* schedule is found.
*/
- DriftDetectionSchedule remove(int resourceId, DriftConfiguration config);
+ DriftDetectionSchedule remove(int resourceId, DriftDefinition driftDef);
/**
- * Removes the schedule identified by the resource id and the drift configuration
name.
+ * Removes the schedule identified by the resource id and the drift definition name.
* This method can remove either the active schedule or a schedule on the queue.
When
* the schedule is in the queue, <code>task</code> is executed
immediately after the
* schedule is removed from the queue. If the schedule is active, then
<code>task</code>
@@ -106,13 +106,13 @@ public interface ScheduleQueue {
* is not in used before task is executed.
*
* @param resourceId The resource id
- * @param config A {@link DriftConfiguration} belonging the resource with the
specified id
+ * @param driftDef A {@link DriftDefinition} belonging the resource with the
specified id
* @param task A callback to perform any post-processing when the schedule is
removed
* from the queue
* @return The {@link DriftDetectionSchedule} that is removed or null if no matching
* schedule is found.
*/
- DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration config,
Runnable task);
+ DriftDetectionSchedule removeAndExecute(int resourceId, DriftDefinition driftDef,
Runnable task);
/**
* Removes all elements from the queue and deactivates the active schedule.
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
index e5fa56e..13e20b6 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java
@@ -7,8 +7,8 @@ import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationComparator;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
public class ScheduleQueueImpl implements ScheduleQueue {
@@ -41,22 +41,21 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
}
- private boolean isActiveSchedule(int resourceId, DriftConfiguration config) {
+ private boolean isActiveSchedule(int resourceId, DriftDefinition driftDef) {
try {
lock.readLock().lock();
return activeSchedule != null && activeSchedule.getResourceId() ==
resourceId
- &&
activeSchedule.getDriftConfiguration().getName().equals(config.getName());
+ &&
activeSchedule.getDriftDefinition().getName().equals(driftDef.getName());
} finally {
lock.readLock().unlock();
}
}
- private boolean isActiveSchedule(int resourceId, DriftConfiguration config,
- DriftConfigurationComparator comparator) {
+ private boolean isActiveSchedule(int resourceId, DriftDefinition driftDef,
DriftDefinitionComparator comparator) {
try {
lock.readLock().lock();
return activeSchedule != null && activeSchedule.getResourceId() ==
resourceId
- && comparator.compare(activeSchedule.getDriftConfiguration(),
config) == 0;
+ && comparator.compare(activeSchedule.getDriftDefinition(),
driftDef) == 0;
} finally {
lock.readLock().unlock();
}
@@ -94,15 +93,15 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public boolean contains(int resourceId, DriftConfiguration config) {
- if (isActiveSchedule(resourceId, config)) {
+ public boolean contains(int resourceId, DriftDefinition driftDef) {
+ if (isActiveSchedule(resourceId, driftDef)) {
return true;
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
- if (schedule.getResourceId() == resourceId &&
- schedule.getDriftConfiguration().getName().equals(config.getName()))
{
+ if (schedule.getResourceId() == resourceId
+ &&
schedule.getDriftDefinition().getName().equals(driftDef.getName())) {
return true;
}
}
@@ -113,15 +112,15 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public boolean contains(int resourceId, DriftConfiguration config,
DriftConfigurationComparator comparator) {
- if (isActiveSchedule(resourceId, config, comparator)) {
+ public boolean contains(int resourceId, DriftDefinition driftDef,
DriftDefinitionComparator comparator) {
+ if (isActiveSchedule(resourceId, driftDef, comparator)) {
return true;
}
try {
lock.readLock().lock();
for (DriftDetectionSchedule schedule : queue) {
- if (schedule.getResourceId() == resourceId &&
- comparator.compare(schedule.getDriftConfiguration(), config) == 0) {
+ if (schedule.getResourceId() == resourceId
+ && comparator.compare(schedule.getDriftDefinition(),
driftDef) == 0) {
return true;
}
}
@@ -132,15 +131,15 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) {
- return removeAndExecute(resourceId, config, NO_OP);
+ public DriftDetectionSchedule remove(int resourceId, DriftDefinition driftDef) {
+ return removeAndExecute(resourceId, driftDef, NO_OP);
}
@Override
- public DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration
config, Runnable task) {
+ public DriftDetectionSchedule removeAndExecute(int resourceId, DriftDefinition
driftDef, Runnable task) {
try {
lock.writeLock().lock();
- if (isActiveSchedule(resourceId, config)) {
+ if (isActiveSchedule(resourceId, driftDef)) {
deactivationTask = task;
DriftDetectionSchedule removedSchedule = activeSchedule;
activeSchedule = null;
@@ -151,7 +150,7 @@ public class ScheduleQueueImpl implements ScheduleQueue {
while (iterator.hasNext()) {
DriftDetectionSchedule schedule = iterator.next();
if (schedule.getResourceId() == resourceId
- &&
schedule.getDriftConfiguration().getName().equals(config.getName())) {
+ &&
schedule.getDriftDefinition().getName().equals(driftDef.getName())) {
iterator.remove();
task.run();
return schedule;
@@ -165,13 +164,13 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
@Override
- public DriftDetectionSchedule update(int resourceId, DriftConfiguration config) {
- DriftDetectionSchedule schedule = remove(resourceId, config);
+ public DriftDetectionSchedule update(int resourceId, DriftDefinition driftDef) {
+ DriftDetectionSchedule schedule = remove(resourceId, driftDef);
if (schedule == null) {
return null;
}
- update(schedule, config);
+ update(schedule, driftDef);
try {
lock.writeLock().lock();
@@ -184,9 +183,9 @@ public class ScheduleQueueImpl implements ScheduleQueue {
}
}
- private void update(DriftDetectionSchedule schedule, DriftConfiguration config) {
- schedule.getDriftConfiguration().setEnabled(config.isEnabled());
- schedule.getDriftConfiguration().setInterval(config.getInterval());
+ private void update(DriftDetectionSchedule schedule, DriftDefinition driftDef) {
+ schedule.getDriftDefinition().setEnabled(driftDef.isEnabled());
+ schedule.getDriftDefinition().setInterval(driftDef.getInterval());
}
@Override
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
index 434ddc1..35e62d8 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSyncManager.java
@@ -19,6 +19,8 @@
package org.rhq.core.pc.drift.sync;
+import static
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
+
import java.io.File;
import java.util.List;
import java.util.Map;
@@ -29,17 +31,15 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.server.drift.DriftServerService;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationComparator;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
import org.rhq.core.pc.drift.DriftManager;
import org.rhq.core.pc.inventory.InventoryManager;
-import static
org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
-
/**
- * This class handles syncing drift configurations and drift content during inventory
sync.
- * This class is intended to server as the public interface (so to speak) to
- * {@link InventoryManager} for syncing drift configurations and content.
+ * This class handles syncing drift definitions during inventory sync. This class is
+ * intended to server as the public interface (so to speak) to {@link InventoryManager}
for
+ * syncing drift definitions.
* <br/><br/>
* Please review the docs for each of the setter methods to determine which properties
* should be set before invoking any business logic methods.
@@ -89,19 +89,13 @@ public class DriftSyncManager {
dataDir = dataDirectory;
}
- /**
- * Synchronized both drift configurations and drift content with the server. The
drift
- * configuration sync goes from server to agent in that the drift configurations in
the
- * local inventory are updated to match the drift configurations on the server
- * inventory.
- * <br/><br/>
- * The content sync works as follows. Any change set content zip files found locally
- * resent to the server under the assumption that the content has not been persisted
on
- * the server.
- *
- * @param resourceIds The ids of resources that need to be synced.
- */
- public void syncWithServer(Set<Integer> resourceIds) {
+ public void syncDefsWithServer(Set<Integer> resourceIds) {
+ log.info("Starting server sync for drift definitions...");
+ long startTime = System.currentTimeMillis();
+
+ Map<Integer, List<DriftDefinition>> defs =
driftServer.getDriftDefinitions(resourceIds);
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
+ BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
DriftSynchronizerFactory synchronizerFactory = new DriftSynchronizerFactory();
DriftSynchronizer synchronizer;
@@ -111,50 +105,26 @@ public class DriftSyncManager {
synchronizer = synchronizerFactory.getRuntimeSynchronizer(driftMgr);
}
- syncConfigs(synchronizer, resourceIds);
- syncContent(synchronizer);
- }
-
- private void syncConfigs(DriftSynchronizer synchronizer, Set<Integer>
resourceIds) {
- log.info("Starting server sync for drift configurations...");
- long startTime = System.currentTimeMillis();
-
- Map<Integer, List<DriftConfiguration>> configs =
driftServer.getDriftConfigurations(resourceIds);
- DriftConfigurationComparator comparator = new DriftConfigurationComparator(
- BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
-
int totalDeleted = 0;
int totalAdded = 0;
- for (Integer resourceId : configs.keySet()) {
- Set<DriftConfiguration> resourceConfigsOnServer = new
TreeSet<DriftConfiguration>(comparator);
- resourceConfigsOnServer.addAll(configs.get(resourceId));
-
- List<DriftConfiguration> deletedConfigs =
synchronizer.getDeletedConfigurations(resourceId,
- resourceConfigsOnServer);
- totalDeleted += deletedConfigs.size();
- synchronizer.purgeFromLocalInventory(resourceId, deletedConfigs);
+ for (Integer resourceId : defs.keySet()) {
+ Set<DriftDefinition> resourceDefsOnServer = new
TreeSet<DriftDefinition>(comparator);
+ resourceDefsOnServer.addAll(defs.get(resourceId));
- List<DriftConfiguration> addedConfigs =
synchronizer.getAddedConfigurations(resourceId,
- resourceConfigsOnServer);
- totalAdded += addedConfigs.size();
- synchronizer.addToLocalInventory(resourceId, addedConfigs);
- }
+ List<DriftDefinition> deletedDefs =
synchronizer.getDeletedDefinitions(resourceId, resourceDefsOnServer);
+ totalDeleted += deletedDefs.size();
+ synchronizer.purgeFromLocalInventory(resourceId, deletedDefs);
- long endTime = System.currentTimeMillis();
- if (log.isInfoEnabled()) {
- log.info("Finished server sync for drift configurations. " +
totalAdded + " added and " + totalDeleted +
- " deleted in " + (endTime - startTime) + " ms");
+ List<DriftDefinition> addedDefs =
synchronizer.getAddedDefinitions(resourceId, resourceDefsOnServer);
+ totalAdded += addedDefs.size();
+ synchronizer.addToLocalInventory(resourceId, addedDefs);
}
- }
- private void syncContent(DriftSynchronizer synchronizer) {
- log.info("Starting drift content sync...");
- long startTime = System.currentTimeMillis();
- synchronizer.syncChangeSetContent();
long endTime = System.currentTimeMillis();
if (log.isInfoEnabled()) {
- log.info("Finished drift content sync in " + (endTime - startTime)
+ " ms");
+ log.info("Finished server sync for drift definitions. " +
totalAdded + " added and " + totalDeleted
+ + " deleted in " + (endTime - startTime) + " ms");
}
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSynchronizer.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSynchronizer.java
index 90c4955..9a8f0cf 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSynchronizer.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/DriftSynchronizer.java
@@ -22,67 +22,65 @@ package org.rhq.core.pc.drift.sync;
import java.util.List;
import java.util.Set;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
/**
- * A DriftSynchronizer is responsible for sycning {@link DriftConfiguration}s in the
+ * A DriftSynchronizer is responsible for sycning {@link DriftDefinition}s in the
* server's with those in the local inventory.
*/
public interface DriftSynchronizer {
/**
- * Determines which drift configurations for a resource have been deleted on the
server
+ * Determines which drift definitions for a resource have been deleted on the server
* and need to be purged from the local inventory. This method should not make any
* changes to the local inventory. It also handles syncing content with the server.
Any
* change set content found on the agent and that is not known to be on the server
* should be sent to the server.
*
* @param resourceId
- * @param configurationsFromServer A set of drift configurations belonging to the
- * resource with the specified id. The set uses a {@link
org.rhq.core.domain.drift.DriftConfigurationComparator DriftConfigurationComparator}
- * with the compare mode set to {@link
org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode#BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS
BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS}.
- * @return A list of drift configurations that need to be purged from the local
inventory.
+ * @param definitionsFromServer A set of drift definitions belonging to the
+ * resource with the specified id. The set uses a {@link
org.rhq.core.domain.drift.DriftDefinitionComparator driftDefinitionComparator}
+ * with the compare mode set to {@link
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode#BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS
BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS}.
+ * @return A list of drift definitions that need to be purged from the local
inventory.
*/
- List<DriftConfiguration> getDeletedConfigurations(int resourceId,
- Set<DriftConfiguration> configurationsFromServer);
-
+ List<DriftDefinition> getDeletedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer);
/**
- * Removes the drift configurations from local inventory. Implementations are
responsible
+ * Removes the drift definitions from local inventory. Implementations are
responsible
* for deciding how that is to be done. For example, if the plugin container is not
- * fully initialized, then purging will involve removing configurations from the
+ * fully initialized, then purging will involve removing definitions from the
* {@link org.rhq.core.pc.inventory.ResourceContainer ResourceContainer}. But if the
* plugin container is initialized, then drift detection will have to be
unscheduled.
*
* @param resourceId
- * @param configurations The drift configurations to purge from local inventory
+ * @param definitions The drift definitions to purge from local inventory
*/
- void purgeFromLocalInventory(int resourceId, List<DriftConfiguration>
configurations);
+ void purgeFromLocalInventory(int resourceId, List<DriftDefinition>
definitions);
/**
- * Determines which drift configurations for a resource have been added on the
server
+ * Determines which drift definitions for a resource have been added on the server
* and need to be added to the local inventory. This method should not make any
changes
* to the local inventory.
*
* @param resourceId
- * @param configurationsFromServer A set of drift configurations belonging to the
- * resource with the specified id. The set uses a {@link
org.rhq.core.domain.drift.DriftConfigurationComparator DriftConfigurationComparator}
- * with the compare mode set to {@link
org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode#BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS
BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS}.
- * @return A list of drift configurations that need to be purged from the local
inventory.
+ * @param definitionsFromServer A set of drift definitions belonging to the
+ * resource with the specified id. The set uses a {@link
org.rhq.core.domain.drift.DriftDefinitionComparator driftDefinitionComparator}
+ * with the compare mode set to {@link
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode#BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS
BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS}.
+ * @return A list of drift definitions that need to be purged from the local
inventory.
*/
- List<DriftConfiguration> getAddedConfigurations(int resourceId,
Set<DriftConfiguration> configurationsFromServer);
+ List<DriftDefinition> getAddedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer);
/**
- * Adds the drift configurations to the local inventory. Implementations are
responsible
+ * Adds the drift definitions to the local inventory. Implementations are
responsible
* for deciding how that is to be done. For example, if the plugin container is not
- * fully initialized, then adding a configuration will involve adding it to the
+ * fully initialized, then adding a definition will involve adding it to the
* {@link org.rhq.core.pc.inventory.ResourceContainer ResourceContainer}. But if the
* plugin container is initialized, drift detection will have to be scheduled.
*
* @param resourceId
- * @param configurations The drift configurations to add to the local inventory.
+ * @param definitions The drift definitions to add to the local inventory.
*/
- void addToLocalInventory(int resourceId, List<DriftConfiguration>
configurations);
+ void addToLocalInventory(int resourceId, List<DriftDefinition> definitions);
/**
* This is an optional operation as it can only be performed when
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/RuntimeSynchronizer.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/RuntimeSynchronizer.java
index 94cea4c..679db62 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/RuntimeSynchronizer.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/RuntimeSynchronizer.java
@@ -19,6 +19,8 @@
package org.rhq.core.pc.drift.sync;
+import static
org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
+
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@@ -26,20 +28,18 @@ import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationComparator;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
import org.rhq.core.pc.drift.DriftDetectionSchedule;
import org.rhq.core.pc.drift.DriftManager;
import org.rhq.core.pc.drift.ScheduleQueue;
-import static
org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS;
-
/**
- * As its name implies, this class synchronizes drift configurations at runtime. By
runtime
+ * As its name implies, this class synchronizes drift definitions at runtime. By runtime
* we mean when {@link DriftManager} is fully initialized. Updating the local inventory
is
- * done through DriftManager. When this class determines that a drift configuration
needs
+ * done through DriftManager. When this class determines that a drift definition needs
* to be purged from the local inventory, it does so by calling DriftManager to
unschedule
- * drift detection. Likewise when this class determines that a drift configuration needs
+ * drift detection. Likewise when this class determines that a drift definition needs
* to be added to the local inventory, it does so by calling DriftManager to schedule
* detection.
* <br/><br/>
@@ -58,49 +58,47 @@ class RuntimeSynchronizer implements DriftSynchronizer {
}
@Override
- public List<DriftConfiguration> getDeletedConfigurations(int resourceId,
- Set<DriftConfiguration> configurationsFromServer) {
- log.debug("Checking for drift configurations that need to be deleted for
resource id " + resourceId);
- List<DriftConfiguration> deleted = new
LinkedList<DriftConfiguration>();
+ public List<DriftDefinition> getDeletedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer) {
+ log.debug("Checking for drift definitions that need to be deleted for
resource id " + resourceId);
+ List<DriftDefinition> deleted = new LinkedList<DriftDefinition>();
ScheduleQueue queue = driftMgr.getSchedulesQueue();
for (DriftDetectionSchedule schedule : getSchedulesForResource(resourceId,
queue.toArray())) {
- if (!configurationsFromServer.contains(schedule.getDriftConfiguration())) {
+ if (!definitionsFromServer.contains(schedule.getDriftDefinition())) {
if (log.isDebugEnabled()) {
- log.debug("Detected stale drift configuration that needs to be
purged - " +
- toString(resourceId, schedule.getDriftConfiguration()));
+ log.debug("Detected stale drift definition that needs to be
purged - "
+ + toString(resourceId, schedule.getDriftDefinition()));
}
- deleted.add(schedule.getDriftConfiguration());
+ deleted.add(schedule.getDriftDefinition());
}
}
return deleted;
}
@Override
- public void purgeFromLocalInventory(int resourceId, List<DriftConfiguration>
configurations) {
- log.debug("Preparing to unschedule drift detection and purge from local
inventory drift configurations " +
- "that have been deleted on the server for resource id " +
resourceId);
+ public void purgeFromLocalInventory(int resourceId, List<DriftDefinition>
definitions) {
+ log.debug("Preparing to unschedule drift detection and purge from local
inventory drift definitions "
+ + "that have been deleted on the server for resource id " +
resourceId);
- for (DriftConfiguration c : configurations) {
+ for (DriftDefinition c : definitions) {
driftMgr.unscheduleDriftDetection(resourceId, c);
}
}
@Override
- public List<DriftConfiguration> getAddedConfigurations(int resourceId,
- Set<DriftConfiguration> configurationsFromServer) {
- log.debug("Checking for drift configurations that need to be added for
resource id " + resourceId);
+ public List<DriftDefinition> getAddedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer) {
+ log.debug("Checking for drift definitions that need to be added for resource
id " + resourceId);
ScheduleQueue queue = driftMgr.getSchedulesQueue();
- DriftConfigurationComparator comparator = new DriftConfigurationComparator(
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
- List<DriftConfiguration> added = new
LinkedList<DriftConfiguration>();
+ List<DriftDefinition> added = new LinkedList<DriftDefinition>();
- for (DriftConfiguration c : configurationsFromServer) {
+ for (DriftDefinition c : definitionsFromServer) {
if (!queue.contains(resourceId, c, comparator)) {
if (log.isDebugEnabled()) {
- log.debug("Detected new drift configuration that needs to be
added to local inventory - " +
- toString(resourceId, c));
+ log.debug("Detected new drift definition that needs to be added
to local inventory - "
+ + toString(resourceId, c));
}
added.add(c);
}
@@ -109,11 +107,11 @@ class RuntimeSynchronizer implements DriftSynchronizer {
}
@Override
- public void addToLocalInventory(int resourceId, List<DriftConfiguration>
configurations) {
- log.debug("Adding drift configurations to local inventory and creating drift
detection schedules for " +
- "resource id " + resourceId);
+ public void addToLocalInventory(int resourceId, List<DriftDefinition>
definitions) {
+ log.debug("Adding drift definitions to local inventory and creating drift
detection schedules for "
+ + "resource id " + resourceId);
- for (DriftConfiguration c : configurations) {
+ for (DriftDefinition c : definitions) {
if (log.isDebugEnabled()) {
log.debug("Adding " + toString(resourceId, c) + " to local
inventory");
}
@@ -126,8 +124,8 @@ class RuntimeSynchronizer implements DriftSynchronizer {
driftMgr.scanForContentToResend();
}
- private String toString(int rid, DriftConfiguration c) {
- return "DriftConfiguration[id: " + c.getId() + ", name: " +
c.getName() + ", resourceId: " + rid + "]";
+ private String toString(int rid, DriftDefinition c) {
+ return "DriftDefinition[id: " + c.getId() + ", name: " +
c.getName() + ", resourceId: " + rid + "]";
}
private List<DriftDetectionSchedule> getSchedulesForResource(int resourceId,
DriftDetectionSchedule[] schedules) {
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/StartupSynchronizer.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/StartupSynchronizer.java
index 0e8ed59..42221a9 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/StartupSynchronizer.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/sync/StartupSynchronizer.java
@@ -19,6 +19,8 @@
package org.rhq.core.pc.drift.sync;
+import static org.rhq.core.util.file.FileUtil.purge;
+
import java.io.File;
import java.util.LinkedList;
import java.util.List;
@@ -27,20 +29,18 @@ import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
-import static org.rhq.core.util.file.FileUtil.purge;
-
/**
- * As its name implies, this class synchronizes drift configurations at start up or any
+ * As its name implies, this class synchronizes drift definitions at start up or any
* time when the plugin container is not fully initialized. If the plugin container is
not
* fully initialized, then that means {@link org.rhq.core.pc.drift.DriftManager
DriftManager}
* is not available to call into to schedule or unschedule drift detection.
- * StartupSynchronizer therefore deals only with the drift configurations attached to
+ * StartupSynchronizer therefore deals only with the drift definitions attached to
* {@link ResourceContainer} objects. As part of its initialization DriftManager
- * creates or recreates detection schedules from the configurations attached to the
+ * creates or recreates detection schedules from the definitions attached to the
* resource containers.
*/
class StartupSynchronizer implements DriftSynchronizer {
@@ -56,17 +56,15 @@ class StartupSynchronizer implements DriftSynchronizer {
}
@Override
- public List<DriftConfiguration> getDeletedConfigurations(int resourceId,
- Set<DriftConfiguration> configurationsFromServer) {
- log.debug("Checking for drift configurations that need to be deleted for
resource id " + resourceId);
- List<DriftConfiguration> deleted = new
LinkedList<DriftConfiguration>();
+ public List<DriftDefinition> getDeletedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer) {
+ log.debug("Checking for drift definitions that need to be deleted for
resource id " + resourceId);
+ List<DriftDefinition> deleted = new LinkedList<DriftDefinition>();
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
- for (DriftConfiguration c : container.getDriftConfigurations()) {
- if (!configurationsFromServer.contains(c)) {
+ for (DriftDefinition c : container.getDriftDefinitions()) {
+ if (!definitionsFromServer.contains(c)) {
if (log.isDebugEnabled()) {
- log.debug("Detected stale drift configuration that needs to be
purged - " +
- toString(resourceId, c));
+ log.debug("Detected stale drift definition that needs to be
purged - " + toString(resourceId, c));
}
deleted.add(c);
}
@@ -76,17 +74,17 @@ class StartupSynchronizer implements DriftSynchronizer {
}
@Override
- public void purgeFromLocalInventory(int resourceId, List<DriftConfiguration>
configurations) {
- log.debug("Preparing to purge from local inventory drift configurations that
have been deleted on the server "
+ public void purgeFromLocalInventory(int resourceId, List<DriftDefinition>
definitions) {
+ log.debug("Preparing to purge from local inventory drift definitions that
have been deleted on the server "
+ "for resource id " + resourceId);
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
File resourceSnapshotsDir = new File(snapshotsDir,
Integer.toString(resourceId));
- for (DriftConfiguration c : configurations) {
+ for (DriftDefinition c : definitions) {
if (log.isDebugEnabled()) {
log.debug("Purging " + toString(resourceId, c) + " from
local inventory");
}
- container.removeDriftConfiguration(c);
+ container.removeDriftDefinition(c);
File snapshotDir = new File(resourceSnapshotsDir, c.getName());
if (snapshotDir.exists()) {
if (log.isDebugEnabled()) {
@@ -98,19 +96,17 @@ class StartupSynchronizer implements DriftSynchronizer {
}
@Override
- public List<DriftConfiguration> getAddedConfigurations(int resourceId,
- Set<DriftConfiguration> configurationsFromServer) {
- log.debug("Checking for drift configurations that need to be added for
resource id " + resourceId);
+ public List<DriftDefinition> getAddedDefinitions(int resourceId,
Set<DriftDefinition> definitionsFromServer) {
+ log.debug("Checking for drift definitions that need to be added for resource
id " + resourceId);
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
- List<DriftConfiguration> added = new
LinkedList<DriftConfiguration>();
-
+ List<DriftDefinition> added = new LinkedList<DriftDefinition>();
- for (DriftConfiguration c : configurationsFromServer) {
- if (!container.containsDriftConfiguration(c)) {
+ for (DriftDefinition c : definitionsFromServer) {
+ if (!container.containsDriftDefinition(c)) {
if (log.isDebugEnabled()) {
- log.debug("Detected new drift configuration that needs to be
added to local inventory - " +
- toString(resourceId, c));
+ log.debug("Detected new drift definition that needs to be added
to local inventory - "
+ + toString(resourceId, c));
}
added.add(c);
}
@@ -119,15 +115,15 @@ class StartupSynchronizer implements DriftSynchronizer {
}
@Override
- public void addToLocalInventory(int resourceId, List<DriftConfiguration>
configurations) {
- log.debug("Adding drift configurations to local inventory for resource id
" + resourceId);
+ public void addToLocalInventory(int resourceId, List<DriftDefinition>
definitions) {
+ log.debug("Adding drift definitions to local inventory for resource id
" + resourceId);
ResourceContainer container = inventoryMgr.getResourceContainer(resourceId);
- for (DriftConfiguration c : configurations) {
+ for (DriftDefinition c : definitions) {
if (log.isDebugEnabled()) {
log.debug("Adding " + toString(resourceId, c) + " to local
inventory");
}
- container.addDriftConfiguration(c);
+ container.addDriftDefinition(c);
}
}
@@ -135,7 +131,7 @@ class StartupSynchronizer implements DriftSynchronizer {
public void syncChangeSetContent() {
}
- private String toString(int rid, DriftConfiguration c) {
- return "DriftConfiguration[id: " + c.getId() + ", name: " +
c.getName() + ", resourceId: " + rid + "]";
+ private String toString(int rid, DriftDefinition c) {
+ return "DriftDefinition[id: " + c.getId() + ", name: " +
c.getName() + ", resourceId: " + rid + "]";
}
}
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index bfdb2a3..a8927a5 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -243,19 +243,16 @@ public class InventoryManager extends AgentService implements
ContainerService,
// inside EmbJopr).
if (configuration.isInsideAgent()) {
// After an initial delay (5s by default), periodically run an
availability check (every 1m by default).
-
availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor,
- configuration.getAvailabilityScanInitialDelay(),
configuration.getAvailabilityScanPeriod(),
- TimeUnit.SECONDS);
+
availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor, configuration
+ .getAvailabilityScanInitialDelay(),
configuration.getAvailabilityScanPeriod(), TimeUnit.SECONDS);
// After an initial delay (10s by default), periodically run a server
discovery scan (every 15m by default).
- inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor,
- configuration.getServerDiscoveryInitialDelay(),
configuration.getServerDiscoveryPeriod(),
- TimeUnit.SECONDS);
+ inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor,
configuration
+ .getServerDiscoveryInitialDelay(),
configuration.getServerDiscoveryPeriod(), TimeUnit.SECONDS);
// After an initial delay (20s by default), periodically run a service
discovery scan (every 1d by default).
- inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor,
- configuration.getServiceDiscoveryInitialDelay(),
configuration.getServiceDiscoveryPeriod(),
- TimeUnit.SECONDS);
+ inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor,
configuration
+ .getServiceDiscoveryInitialDelay(),
configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS);
}
} finally {
inventoryLock.writeLock().unlock();
@@ -312,8 +309,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try {
- ResourceDiscoveryComponent proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
- context.getResourceType(), component, timeout, parentResourceContainer);
+ ResourceDiscoveryComponent proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
+ .getResourceType(), component, timeout, parentResourceContainer);
Set<DiscoveredResourceDetails> results =
proxy.discoverResources(context);
return results;
} catch (TimeoutException te) {
@@ -348,8 +345,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try {
- ManualAddFacet proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
- context.getResourceType(), component, timeout, ManualAddFacet.class,
parentResourceContainer);
+ ManualAddFacet proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
+ .getResourceType(), component, timeout, ManualAddFacet.class,
parentResourceContainer);
DiscoveredResourceDetails result = proxy.discoverResource(pluginConfig,
context);
return result;
} catch (TimeoutException te) {
@@ -388,8 +385,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
component, timeout, ClassLoaderFacet.class, parentContainer);
ResourceDiscoveryContext discoveryContext = new
ResourceDiscoveryContext(resourceType, parentComponent,
- parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null,
- this.configuration.getContainerName(),
this.configuration.getPluginContainerDeployment());
+ parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null,
this.configuration
+ .getContainerName(), this.configuration.getPluginContainerDeployment());
// Configurations are not immutable, so clone the plugin config, so the plugin
will not be able to change the
// actual PC-managed plugin config.
@@ -677,8 +674,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
ResourceDiscoveryContext<ResourceComponent<?>>
discoveryContext = new ResourceDiscoveryContext<ResourceComponent<?>>(
resourceType, parentResourceComponent,
parentResourceContainer.getResourceContext(),
SystemInfoFactory.createSystemInfo(), new
ArrayList<ProcessScanResult>(0),
- new ArrayList<Configuration>(0),
this.configuration.getContainerName(),
- this.configuration.getPluginContainerDeployment());
+ new ArrayList<Configuration>(0),
this.configuration.getContainerName(), this.configuration
+ .getPluginContainerDeployment());
// Ask the plugin's discovery component to find the new resource,
throwing exceptions if it cannot be
// found at all.
@@ -880,7 +877,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
if ((this.platform != null) && (this.platform.getInventoryStatus() ==
InventoryStatus.NEW)
&& newPlatformWasDeletedRecently) {
// let's make sure we are registered; its probable that our platform
was deleted and we need to re-register
- log.info("No committed resources to send in our availability report
- the platform/agent was deleted, let's re-register again");
+ log
+ .info("No committed resources to send in our availability report
- the platform/agent was deleted, let's re-register again");
registerWithServer();
newPlatformWasDeletedRecently = false; // we've tried to recover from
our platform being deleted, let's not do it again
}
@@ -923,8 +921,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
log.debug("Availability report content: " +
report.toString(log.isTraceEnabled()));
}
- boolean ok =
configuration.getServerServices().getDiscoveryServerService()
- .mergeAvailabilityReport(report);
+ boolean ok =
configuration.getServerServices().getDiscoveryServerService().mergeAvailabilityReport(
+ report);
if (!ok) {
// I guess I could immediately call
executeAvailabilityScanImmediately and pass its results to
// mergeAvailabilityReport again right now, but what happens if
we've queued up a bunch of
@@ -970,9 +968,10 @@ public class InventoryManager extends AgentService implements
ContainerService,
(System.currentTimeMillis() - startTime)));
}
} catch (StaleTypeException e) {
- log.error("Failed to merge inventory report with server. The report
contains one or more resource types "
- + "that have been marked for deletion. Notifying the plugin
container that a reboot is needed to purge "
- + "stale types.");
+ log
+ .error("Failed to merge inventory report with server. The report
contains one or more resource types "
+ + "that have been marked for deletion. Notifying the plugin
container that a reboot is needed to purge "
+ + "stale types.");
PluginContainer.getInstance().notifyRebootRequestListener();
return false;
} catch (InvalidInventoryReportException e) {
@@ -980,7 +979,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
if ((this.platform != null) && (this.platform.getInventoryStatus() ==
InventoryStatus.NEW)
&& newPlatformWasDeletedRecently) {
// let's make sure we are registered; its probable that our platform
was deleted and we need to re-register
- log.info("The inventory report was invalid probably because the
platform/Agent was deleted; let's re-register...");
+ log
+ .info("The inventory report was invalid probably because the
platform/Agent was deleted; let's re-register...");
registerWithServer();
newPlatformWasDeletedRecently = false; // we've tried to recover from
our platform being deleted, let's not do it again
}
@@ -1176,8 +1176,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
parent.removeChildResource(resource);
}
- PluginContainer.getInstance().getMeasurementManager()
- .unscheduleCollection(Collections.singleton(resource.getId()));
+ PluginContainer.getInstance().getMeasurementManager().unscheduleCollection(
+ Collections.singleton(resource.getId()));
if (this.resourceContainers.remove(resource.getUuid()) == null) {
if (log.isDebugEnabled()) {
@@ -1283,8 +1283,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
logMessage.append("description, ");
}
- logMessage.replace(logMessage.length() - 1, logMessage.length(),
"to become [")
- .append(existingResource.toString()).append("]");
+ logMessage.replace(logMessage.length() - 1, logMessage.length(),
"to become [").append(
+ existingResource.toString()).append("]");
log.info(logMessage.toString());
} else {
@@ -1520,8 +1520,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
log.warn("Cannot give activated resource its discovery component.
Cause: " + e);
}
-
ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(),
- type.getPluginConfigurationDefinition());
+
ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(), type
+ .getPluginConfigurationDefinition());
ResourceComponent<?> parentComponent = null;
if (resource.getParentResource() != null) {
@@ -1659,8 +1659,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
resource.setConnected(false); // invalid plugin configuration infers the resource
component is disconnected
// Give the server-side an error message describing the connection failure that
can be
// displayed on the resource's Inventory page.
- ResourceError resourceError = new ResourceError(resource,
ResourceErrorType.INVALID_PLUGIN_CONFIGURATION,
- t.getLocalizedMessage(), ThrowableUtil.getStackAsString(t),
System.currentTimeMillis());
+ ResourceError resourceError = new ResourceError(resource,
ResourceErrorType.INVALID_PLUGIN_CONFIGURATION, t
+ .getLocalizedMessage(), ThrowableUtil.getStackAsString(t),
System.currentTimeMillis());
return sendResourceErrorToServer(resourceError);
}
@@ -1919,7 +1919,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
}
} else {
// This is very strange - there are no platform types - we should never be
missing the built-in platform plugin.
- log.error("Missing platform plugin(s) - falling back to dummy platform
impl; this should only occur in tests!");
+ log
+ .error("Missing platform plugin(s) - falling back to dummy platform
impl; this should only occur in tests!");
// TODO: Set sysprop (e.g. rhq.test.mode=true) in integration tests,
// and throw a runtime exception here if that sysprop is not set.
return getTestPlatform();
@@ -2042,7 +2043,7 @@ public class InventoryManager extends AgentService implements
ContainerService,
private boolean supportsDriftManagement(Resource r) {
PluginMetadataManager metaDataMgr =
PluginContainer.getInstance().getPluginManager().getMetadataManager();
ResourceType type = metaDataMgr.getType(r.getResourceType());
- return type.getDriftConfigurationTemplates() != null &&
!type.getDriftConfigurationTemplates().isEmpty();
+ return type.getDriftDefinitionTemplates() != null &&
!type.getDriftDefinitionTemplates().isEmpty();
}
private void syncSchedules(Set<Resource> resources) {
@@ -2304,8 +2305,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
try {
ResourceDiscoveryContext context = new ResourceDiscoveryContext(resourceType,
parentComponent,
parentResourceContext, SystemInfoFactory.createSystemInfo(),
processScanResults,
- Collections.EMPTY_LIST, this.configuration.getContainerName(),
- this.configuration.getPluginContainerDeployment());
+ Collections.EMPTY_LIST, this.configuration.getContainerName(),
this.configuration
+ .getPluginContainerDeployment());
newResources = new HashSet<Resource>();
try {
Set<DiscoveredResourceDetails> discoveredResources =
invokeDiscoveryComponent(parentContainer,
@@ -2541,8 +2542,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
if (log.isDebugEnabled()) {
log.debug("Merging [" + modifiedResourceIds.size() + "]
modified Resources into local inventory...");
}
- Set<Resource> modifiedResources =
configuration.getServerServices().getDiscoveryServerService()
- .getResources(modifiedResourceIds, false);
+ Set<Resource> modifiedResources =
configuration.getServerServices().getDiscoveryServerService().getResources(
+ modifiedResourceIds, false);
syncSchedules(modifiedResources); // RHQ-792, mtime is the indicator that
schedules should be sync'ed too
syncDriftConfigurations(modifiedResources);
for (Resource modifiedResource : modifiedResources) {
@@ -2791,9 +2792,10 @@ public class InventoryManager extends AgentService implements
ContainerService,
log.info("Resource activation and upgrade finished.");
} catch (Throwable t) {
- log.error(
- "Resource activation or upgrade failed with an exception. An attempt
to merely activate the resources will be made now.",
- t);
+ log
+ .error(
+ "Resource activation or upgrade failed with an exception. An
attempt to merely activate the resources will be made now.",
+ t);
//make sure to at least activate the resources
activateAndUpgradeResourceRecursively(getPlatform(), false);
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
index 791857b..854e624 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
@@ -49,7 +49,7 @@ import org.jetbrains.annotations.Nullable;
import org.rhq.core.clientapi.agent.PluginContainerException;
import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
@@ -67,6 +67,7 @@ import org.rhq.core.pluginapi.inventory.ResourceContext;
* @author John Mazzitelli
* @author Ian Springer
*/
+@SuppressWarnings("unchecked")
public class ResourceContainer implements Serializable {
private static final long serialVersionUID = 1L;
@@ -90,7 +91,7 @@ public class ResourceContainer implements Serializable {
private SynchronizationState synchronizationState = SynchronizationState.NEW;
private Set<MeasurementScheduleRequest> measurementSchedule = new
HashSet<MeasurementScheduleRequest>();
private Set<ResourcePackageDetails> installedPackages = new
HashSet<ResourcePackageDetails>();
- private Map<String, DriftConfiguration> driftConfigurations = new
HashMap<String, DriftConfiguration>();
+ private Map<String, DriftDefinition> driftDefinitions = new HashMap<String,
DriftDefinition>();
// transient fields
private transient ResourceComponent resourceComponent;
@@ -245,27 +246,27 @@ public class ResourceContainer implements Serializable {
}
}
- public Collection<DriftConfiguration> getDriftConfigurations() {
+ public Collection<DriftDefinition> getDriftDefinitions() {
synchronized (this) {
- return driftConfigurations.values();
+ return driftDefinitions.values();
}
}
- public boolean containsDriftConfiguration(DriftConfiguration c) {
+ public boolean containsDriftDefinition(DriftDefinition d) {
synchronized (this) {
- return driftConfigurations.containsKey(c.getName());
+ return driftDefinitions.containsKey(d.getName());
}
}
- public void addDriftConfiguration(DriftConfiguration c) {
+ public void addDriftDefinition(DriftDefinition d) {
synchronized (this) {
- driftConfigurations.put(c.getName(), c);
+ driftDefinitions.put(d.getName(), d);
}
}
- public void removeDriftConfiguration(DriftConfiguration c) {
+ public void removeDriftDefinition(DriftDefinition d) {
synchronized (this) {
- driftConfigurations.remove(c.getName());
+ driftDefinitions.remove(d.getName());
}
}
@@ -330,7 +331,6 @@ public class ResourceContainer implements Serializable {
*
* @throws PluginContainerException if the component does not exist or does not
implement the interface
*/
- @SuppressWarnings("unchecked")
public <T> T createResourceComponentProxy(Class<T> facetInterface,
FacetLockType lockType, long timeout,
boolean daemonThread, boolean onlyIfStarted) throws PluginContainerException {
if (onlyIfStarted) {
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java
index 88cda7f..05d9ccc 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java
@@ -94,8 +94,8 @@ public class ChangeSetManagerImplTest extends DriftTest {
Headers createHeaders(String driftConfigName, DriftChangeSetCategory type) {
Headers headers = new Headers();
headers.setResourceId(resourceId());
- headers.setDriftCofigurationId(1);
- headers.setDriftConfigurationName(driftConfigName);
+ headers.setDriftDefinitionId(1);
+ headers.setDriftDefinitionName(driftConfigName);
headers.setBasedir(resourceDir.getPath());
headers.setType(type);
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
index a5581ca..99c7101 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftClientTestStub.java
@@ -2,19 +2,17 @@ package org.rhq.core.pc.drift;
import java.io.File;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftChangeSetCategory;
+import org.rhq.core.domain.drift.DriftDefinition;
class DriftClientTestStub implements DriftClient {
private File basedir;
- private boolean failingOnSendChangeSet;
-
@Override
- public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
- if (failingOnSendChangeSet) {
- throw new RuntimeException("Failed to send change set to server");
- }
+ public void sendChangeSetToServer(int resourceId, DriftDefinition
driftConfiguration,
+ DriftChangeSetCategory type) {
+
}
@Override
@@ -22,19 +20,11 @@ class DriftClientTestStub implements DriftClient {
}
@Override
- public File getAbsoluteBaseDirectory(int resourceId, DriftConfiguration
driftConfiguration) {
+ public File getAbsoluteBaseDirectory(int resourceId, DriftDefinition
driftConfiguration) {
return basedir;
}
public void setBaseDir(File basedir) {
this.basedir = basedir;
}
-
- public boolean isFailingOnSendChangeSet() {
- return failingOnSendChangeSet;
- }
-
- public void setFailingOnSendChangeSet(boolean failing) {
- failingOnSendChangeSet = failing;
- }
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
index 4811044..0a3b10c 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java
@@ -34,7 +34,7 @@ import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
@@ -80,7 +80,7 @@ public class DriftDetectorTest extends DriftTest {
// create an empty directory
File libDir = mkdir(resourceDir, "lib");
- DriftConfiguration driftConfig = driftConfiguration("coverage-test",
resourceDir.getAbsolutePath());
+ DriftDefinition driftConfig = driftConfiguration("coverage-test",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(),
driftConfig));
detector.run();
@@ -100,7 +100,7 @@ public class DriftDetectorTest extends DriftTest {
File server1Conf = createRandomFile(confDir, "server-1.conf");
File server2Conf = createRandomFile(confDir, "server-2.conf");
- DriftConfiguration config = driftConfiguration("multiple-files-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("multiple-files-test",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
detector.run();
@@ -124,7 +124,7 @@ public class DriftDetectorTest extends DriftTest {
File libDir = mkdir(resourceDir, "lib");
File serverLib = createRandomFile(libDir, "server.jar");
- DriftConfiguration config = driftConfiguration("sibling-dirs-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("sibling-dirs-test",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
detector.run();
@@ -148,7 +148,7 @@ public class DriftDetectorTest extends DriftTest {
File subConfDir = mkdir(confDir, "subconf");
File server2Conf = createRandomFile(subConfDir, "server-2.conf");
- DriftConfiguration config = driftConfiguration("nested-dirs-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("nested-dirs-test",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
detector.run();
@@ -169,7 +169,7 @@ public class DriftDetectorTest extends DriftTest {
File confDir = mkdir(resourceDir, "conf");
File serverConf = createRandomFile(confDir, "server.conf");
- DriftConfiguration config = driftConfiguration("nothing-to-update",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("nothing-to-update",
resourceDir.getAbsolutePath());
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
detector.run();
@@ -177,19 +177,13 @@ public class DriftDetectorTest extends DriftTest {
File changeSet = changeSet(config.getName(), COVERAGE);
String originalHash = sha256(changeSet);
- // Reset the schedule so that detection will run again the next time we call
- // detection.run()
- DriftDetectionSchedule schedule = scheduleQueue.remove(resourceId(), config);
- schedule.resetSchedule();
- scheduleQueue.addSchedule(schedule);
-
// Run the detector again. Note that nothing has changed so the snapshot should
// remain the same and no drift change set file should be generated.
detector.run();
String newHash = sha256(changeSet);
- assertEquals(newHash, originalHash, "The snapshot file should not have
changed since there was no drift. ");
+ assertEquals(newHash, originalHash, "The snapshot file should not have
changed since there was no drift.");
File driftChangeSet = changeSet(config.getName(), DRIFT);
@@ -199,19 +193,20 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
- public void skipDetectionForScheduledThatIsDisabled() throws Exception {
+ public void skipScheduledThatHasConfigDisabled() throws Exception {
detector.setDriftClient(new DriftClientTestStub() {
{
setBaseDir(resourceDir);
}
@Override
- public void sendChangeSetToServer(DriftDetectionSummary detectionSummary) {
+ public void sendChangeSetToServer(int resourceId, DriftDefinition
driftConfiguration,
+ DriftChangeSetCategory type) {
throw new RuntimeException("Should not invoke drift client when
drift configuration is disabled");
}
});
- DriftConfiguration config = driftConfiguration("disabled-config-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("disabled-config-test",
resourceDir.getAbsolutePath());
config.setEnabled(false);
File confDir = mkdir(resourceDir, "conf");
@@ -224,47 +219,8 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
- public void skipDetectionWhenPreviousSnapshotFileExists() throws Exception {
- // The presence of a previous snapshot file means that the server has
- // not acknowledged that it has received and processed the change set.
- DriftConfiguration config =
driftConfiguration("previous-snapshot-test", resourceDir.getAbsolutePath());
-
- File confDir = mkdir(resourceDir, "conf");
- createRandomFile(confDir, "server.conf");
-
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
- scheduleQueue.addSchedule(schedule);
- detector.run();
-
- // create some drift and generate a new snapshot
- createRandomFile(confDir, "server-1.conf");
- schedule.resetSchedule();
- detector.run();
-
- File snapshot = changeSet(config.getName(), COVERAGE);
- String newHash = sha256(snapshot);
- File previousSnapshot = previousChangeSet(config.getName());
- String oldHash = sha256(previousSnapshot);
-
- // create some drift and make sure drift detection does not run.
- createRandomFile(confDir, "server-2.conf");
- schedule.resetSchedule();
- // Tell driftClient to throw an exception if detector attempts to send
- // the change set report to the server. The detector should never call
- // driftClient in this scenario.
- driftClient.setFailingOnSendChangeSet(true);
- detector.run();
-
- assertEquals(sha256(snapshot), newHash, "The snapshot should not have
changed since the previous snapshot " +
- "is still on disk.");
- assertEquals(sha256(previousSnapshot), oldHash, "The previous snapshot
should not have changed since " +
- "drift detection should not have run until the server acked the previous
snapshot.");
- }
-
- @SuppressWarnings("unchecked")
- @Test
public void includeAddedFileInDriftChangeSet() throws Exception {
- DriftConfiguration config = driftConfiguration("file-added-drift-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("file-added-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -301,7 +257,7 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeModifiedFileInDriftChangeSet() throws Exception {
- DriftConfiguration config =
driftConfiguration("file-modified-drift-test", resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("file-modified-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -339,7 +295,7 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test(enabled = false)
public void includeFiledAddedInNewDirectoryInDriftChangeSet() throws Exception {
- DriftConfiguration config = driftConfiguration("file-added-in-new-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("file-added-in-new-dir",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -377,7 +333,7 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeRemovedFileInDriftChangeSet() throws Exception {
- DriftConfiguration config =
driftConfiguration("file-removed-drift-test", resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("file-removed-drift-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -416,7 +372,7 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked")
@Test
public void includeFilesInRemovedDirectoryInDriftChangeSet() throws Exception {
- DriftConfiguration config = driftConfiguration("dir-removed-test",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("dir-removed-test",
resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf");
File server1Conf = createRandomFile(confDir, "server-1.conf");
@@ -450,169 +406,6 @@ public class DriftDetectorTest extends DriftTest {
coverageChangeSet);
}
- @SuppressWarnings("unchecked")
- @Test
- public void revertToPreviousSnapshotWhenSendingChangeSetFails() throws Exception {
- DriftConfiguration config = driftConfiguration("revert-snapshot-test",
resourceDir.getAbsolutePath());
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
-
- File confDir = mkdir(resourceDir, "conf");
- File server1Conf = createRandomFile(confDir, "server.conf");
-
- scheduleQueue.addSchedule(schedule);
- // generate the initial snapshot
- detector.run();
-
- // Now generate a drift change set
- createRandomFile(confDir, "server-1.conf");
- schedule.resetSchedule();
- detector.run();
-
- File changeSet = changeSet(config.getName(), COVERAGE);
- String currentHash = sha256(changeSet);
-
- // Need to delete the previous version snapshot file; otherwise, the
- // next detection run will be skipped.
- previousChangeSet(config.getName()).delete();
-
- // generate some more drift, and fail on sending the change set
- // to the server
- createRandomFile(confDir, "server-2.conf");
- schedule.resetSchedule();
- driftClient.setFailingOnSendChangeSet(true);
- try {
- detector.run();
- } catch (RuntimeException e) {}
-
- String newHash = sha256(changeSet);
-
- assertEquals(newHash, currentHash, "The snapshot file should be reverted if
sending the new snapshot " +
- "to the server fails.");
- // The previous version file must be deleted on revert; otherwise, drift
- // detection will not run for the schedule if the previous version file
- // is found on disk.
- assertFalse(previousChangeSet(config.getName()).exists(), "The copy of the
previous version snapshot file " +
- "should be deleted once we have reverted back to it and have a new,
current snapsot file.");
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void purgeSnapshotWhenSendingInitialChangeSetFails() throws Exception {
- // If we have just generated the initial change set and sending it to
- // the server fails, then there is no prior snapshot version to which
- // we can revert. We therefore need to purge the snapshot file and
- // allow DriftDetector to simply regenerate the initial change set again.
-
- DriftConfiguration config = driftConfiguration("purge-snapshot-test",
resourceDir.getAbsolutePath());
-
- File confDir = mkdir(resourceDir, "conf");
- createRandomFile(confDir, "server.conf");
-
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
- driftClient.setFailingOnSendChangeSet(true);
- try {
- detector.run();
- } catch (RuntimeException e) {}
-
- assertFalse(changeSet(config.getName(), COVERAGE).exists(), "Snapshot file
should be deleted when " +
- "only the initial change set has been generated and sending change send
report to server fails");
- }
-
- @Test
- public void ignoreFilesThatAreNotReadableForCoverageChangeSet() throws Exception {
- DriftConfiguration config =
driftConfiguration("nonreadable-files-coverage",
resourcesDir.getAbsolutePath());
-
- File confDir = mkdir(resourceDir, "conf");
- File server1Conf = createRandomFile(confDir, "server-1.conf");
- File server2Conf = createRandomFile(confDir, "server-2.conf");
- assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
-
- scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config));
- detector.run();
-
- File changeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> entries =
asList(addedFileEntry("conf/server-1.conf", sha256(server1Conf)));
-
- assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
- assertFileEntriesMatch("Files that are non-readable should be skipped but
other, readable file should still " +
- "be included in the change set", entries, changeSet);
- }
-
- @Test
- public void ignoreNewFilesThatAreNotReadableForDriftChangeSet() throws Exception {
- DriftConfiguration config =
driftConfiguration("nonreadable-files-drfit", resourceDir.getAbsolutePath());
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
-
- File confDir = mkdir(resourceDir, "conf");
- File server1Conf = createRandomFile(confDir, "server-1.conf");
- String oldServer1Hash = sha256(server1Conf);
-
- scheduleQueue.addSchedule(schedule);
- detector.run();
-
- // create some drift that includes a new file that is not readable
- server1Conf.delete();
- server1Conf = createRandomFile(confDir, "server-1.conf");
- String newServer1Hash = sha256(server1Conf);
-
- File server2Conf = createRandomFile(confDir, "server-2.conf");
- assertTrue(server2Conf.setReadable(false), "Failed to make " +
server2Conf.getPath() + " write only");
-
- schedule.resetSchedule();
- detector.run();
-
- File driftChangeSet = changeSet(config.getName(), DRIFT);
- List<FileEntry> driftEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash,
newServer1Hash));
-
- // verify that the drift change set was generated
- assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
- assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
-
- // verify that the coverage change set was updated
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> coverageEntries =
asList(changedFileEntry("conf/server-1.conf", oldServer1Hash,
newServer1Hash));
-
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
- assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
- coverageChangeSet);
- }
-
- @Test
- public void markFileUnderDriftDetectionAsRemovedWhenItIsMadeNonReadable() throws
Exception {
- DriftConfiguration config = driftConfiguration("file-made-nonreadable",
resourceDir.getAbsolutePath());
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
-
- File confDir = mkdir(resourceDir, "conf");
- File server1Conf = createRandomFile(confDir, "server-1.conf");
- String server1Hash = sha256(server1Conf);
-
- scheduleQueue.addSchedule(schedule);
- detector.run();
-
- // make the file non-readable and run the detector again
- assertTrue(server1Conf.setReadable(false), "Failed to make " +
server1Conf.getPath() + " write only");
-
- schedule.resetSchedule();
- detector.run();
-
- File driftChangeSet = changeSet(config.getName(), DRIFT);
- List<FileEntry> driftEntries =
asList(removedFileEntry("conf/server-1.conf", server1Hash));
-
- // verify that the drift change set was generated
- assertTrue(driftChangeSet.exists(), "Expected to find drift change set
" + driftChangeSet.getPath());
- assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT, 1));
- assertFileEntriesMatch("The drift change set does not match the expected
values", driftEntries, driftChangeSet);
-
- // verify that the coverage change set was updated
- File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- List<FileEntry> coverageEntries = emptyList();
-
- assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE, 1));
- assertFileEntriesMatch("The coverage change set was not updated as
expected", coverageEntries,
- coverageChangeSet);
- }
-
void assertHeaderEquals(File changeSet, Headers expected) throws Exception {
ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new
FileReader(changeSet)));
Headers actual = reader.getHeaders();
@@ -631,15 +424,15 @@ public class DriftDetectorTest extends DriftTest {
assertCollectionMatchesNoOrder(msg, expected, actual);
}
- Headers createHeaders(DriftConfiguration driftConfig, DriftChangeSetCategory type) {
+ Headers createHeaders(DriftDefinition driftConfig, DriftChangeSetCategory type) {
return createHeaders(driftConfig, type, 0);
}
- Headers createHeaders(DriftConfiguration driftConfig, DriftChangeSetCategory type,
int version) {
+ Headers createHeaders(DriftDefinition driftConfig, DriftChangeSetCategory type, int
version) {
Headers headers = new Headers();
headers.setResourceId(resourceId());
- headers.setDriftCofigurationId(driftConfig.getId());
- headers.setDriftConfigurationName(driftConfig.getName());
+ headers.setDriftDefinitionId(driftConfig.getId());
+ headers.setDriftDefinitionName(driftConfig.getName());
headers.setBasedir(resourceDir.getAbsolutePath());
headers.setType(type);
headers.setVersion(version);
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java
index bace111..a70ab8c 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java
@@ -179,8 +179,8 @@ public class DriftFilesSenderTest extends DriftTest {
Headers createHeaders(String configName, DriftChangeSetCategory type) {
Headers headers = new Headers();
headers.setResourceId(resourceId());
- headers.setDriftCofigurationId(0);
- headers.setDriftConfigurationName(configName);
+ headers.setDriftDefinitionId(0);
+ headers.setDriftDefinitionName(configName);
headers.setBasedir(resourceDir.getAbsolutePath());
headers.setType(type);
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
index ae3a940..696561a 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java
@@ -32,7 +32,7 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.server.drift.DriftServerService;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.pc.PluginContainerConfiguration;
@@ -75,12 +75,11 @@ public class DriftManagerTest extends DriftTest {
driftMgr = new TestDriftManager();
driftMgr.setConfiguration(pcConfig);
- driftMgr.setChangeSetMgr(changeSetMgr);
}
@Test
public void writeChangeSetZipFileToChangeSetDirectory() throws Exception {
- final DriftConfiguration config =
driftConfiguration("write-changeset-file", resourceDir.getAbsolutePath());
+ final DriftDefinition config =
driftConfiguration("write-changeset-file", resourceDir.getAbsolutePath());
final File changeSetDir = changeSetDir(config.getName());
createRandomFile(changeSetDir, "changeset.txt");
@@ -94,19 +93,14 @@ public class DriftManagerTest extends DriftTest {
}
});
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
- DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
- detectionSummary.setSchedule(schedule);
- detectionSummary.setType(COVERAGE);
-
driftMgr.setChangeSetMgr(changeSetMgr);
- driftMgr.getSchedulesQueue().addSchedule(schedule);
- driftMgr.sendChangeSetToServer(detectionSummary);
+ driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
+ driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
}
@Test
public void sendChangeSetReportInZipFile() throws Exception {
- final DriftConfiguration config =
driftConfiguration("send-changeset-in-zip", resourceDir.getAbsolutePath());
+ final DriftDefinition config =
driftConfiguration("send-changeset-in-zip", resourceDir.getAbsolutePath());
final File changeSetDir = changeSetDir(config.getName());
final File changeSetFile = createRandomFile(changeSetDir,
"changeset.txt");
@@ -117,32 +111,32 @@ public class DriftManagerTest extends DriftTest {
}
});
- DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(),
config);
- DriftDetectionSummary detectionSummary = new DriftDetectionSummary();
- detectionSummary.setSchedule(schedule);
- detectionSummary.setType(COVERAGE);
-
driftMgr.setChangeSetMgr(changeSetMgr);
driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
- driftMgr.sendChangeSetToServer(detectionSummary);
+ driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
}
@Test
- public void cleanUpWhenServerAcksChangeSet() throws Exception {
- DriftConfiguration config =
driftConfiguration("clean-up-when-server-acks-changeset",
- resourceDir.getAbsolutePath());
- File changeSetDir = changeSetDir(config.getName());
- File snapshotFile = createRandomFile(changeSetDir, "changeset.txt");
- File previousSnapshotFile = createRandomFile(changeSetDir,
"changeset.txt.previous");
- File changeSetZipFile = createRandomFile(changeSetDir, "changeset_" +
System.currentTimeMillis() + ".zip");
+ public void cleanUpAfterSendingChangeSetToServer() throws Exception {
+ final DriftDefinition config =
driftConfiguration("send-changeset-in-zip", resourceDir.getAbsolutePath());
+ final File changeSetDir = changeSetDir(config.getName());
+ createRandomFile(changeSetDir, "changeset.txt");
- driftMgr.ackChangeSet(resourceId(), config.getName());
+ driftMgr.setChangeSetMgr(changeSetMgr);
+ driftMgr.getSchedulesQueue().addSchedule(new DriftDetectionSchedule(resourceId(),
config));
+ driftMgr.sendChangeSetToServer(resourceId(), config, COVERAGE);
+
+ // clean up should not happen until after the input stream is closed. The remote
+ // input stream is consumed asynchronously; so, we have to wait until the stream
+ // is closed. We could otherwise disrupt the transmission of bits.
+
+ File changeSetZip = assertThatZipFileExists(changeSetDir, "changeset_",
"Expected to find change set zip " +
+ "zip file in " + changeSetDir.getPath() + ". The file name
should follow the pattern " +
+ "changeset_<integer_timestamp>.zip");
- assertTrue(snapshotFile.exists(), "Snapshot file should exist after server
acks change set");
- assertFalse(previousSnapshotFile.exists(), "Previous version snapshot file
should be deleted when server " +
- "acks change set");
- assertEquals(findChangeSetZipFiles(changeSetDir).size(), 0, "All change set
zip files should be deleted when " +
- "server acks change set");
+ driftServerService.inputStream.close();
+
+ assertFalse(changeSetZip.exists(), "The change set zip should be deleted
when the remote input stream is closed.");
}
@Test
@@ -183,28 +177,35 @@ public class DriftManagerTest extends DriftTest {
});
driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir);
-
- // verify that the content directory is purged
- assertThatDirectoryIsEmpty(contentDir);
}
@Test
- public void cleanUpWhenServerAcksChangeSetContent() throws Exception {
- String configName = "cleanup-when-server-acks-content";
+ public void cleanUpAfterSendingContentToServer() throws Exception {
+ String configName = "clean-up-after-sending-content";
File changeSetDir = changeSetDir(configName);
File contentDir = mkdir(changeSetDir, "content");
- String token = Long.toString(System.currentTimeMillis());
- File contentZipFile = createRandomFile(changeSetDir, "content_" + token
+ ".zip");
+ createRandomFile(contentDir, "content-1");
+ createRandomFile(contentDir, "content-2");
+
+ driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir);
- driftMgr.ackChangeSetContent(resourceId(), configName, token);
+ // clean up should not happen until after the input stream is closed. The remote
+ // input stream is consumed asynchronously; so, we have to wait until the stream
+ // is closed. We could otherwise disrupt the transmission of bits.
+ File contentZipFile = assertThatZipFileExists(changeSetDir,
"content_",
+ "Expected to find content zip file in " +
+ changeSetDir.getPath() + ". The file name should have a pattern of
content_integer_timestamp>.zip");
- assertFalse(contentZipFile.exists(), "Content zip file should be purged
after server sends content ack");
+ driftServerService.inputStream.close();
+
+ assertFalse(contentZipFile.exists(), "The content zip should be deleted when
the remote input stream is closed");
+ assertThatDirectoryIsEmpty(contentDir);
}
@Test
public void unschedulingDetectionRemovesScheduleFromQueue() throws Exception {
- DriftConfiguration config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
driftMgr.scheduleDriftDetection(resourceId(), config);
driftMgr.scheduleDriftDetection(resourceId() + 5,
driftConfiguration("another-config", "."));
@@ -216,8 +217,8 @@ public class DriftManagerTest extends DriftTest {
@Test
public void unschedulingDetectionRemovesDriftConfigFromResourceContainer() throws
Exception {
- DriftConfiguration config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
- DriftConfiguration config2 = driftConfiguration("do-not-remove",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("remove-from-queue",
resourceDir.getAbsolutePath());
+ DriftDefinition config2 = driftConfiguration("do-not-remove",
resourceDir.getAbsolutePath());
driftMgr.scheduleDriftDetection(resourceId(), config);
driftMgr.scheduleDriftDetection(resourceId(), config2);
@@ -226,12 +227,12 @@ public class DriftManagerTest extends DriftTest {
ResourceContainer container =
driftMgr.getInventoryManager().getResourceContainer(resourceId());
assertCollectionMatchesNoOrder(config + " should have been removed from the
resource container ",
- asList(config2), container.getDriftConfigurations());
+ asList(config2), container.getDriftDefinitions());
}
@Test
public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsNotActive()
throws Exception {
- DriftConfiguration config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
File changeSetDir = changeSetDir(config.getName());
File contentDir = mkdir(changeSetDir, "content");
@@ -246,7 +247,7 @@ public class DriftManagerTest extends DriftTest {
@Test
public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsDeactivated()
throws Exception {
- DriftConfiguration config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
+ DriftDefinition config = driftConfiguration("delete-changeset-dir",
resourceDir.getAbsolutePath());
File changeSetDir = changeSetDir(config.getName());
File contentDir = mkdir(changeSetDir, "content");
@@ -265,16 +266,6 @@ public class DriftManagerTest extends DriftTest {
"deactivated.");
}
- private List<File> findChangeSetZipFiles(File dir) {
- File[] files = dir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return name.startsWith("changeset_") &&
name.endsWith(".zip");
- }
- });
- return asList(files);
- }
-
/**
* This method first verifies that each of the expected files is contained in the
the
* zip file. Then it verifies that the content for each file in the zip file matches
@@ -360,8 +351,6 @@ public class DriftManagerTest extends DriftTest {
private static class TestDriftServerService implements DriftServerService {
public int resourceId;
- public String driftConfigName;
- public String token;
public long fileSize;
public InputStream inputStream;
@@ -379,11 +368,8 @@ public class DriftManagerTest extends DriftTest {
}
@Override
- public void sendFilesZip(int resourceId, String driftConfigName, String token,
long zipSize,
- InputStream zipStream) {
+ public void sendFilesZip(int resourceId, long zipSize, InputStream zipStream) {
this.resourceId = resourceId;
- this.driftConfigName = driftConfigName;
- this.token = token;
fileSize = zipSize;
inputStream = zipStream;
@@ -393,7 +379,7 @@ public class DriftManagerTest extends DriftTest {
}
@Override
- public Map<Integer, List<DriftConfiguration>>
getDriftConfigurations(Set<Integer> resourceIds) {
+ public Map<Integer, List<DriftDefinition>>
getDriftDefinitions(Set<Integer> resourceIds) {
return null;
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
index a267402..ad32251 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java
@@ -31,7 +31,7 @@ import org.testng.annotations.BeforeMethod;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.util.MessageDigestGenerator;
import static java.util.Arrays.asList;
@@ -243,7 +243,7 @@ public class DriftTest {
}
/**
- * Creates a {@link DriftConfiguration} with the specified basedir. The file system
is
+ * Creates a {@link DriftDefinition} with the specified basedir. The file system is
* used as the context for the basedir which means the path specified is used as is.
* The interval property is set to {@link #defaultInterval}.
*
@@ -251,10 +251,10 @@ public class DriftTest {
* @param basedir An absolute path of the base directory
* @return The drift configuration object
*/
- protected DriftConfiguration driftConfiguration(String name, String basedir) {
- DriftConfiguration config = new DriftConfiguration(new Configuration());
+ protected DriftDefinition driftConfiguration(String name, String basedir) {
+ DriftDefinition config = new DriftDefinition(new Configuration());
config.setName(name);
- config.setBasedir(new DriftConfiguration.BaseDirectory(fileSystem, basedir));
+ config.setBasedir(new DriftDefinition.BaseDirectory(fileSystem, basedir));
config.setEnabled(true);
config.setInterval(defaultInterval);
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
index fa9fa06..78bdd58 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
@@ -104,34 +104,34 @@ public class LinkManager {
public static String getEntityTabLink(EntityContext entityContext, String tabName,
String subTabName) {
String link;
switch (entityContext.getType()) {
- case Resource:
- link = getResourceTabLink(entityContext.getResourceId(), tabName,
subTabName);
- break;
- case ResourceGroup:
- if (entityContext.isAutoGroup()) {
- link = getAutoGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
- } else if (entityContext.isAutoCluster()) {
- link = getAutoClusterTabLink(entityContext.getGroupId(), tabName,
subTabName);
- } else {
- link = getResourceGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
- }
- break;
- case SubsystemView:
- if (tabName.equals("Alerts") &&
subTabName.equals("Definitions")) {
- link = "#Reports/Subsystems/AlertDefinitions";
- } else if (tabName.equals("Alerts") &&
subTabName.equals("History")) {
- link = "#Reports/Subsystems/RecentAlerts";
- } else if (tabName.equals("Operations") &&
subTabName.equals("History")) {
- link = "#Reports/Subsystems/RecentOperations";
- } else if (tabName.equals("Configuration") &&
subTabName.equals("History")) {
- link = "#Reports/Subsystems/ConfigurationHistoryView";
- } else {
- throw new IllegalArgumentException("Subsystem link not supported
for tab " + tabName + ">"
- + subTabName + ".");
- }
- break;
- default:
- throw new IllegalArgumentException("Unsupported entity context type:
" + entityContext.getType());
+ case Resource:
+ link = getResourceTabLink(entityContext.getResourceId(), tabName,
subTabName);
+ break;
+ case ResourceGroup:
+ if (entityContext.isAutoGroup()) {
+ link = getAutoGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ } else if (entityContext.isAutoCluster()) {
+ link = getAutoClusterTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ } else {
+ link = getResourceGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ }
+ break;
+ case SubsystemView:
+ if (tabName.equals("Alerts") &&
subTabName.equals("Definitions")) {
+ link = "#Reports/Subsystems/AlertDefinitions";
+ } else if (tabName.equals("Alerts") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/RecentAlerts";
+ } else if (tabName.equals("Operations") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/RecentOperations";
+ } else if (tabName.equals("Configuration") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/ConfigurationHistoryView";
+ } else {
+ throw new IllegalArgumentException("Subsystem link not supported for
tab " + tabName + ">" + subTabName
+ + ".");
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported entity context type:
" + entityContext.getType());
}
return link;
}
@@ -491,8 +491,8 @@ public class LinkManager {
return "#Resource/" + resourceId + "/Drift/History/" +
driftId;
}
- public static String getDriftConfigurationLink(int resourceId, int driftConfigId) {
- return "#Resource/" + resourceId + "/Drift/Configuration/" +
driftConfigId;
+ public static String getDriftDefinitionEditLink(int resourceId, int driftDefId) {
+ return "#Resource/" + resourceId + "/Drift/Definitions/" +
driftDefId + "/Edit";
}
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java
index 92913f9..2474f02 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ConditionsEditor.java
@@ -163,13 +163,13 @@ public class ConditionsEditor extends LocatableVLayout {
// the drift config.
if (type != resourceType) {
// paranoia, unsure if this is needed but clear out
any old drift config still hanging around
- if (resourceType.getDriftConfigurationTemplates() !=
null) {
-
resourceType.getDriftConfigurationTemplates().clear();
+ if (resourceType.getDriftDefinitionTemplates() !=
null) {
+
resourceType.getDriftDefinitionTemplates().clear();
}
// if the newly loaded resource type supports drift,
put it in our type object
- if (type.getDriftConfigurationTemplates() != null) {
- for (ConfigurationTemplate ct :
type.getDriftConfigurationTemplates()) {
-
resourceType.addDriftConfigurationTemplate(ct);
+ if (type.getDriftDefinitionTemplates() != null) {
+ for (ConfigurationTemplate ct :
type.getDriftDefinitionTemplates()) {
+ resourceType.addDriftDefinitionTemplate(ct);
}
}
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java
index 23b59f6..5142a7c 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewConditionEditor.java
@@ -133,7 +133,7 @@ public class NewConditionEditor extends LocatableDynamicForm {
this.supportsEvents = (rtype.getEventDefinitions() != null &&
rtype.getEventDefinitions().size() > 0);
this.supportsResourceConfig = (rtype.getResourceConfigurationDefinition() !=
null);
- this.supportsDrift = (rtype.getDriftConfigurationTemplates() != null &&
rtype.getDriftConfigurationTemplates()
+ this.supportsDrift = (rtype.getDriftDefinitionTemplates() != null &&
rtype.getDriftDefinitionTemplates()
.size() > 0);
Set<MeasurementDefinition> metricDefinitions =
rtype.getMetricDefinitions();
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/Carousel.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/Carousel.java
new file mode 100644
index 0000000..9388bbc
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/Carousel.java
@@ -0,0 +1,1135 @@
+/*
+ * 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.gui.coregui.client.components.carousel;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.google.gwt.event.dom.client.KeyCodes;
+import com.smartgwt.client.data.Criteria;
+import com.smartgwt.client.data.SortSpecifier;
+import com.smartgwt.client.types.Overflow;
+import com.smartgwt.client.types.SelectionStyle;
+import com.smartgwt.client.types.VerticalAlignment;
+import com.smartgwt.client.util.BooleanCallback;
+import com.smartgwt.client.util.SC;
+import com.smartgwt.client.widgets.Canvas;
+import com.smartgwt.client.widgets.HTMLFlow;
+import com.smartgwt.client.widgets.IButton;
+import com.smartgwt.client.widgets.Img;
+import com.smartgwt.client.widgets.Label;
+import com.smartgwt.client.widgets.events.ClickEvent;
+import com.smartgwt.client.widgets.events.ClickHandler;
+import com.smartgwt.client.widgets.events.DoubleClickHandler;
+import com.smartgwt.client.widgets.form.fields.FormItem;
+import com.smartgwt.client.widgets.form.fields.HiddenItem;
+import com.smartgwt.client.widgets.form.fields.SelectItem;
+import com.smartgwt.client.widgets.form.fields.TextItem;
+import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
+import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
+import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
+import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
+import com.smartgwt.client.widgets.layout.HLayout;
+import com.smartgwt.client.widgets.layout.LayoutSpacer;
+import com.smartgwt.client.widgets.menu.IMenuButton;
+import com.smartgwt.client.widgets.menu.MenuItem;
+import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
+
+import org.rhq.core.domain.search.SearchSubsystem;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.RefreshableView;
+import org.rhq.enterprise.gui.coregui.client.components.form.SearchBarItem;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIMenuButton;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
+
+/**
+ * Similar to (i.e. originally a copy of) Table but instead of encapsulating a ListGrid,
it manages a list of
+ * @{link CarouselMember}s, offering horizontal presentation of the member canvases, high
level filtering, and
+ * other member-wide handling.
+ *
+ * @author Jay Shaughnessy
+ */
+@SuppressWarnings("unchecked")
+public abstract class Carousel extends LocatableHLayout implements RefreshableView {
+
+ private static final String FILTER_CAROUSEL_START = "CarouselStart";
+ private static final String FILTER_CAROUSEL_SIZE = "CarouselSize";
+
+ private LocatableVLayout contents;
+
+ private HLayout titleLayout;
+ private Canvas titleComponent;
+ private HTMLFlow titleCanvas;
+ private String titleString;
+ private List<String> titleIcons = new ArrayList<String>();
+
+ private Canvas carouselDetails;
+
+ private CarouselFilter filterForm;
+
+ private LocatableHLayout carouselHolder;
+
+ private Label carouselInfo;
+
+ private boolean showTitle = true;
+ private boolean showFooter = true;
+ private boolean showFooterRefresh = true;
+ private boolean showFilterForm = true;
+
+ private Criteria initialCriteria;
+ private boolean initialCriteriaFixed = true;
+ @SuppressWarnings("unused")
+ private SortSpecifier[] sortSpecifiers;
+ @SuppressWarnings("unused")
+ private String[] excludedFieldNames;
+ @SuppressWarnings("unused")
+ private boolean autoFetchData;
+ @SuppressWarnings("unused")
+ private boolean flexRowDisplay = true;
+ private boolean hideSearchBar = false;
+ private String initialSearchBarSearchText = null;
+
+ private List<CarouselActionInfo> carouselActions = new
ArrayList<CarouselActionInfo>();
+ private boolean carouselActionDisableOverride = false;
+ protected List<Canvas> extraWidgetsAboveFooter = new
ArrayList<Canvas>();
+ protected List<Canvas> extraWidgetsInMainFooter = new
ArrayList<Canvas>();
+ private LocatableToolStrip footer;
+ private LocatableToolStrip footerExtraWidgets;
+ private LocatableIButton refreshButton;
+ private LocatableIButton nextButton;
+ private LocatableIButton previousButton;
+ private LocatableIButton widthButton;
+
+ // null indicates filtering on the member number
+ private Integer carouselStartFilter = null;
+ // null indicates no limit to the carousel size. This can be dangerous.
+ private Integer carouselSizeFilter = null;
+ private boolean carouselDirty = false;
+ private boolean carouselUsingFixedWidths = false;
+
+ public Carousel(String locatorId) {
+ this(locatorId, null, null, null, null, true);
+ }
+
+ public Carousel(String locatorId, String titleString) {
+ this(locatorId, titleString, null, null, null, true);
+ }
+
+ public Carousel(String locatorId, String titleString, Criteria criteria) {
+ this(locatorId, titleString, criteria, null, null, true);
+ }
+
+ public Carousel(String locatorId, String titleString, SortSpecifier[] sortSpecifiers)
{
+ this(locatorId, titleString, null, sortSpecifiers, null, true);
+ }
+
+ protected Carousel(String locatorId, String titleString, SortSpecifier[]
sortSpecifiers, Criteria criteria) {
+ this(locatorId, titleString, criteria, sortSpecifiers, null, true);
+ }
+
+ public Carousel(String locatorId, String titleString, boolean autoFetchData) {
+ this(locatorId, titleString, null, null, null, autoFetchData);
+ }
+
+ public Carousel(String locatorId, String titleString, SortSpecifier[] sortSpecifiers,
String[] excludedFieldNames) {
+ this(locatorId, titleString, null, sortSpecifiers, excludedFieldNames, true);
+ }
+
+ public Carousel(String locatorId, String titleString, Criteria criteria,
SortSpecifier[] sortSpecifiers,
+ String[] excludedFieldNames) {
+ this(locatorId, titleString, criteria, sortSpecifiers, excludedFieldNames,
true);
+ }
+
+ public Carousel(String locatorId, String titleString, Criteria criteria,
SortSpecifier[] sortSpecifiers,
+ String[] excludedFieldNames, boolean autoFetchData) {
+ super(locatorId);
+
+ setWidth100();
+ setHeight100();
+ setOverflow(Overflow.HIDDEN);
+
+ this.titleString = titleString;
+ this.initialCriteria = criteria;
+ this.sortSpecifiers = sortSpecifiers;
+ this.excludedFieldNames = excludedFieldNames;
+ this.autoFetchData = autoFetchData;
+ }
+
+ /**
+ * If this returns true, then even if a {@link #getSearchSubsystem() search
subsystem}
+ * is defined by the class, the search bar will not be shown.
+ *
+ * @return true if the search bar is to be hidden (default is false)
+ */
+ public boolean getHideSearchBar() {
+ return this.hideSearchBar;
+ }
+
+ public void setHideSearchBar(boolean flag) {
+ this.hideSearchBar = flag;
+ }
+
+ public String getInitialSearchBarSearchText() {
+ return this.initialSearchBarSearchText;
+ }
+
+ public void setInitialSearchBarSearchText(String text) {
+ this.initialSearchBarSearchText = text;
+ }
+
+ public void setFlexRowDisplay(boolean flexRowDisplay) {
+ this.flexRowDisplay = flexRowDisplay;
+ }
+
+ @Override
+ protected void onInit() {
+ super.onInit();
+
+ contents = new LocatableVLayout(extendLocatorId("Contents"));
+ contents.setWidth100();
+ contents.setHeight100();
+ //contents.setOverflow(Overflow.AUTO);
+ addMember(contents);
+
+ filterForm = new CarouselFilter(this);
+
+ /*
+ * carousel filters and search bar are currently mutually exclusive
+ */
+
+ if (getSearchSubsystem() == null) {
+ configureCarouselFilters();
+
+ } else {
+ if (!this.hideSearchBar) {
+ final SearchBarItem searchFilter = new SearchBarItem("search",
MSG.common_button_search(),
+ getSearchSubsystem(), getInitialSearchBarSearchText());
+ setFilterFormItems(searchFilter);
+ }
+ }
+
+ carouselHolder = new LocatableHLayout(extendLocatorId("Holder"));
+ carouselHolder.setOverflow(Overflow.AUTO);
+ carouselHolder.setWidth100();
+ contents.addMember(carouselHolder);
+ }
+
+ protected SelectionStyle getDefaultSelectionStyle() {
+ return SelectionStyle.MULTIPLE;
+ }
+
+ @Override
+ protected void onDraw() {
+ try {
+ super.onDraw();
+
+ for (Canvas child : contents.getMembers()) {
+ contents.removeChild(child);
+ }
+
+ // Title
+ this.titleCanvas = new HTMLFlow();
+ setTitleString(this.titleString);
+
+ if (showTitle) {
+ titleLayout = new
LocatableHLayout(contents.extendLocatorId("Title"));
+ titleLayout.setAutoHeight();
+ titleLayout.setAlign(VerticalAlignment.BOTTOM);
+ contents.addMember(titleLayout, 0);
+ }
+
+ if (null != carouselDetails) {
+ contents.addMember(carouselDetails);
+ }
+
+ if (filterForm.hasContent()) {
+ contents.addMember(filterForm);
+ }
+
+ contents.addMember(carouselHolder);
+
+ // Footer
+
+ // A second toolstrip that optionally appears before the main footer - it
will contain extra widgets.
+ // This is hidden from view unless extra widgets are actually added to the
carousel above the main footer.
+ this.footerExtraWidgets = new
LocatableToolStrip(contents.extendLocatorId("FooterExtraWidgets"));
+ footerExtraWidgets.setPadding(5);
+ footerExtraWidgets.setWidth100();
+ footerExtraWidgets.setMembersMargin(15);
+ footerExtraWidgets.hide();
+ contents.addMember(footerExtraWidgets);
+
+ this.footer = new
LocatableToolStrip(contents.extendLocatorId("Footer"));
+ footer.setPadding(5);
+ footer.setWidth100();
+ footer.setMembersMargin(15);
+ contents.addMember(footer);
+
+ // The ListGrid has been created and configured
+ // Now give subclasses a chance to configure the carousel
+ configureCarousel();
+
+ Label carouselInfo = new Label();
+ carouselInfo.setWrap(false);
+ setCarouselInfo(carouselInfo);
+ refreshRowCount();
+
+ if (showTitle) {
+ drawTitle();
+ }
+
+ if (showFooter) {
+ drawFooter();
+ }
+ } catch (Exception e) {
+
CoreGUI.getErrorHandler().handleError(MSG.view_table_drawFail(this.toString()), e);
+ }
+ }
+
+ private void refreshRowCount() {
+ }
+
+ @Override
+ public void destroy() {
+ SeleniumUtility.destroyMembers(contents);
+ super.destroy();
+ }
+
+ private void drawTitle() {
+ for (String headerIcon : titleIcons) {
+ Img img = new Img(headerIcon, 24, 24);
+ img.setPadding(4);
+ titleLayout.addMember(img);
+ }
+
+ titleLayout.addMember(titleCanvas);
+
+ if (titleComponent != null) {
+ titleLayout.addMember(new LayoutSpacer());
+ titleLayout.addMember(titleComponent);
+ }
+ }
+
+ private void drawFooter() {
+ // populate the extraWidgets toolstrip
+ footerExtraWidgets.removeMembers(footerExtraWidgets.getMembers());
+ if (!extraWidgetsAboveFooter.isEmpty()) {
+ for (Canvas extraWidgetCanvas : extraWidgetsAboveFooter) {
+ footerExtraWidgets.addMember(extraWidgetCanvas);
+ }
+ footerExtraWidgets.show();
+ }
+
+ footer.removeMembers(footer.getMembers());
+
+ for (final CarouselActionInfo carouselAction : carouselActions) {
+
+ if (null == carouselAction.getValueMap()) {
+ // button action
+ IButton button = new LocatableIButton(carouselAction.getLocatorId(),
carouselAction.getTitle());
+ button.setDisabled(true);
+ button.setOverflow(Overflow.VISIBLE);
+ button.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ disableAllFooterControls();
+ if (carouselAction.confirmMessage != null) {
+ String message =
carouselAction.confirmMessage.replaceAll("\\#", "TODO:");
+
+ SC.ask(message, new BooleanCallback() {
+ public void execute(Boolean confirmed) {
+ if (confirmed) {
+ carouselAction.action.executeAction(null);
+ } else {
+ refreshCarouselInfo();
+ }
+ }
+ });
+ } else {
+ carouselAction.action.executeAction(null);
+ }
+ }
+ });
+
+ carouselAction.actionCanvas = button;
+ footer.addMember(button);
+
+ } else {
+ // menu action
+ LocatableMenu menu = new LocatableMenu(carouselAction.getLocatorId() +
"Menu");
+ final Map<String, ? extends Object> menuEntries =
carouselAction.getValueMap();
+ for (final String key : menuEntries.keySet()) {
+ MenuItem item = new MenuItem(key);
+ item.addClickHandler(new
com.smartgwt.client.widgets.menu.events.ClickHandler() {
+ public void onClick(MenuItemClickEvent event) {
+ disableAllFooterControls();
+
carouselAction.getAction().executeAction(menuEntries.get(key));
+ }
+ });
+ menu.addItem(item);
+ }
+
+ IMenuButton menuButton = new
LocatableIMenuButton(carouselAction.getLocatorId(), carouselAction
+ .getTitle());
+ menuButton.setMenu(menu);
+ menuButton.setDisabled(true);
+ menuButton.setAutoFit(true); // this makes it pretty tight, but maybe
better than the default, which is pretty wide
+ menuButton.setOverflow(Overflow.VISIBLE);
+ menuButton.setShowMenuBelow(false);
+
+ carouselAction.actionCanvas = menuButton;
+ footer.addMember(menuButton);
+ }
+ }
+
+ for (Canvas extraWidgetCanvas : extraWidgetsInMainFooter) {
+ footer.addMember(extraWidgetCanvas);
+ }
+
+ footer.addMember(new LayoutSpacer());
+
+ widthButton = new LocatableIButton(extendLocatorId("Width"),
MSG.common_button_fixedWidth());
+ widthButton.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ carouselUsingFixedWidths = !carouselUsingFixedWidths;
+ widthButton.setTitle(carouselUsingFixedWidths ?
MSG.common_button_scaleToFit() : MSG
+ .common_button_fixedWidth());
+ buildCarousel(true);
+ }
+ });
+ footer.addMember(widthButton);
+
+ if (isShowFooterRefresh()) {
+ this.refreshButton = new
LocatableIButton(extendLocatorId("Refresh"), MSG.common_button_refresh());
+ refreshButton.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ disableAllFooterControls();
+ refresh();
+ }
+ });
+ footer.addMember(refreshButton);
+ }
+
+ previousButton = new LocatableIButton(extendLocatorId("Previous"),
MSG.common_button_previous());
+ previousButton.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ disableAllFooterControls();
+ previous();
+ }
+ });
+ footer.addMember(previousButton);
+
+ nextButton = new LocatableIButton(extendLocatorId("Next"),
MSG.common_button_next());
+ nextButton.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ disableAllFooterControls();
+ next();
+ }
+ });
+ footer.addMember(nextButton);
+
+ footer.addMember(carouselInfo);
+
+ // Ensure buttons are initially set correctly.
+ refreshCarouselInfo();
+ }
+
+ private void previous() {
+ if (null == carouselSizeFilter) {
+ carouselSizeFilter = getDefaultCarouselSize();
+ }
+ if (null != carouselStartFilter) {
+ int newStart = carouselStartFilter + carouselSizeFilter;
+ setCarouselStartFilter(newStart);
+ }
+ buildCarousel(true);
+ }
+
+ private void next() {
+ if (null == carouselSizeFilter) {
+ carouselSizeFilter = getDefaultCarouselSize();
+ }
+
+ if (null != carouselStartFilter) {
+ int newStart = carouselStartFilter - carouselSizeFilter;
+ newStart = (newStart < carouselSizeFilter) ? carouselSizeFilter :
newStart;
+ setCarouselStartFilter(newStart);
+ }
+ buildCarousel(true);
+ }
+
+ protected abstract int getDefaultCarouselSize();
+
+ protected abstract String getCarouselMemberFixedWidth();
+
+ protected abstract String getCarouselStartFilterLabel();
+
+ protected abstract String getCarouselSizeFilterLabel();
+
+ private void disableAllFooterControls() {
+ for (CarouselActionInfo action : carouselActions) {
+ action.actionCanvas.disable();
+ }
+ for (Canvas extraWidget : extraWidgetsAboveFooter) {
+ extraWidget.disable();
+ }
+ for (Canvas extraWidget : extraWidgetsInMainFooter) {
+ extraWidget.disable();
+ }
+ if (isShowFooterRefresh() && this.refreshButton != null) {
+ this.refreshButton.disable();
+ }
+ }
+
+ /**
+ * Subclasses can use this as a chance to configure the list grid after it has been
+ * created but before it has been drawn to the DOM. This is also the proper place to
add
+ * actions so that they're rendered in the footer.
+ */
+ protected void configureCarousel() {
+ return;
+ }
+
+ /**
+ * If not overriden this will append the standard carousel filters to those already
supplied. To ensure
+ * the supplied form items end a row, call {@link FormItem#setEndRow(Boolean)} as
needed. The filter form is
+ * set to use 6 columns, which allows the carousle filters to fit on one row.
+ * @param formItems
+ */
+ public void setFilterFormItems(FormItem... formItems) {
+ // since Arrays.copyOf is unsupported...
+ FormItem[] carouselFormItems = new FormItem[2 + formItems.length];
+ int i = 0;
+ for (FormItem item : formItems) {
+ carouselFormItems[i++] = item;
+ }
+
+ // drift file path filter
+ TextItem startFilter = new TextItem(FILTER_CAROUSEL_START,
getCarouselStartFilterLabel());
+ TextItem numFilter = new TextItem(FILTER_CAROUSEL_SIZE,
getCarouselSizeFilterLabel());
+ carouselFormItems[i++] = startFilter;
+ carouselFormItems[i++] = numFilter;
+
+ this.filterForm.setNumCols(4);
+ this.filterForm.setItems(carouselFormItems);
+ }
+
+ /**
+ * Overriding components can use this as a chance to add {@link FormItem}s which will
filter
+ * the carousel members that display their data. If not overriden the standard
carousel filters are applied.
+ */
+ protected void configureCarouselFilters() {
+ setFilterFormItems();
+ }
+
+ /**
+ * Set the Carousel's title string. This will subsequently call {@link
#updateTitleCanvas(String)}.
+ * @param titleString
+ */
+ public void setTitleString(String titleString) {
+ this.titleString = titleString;
+ if (this.titleCanvas != null) {
+ updateTitleCanvas(titleString);
+ }
+ }
+
+ public Canvas getTitleCanvas() {
+ return this.titleCanvas;
+ }
+
+ /**
+ * To set the Carousel's title, call {@link #setTitleString(String)}. This is
primarily declared for purposes of
+ * override.
+ * @param titleString
+ */
+ public void updateTitleCanvas(String titleString) {
+ if (titleString == null) {
+ titleString = "";
+ }
+ if (titleString.length() > 0) {
+ titleCanvas.setWidth100();
+ titleCanvas.setHeight(35);
+ titleCanvas.setContents(titleString);
+ titleCanvas.setPadding(4);
+ titleCanvas.setStyleName("HeaderLabel");
+ } else {
+ titleCanvas.setWidth100();
+ titleCanvas.setHeight(0);
+ titleCanvas.setContents(null);
+ titleCanvas.setPadding(0);
+ titleCanvas.setStyleName("normal");
+ }
+
+ titleCanvas.markForRedraw();
+ }
+
+ /**
+ * Returns the encompassing canvas that contains all content for this component.
+ * This content includes the carousel members, the buttons, etc.
+ */
+ public Canvas getCarouselContents() {
+ return this.contents;
+ }
+
+ public boolean isShowTitle() {
+ return showTitle;
+ }
+
+ public void setShowTitle(boolean showTitle) {
+ this.showTitle = showTitle;
+ }
+
+ public boolean isShowFooter() {
+ return showFooter;
+ }
+
+ public void setShowFooter(boolean showFooter) {
+ this.showFooter = showFooter;
+ }
+
+ protected boolean isInitialCriteriaFixed() {
+ return initialCriteriaFixed;
+ }
+
+ /**
+ * @param initialCriteriaFixed If true initialCriteria is applied to all subsequent
fetch criteria. If false
+ * initialCriteria is used only for the initial autoFetch. Irrelevant if autoFetch is
false. Default is true.
+ */
+ protected void setInitialCriteriaFixed(boolean initialCriteriaFixed) {
+ this.initialCriteriaFixed = initialCriteriaFixed;
+ }
+
+ /**
+ *
+ * @return the current criteria, which includes any fixed criteria, as well as any
user-specified filters; may be
+ * null if there are no fixed criteria or user-specified filters
+ */
+ protected Criteria getCurrentCriteria() {
+ Criteria criteria = null;
+
+ // If this carousel has a filter form (filters OR search bar),
+ // we need to refresh it as per the filtering, combined with any fixed criteria.
+ if (this.filterForm != null && this.filterForm.hasContent()) {
+
+ criteria = this.filterForm.getValuesAsCriteria();
+
+ if (this.initialCriteriaFixed) {
+ if (criteria != null) {
+ if (this.initialCriteria != null) {
+ // There is fixed criteria - add it to the filter form criteria.
+ addCriteria(criteria, this.initialCriteria);
+ }
+ } else {
+ criteria = this.initialCriteria;
+ }
+ }
+ } else if (this.initialCriteriaFixed) {
+
+ criteria = this.initialCriteria;
+ }
+
+ return criteria;
+ }
+
+ // SmartGWT 2.4's version of Criteria.addCriteria for some reason doesn't
have else clauses for the array types
+ // and it doesn't handle Object types properly (seeing odd behavior because of
this), so this method explicitly
+ // supports adding array types and Objects.
+ // This method takes the src criteria and adds it to the dest criteria.
+ private static void addCriteria(Criteria dest, Criteria src) {
+ Map otherMap = src.getValues();
+ Set otherKeys = otherMap.keySet();
+ for (Iterator i = otherKeys.iterator(); i.hasNext();) {
+ String field = (String) i.next();
+ Object value = otherMap.get(field);
+
+ if (value instanceof Integer) {
+ dest.addCriteria(field, (Integer) value);
+ } else if (value instanceof Float) {
+ dest.addCriteria(field, (Float) value);
+ } else if (value instanceof String) {
+ dest.addCriteria(field, (String) value);
+ } else if (value instanceof Date) {
+ dest.addCriteria(field, (Date) value);
+ } else if (value instanceof Boolean) {
+ dest.addCriteria(field, (Boolean) value);
+ } else if (value instanceof Integer[]) {
+ dest.addCriteria(field, (Integer[]) value);
+ } else if (value instanceof Double[]) {
+ dest.addCriteria(field, (Double[]) value);
+ } else if (value instanceof String[]) {
+ dest.addCriteria(field, (String[]) value);
+ } else {
+ // this is the magic piece - we need to get attrib as an object and set
that value
+ dest.setAttribute(field, src.getAttributeAsObject(field));
+ }
+ }
+ }
+
+ public void setCarouselDetails(Canvas carouselDetails) {
+ this.carouselDetails = carouselDetails;
+ }
+
+ public Canvas getCarouselDetails() {
+ return carouselDetails;
+ }
+
+ public void setTitleComponent(Canvas canvas) {
+ this.titleComponent = canvas;
+ }
+
+ /**
+ * Note: To prevent user action while a current action completes, all widgets on the
footer are disabled
+ * when footer actions take place, typically a button click. It is up to the action
to ensure the page
+ * (via refresh() or CoreGUI.refresh()) or footer (via refreshCarouselActions) are
refreshed as needed at action
+ * completion. Failure to do so may leave the widgets disabled.
+ */
+ public void addCarouselAction(String locatorId, String title, CarouselAction action)
{
+ this.addCarouselAction(locatorId, title, null, null, action);
+ }
+
+ /**
+ * Note: To prevent user action while a current action completes, all widgets on the
footer are disabled
+ * when footer actions take place, typically a button click. It is up to the action
to ensure the page
+ * (via refresh() or CoreGUI.refresh()) or footer (via refreshCarouselActions) are
refreshed as needed at action
+ * completion. Failure to do so may leave the widgets disabled.
+ */
+ public void addCarouselAction(String locatorId, String title, String confirmation,
CarouselAction action) {
+ this.addCarouselAction(locatorId, title, confirmation, null, action);
+ }
+
+ /**
+ * Note: To prevent user action while a current action completes, all widgets on the
footer are disabled
+ * when footer actions take place, typically a button click. It is up to the action
to ensure the page
+ * (via refresh() or CoreGUI.refresh()) or footer (via refreshCarouselActions) are
refreshed as needed at action
+ * completion. Failure to do so may leave the widgets disabled.
+ */
+ public void addCarouselAction(String locatorId, String title, String confirmation,
+ LinkedHashMap<String, ? extends Object> valueMap, CarouselAction action) {
+ // If the specified locator ID is qualified, strip off the ancestry prefix, so we
can make sure its locator ID
+ // extends the footer's locator ID as it should.
+ int underscoreIndex = locatorId.lastIndexOf('_');
+ String unqualifiedLocatorId;
+ if (underscoreIndex >= 0 && underscoreIndex != (locatorId.length() -
1)) {
+ unqualifiedLocatorId = locatorId.substring(underscoreIndex + 1);
+ } else {
+ unqualifiedLocatorId = locatorId;
+ }
+ CarouselActionInfo info = new
CarouselActionInfo(this.footer.extendLocatorId(unqualifiedLocatorId), title,
+ confirmation, valueMap, action);
+ carouselActions.add(info);
+ }
+
+ public void addCarouselMember(Canvas member) {
+ member.setWidth(carouselUsingFixedWidths ? getCarouselMemberFixedWidth() :
"*");
+ this.carouselHolder.addMember(member);
+ }
+
+ public void setListGridDoubleClickHandler(DoubleClickHandler handler) {
+ //doubleClickHandler = handler;
+ }
+
+ /**
+ * Adds extra widgets to the bottom of the carousel view.
+ * <br/><br/>
+ * Note: To prevent user action while a current action completes, all widgets on the
footer are disabled
+ * when footer actions take place, typically a button click. It is up to the action
to ensure the page
+ * (via refresh() or CoreGUI.refresh()) or footer (via refreshCarouselActions) are
refreshed as needed at action
+ * completion. Failure to do so may leave the widgets disabled.
+ *
+ * @param widget the new widget to add to the view
+ * @param aboveFooter if true, the widget will be placed in a second toolstrip just
above the main footer.
+ * if false, the widget will be placed in the main footer
toolstrip itself. This is
+ * useful if the widget is really big and won't fit in the
main footer along with the
+ * rest of the main footer members.
+ */
+ public void addExtraWidget(Canvas widget, boolean aboveFooter) {
+ if (aboveFooter) {
+ this.extraWidgetsAboveFooter.add(widget);
+ } else {
+ this.extraWidgetsInMainFooter.add(widget);
+ }
+ }
+
+ public void setHeaderIcon(String headerIcon) {
+ if (this.titleIcons.size() > 0) {
+ this.titleIcons.clear();
+ }
+ addHeaderIcon(headerIcon);
+ }
+
+ public void addHeaderIcon(String headerIcon) {
+ this.titleIcons.add(headerIcon);
+ }
+
+ /**
+ * By default, all actions have buttons that are enabled or
+ * disabled based on if and how many rows are selected. There are
+ * times when you don't want the user to be able to press action
+ * buttons regardless of which rows are selected. This method let's
+ * you set this override-disable flag.
+ *
+ * Note: this also effects the double-click handler - if this disable override
+ * is on, the double-click handler is not called.
+ *
+ * @param disabled if true, all action buttons will be disabled
+ * if false, action buttons will be enabled based on their
predefined
+ * selection enablement rule.
+ */
+ public void setCarouselActionDisableOverride(boolean disabled) {
+ this.carouselActionDisableOverride = disabled;
+ refreshCarouselInfo();
+ }
+
+ public boolean getCarouselActionDisableOverride() {
+ return this.carouselActionDisableOverride;
+ }
+
+ /**
+ * Refreshes the members, filtered by any fixed criteria, as well as any
user-specified filters.
+ */
+ public void refresh() {
+ Criteria criteria = getCurrentCriteria();
+
+ Map<String, Object> criteriaMap = (criteria != null) ? criteria.getValues()
: Collections
+ .<String, Object> emptyMap();
+ Integer carouselStart;
+ Integer carouselSize;
+ try {
+ carouselSize = Integer.valueOf((String)
criteriaMap.get(FILTER_CAROUSEL_SIZE));
+ } catch (Exception e) {
+ carouselSize = null;
+ }
+ try {
+ carouselStart = Integer.valueOf((String)
criteriaMap.get(FILTER_CAROUSEL_START));
+ } catch (Exception e) {
+ carouselStart = null;
+ }
+ if (carouselStartFilter != carouselStart) {
+ if (null == carouselStartFilter ||
!carouselStartFilter.equals(carouselStart)) {
+ carouselStartFilter = carouselStart;
+ carouselDirty = true;
+ }
+ }
+ if (carouselSizeFilter != carouselSize) {
+ if (null == carouselSizeFilter || !carouselSizeFilter.equals(carouselSize))
{
+ carouselSizeFilter = carouselSize;
+ carouselDirty = true;
+ }
+ }
+
+ // if we're channging the entire carousel then rebuild, otherwise, just
refresh the members
+ if (carouselDirty) {
+ buildCarousel(true);
+
+ } else {
+ for (Canvas member : carouselHolder.getMembers()) {
+ CarouselMember carouselMember = (CarouselMember) member;
+ carouselMember.refresh(criteria);
+ }
+ }
+
+ // TODO: it would be best if this was actually called after the async return of
the member refreshes
+ refreshCarouselInfo();
+ }
+
+ protected void buildCarousel(boolean isRefresh) {
+ if (null != carouselHolder) {
+ carouselHolder.destroyMembers();
+ }
+ }
+
+ public void refreshCarouselInfo() {
+ if (this.showFooter && (this.carouselHolder != null)) {
+ if (this.carouselActionDisableOverride) {
+ //this.listGrid.setSelectionType(SelectionStyle.NONE);
+ } else {
+ //this.listGrid.setSelectionType(getDefaultSelectionStyle());
+ }
+
+ //int selectionCount = this.listGrid.getSelection().length;
+ for (CarouselActionInfo carouselAction : this.carouselActions) {
+ if (carouselAction.actionCanvas != null) { // if null, we haven't
initialized our buttons yet, so skip this
+ boolean enabled = (!this.carouselActionDisableOverride &&
carouselAction.action.isEnabled());
+ carouselAction.actionCanvas.setDisabled(!enabled);
+ }
+ }
+ for (Canvas extraWidget : this.extraWidgetsAboveFooter) {
+ extraWidget.enable();
+ if (extraWidget instanceof CarouselWidget) {
+ ((CarouselWidget) extraWidget).refresh(carouselHolder.getMembers());
+ }
+ }
+ for (Canvas extraWidget : this.extraWidgetsInMainFooter) {
+ extraWidget.enable();
+ if (extraWidget instanceof CarouselWidget) {
+ ((CarouselWidget) extraWidget).refresh(carouselHolder.getMembers());
+ }
+ }
+ refreshRowCount();
+ if (isShowFooterRefresh() && this.refreshButton != null) {
+ this.refreshButton.enable();
+ }
+ }
+ }
+
+ protected String getDataTypeName() {
+ return "item";
+ }
+
+ protected String getDataTypeNamePlural() {
+ return "items";
+ }
+
+ protected String getDeleteConfirmMessage() {
+ return MSG.common_msg_deleteConfirm(getDataTypeNamePlural());
+ }
+
+ // -------------- Inner utility classes ------------- //
+
+ /**
+ * A subclass of SmartGWT's DynamicForm widget that provides a more convenient
interface for filtering a
+ * {@link Carousel} of data.
+ *
+ * @author Joseph Marques
+ */
+ private static class CarouselFilter extends LocatableDynamicForm implements
KeyPressHandler, ChangedHandler,
+ com.google.gwt.event.dom.client.KeyPressHandler {
+
+ private Carousel carousel;
+ private SearchBarItem searchBarItem;
+ private HiddenItem hiddenItem;
+
+ public CarouselFilter(Carousel carousel) {
+ super(carousel.extendLocatorId("CarouselFilter"));
+ setIsGroup(true);
+ setGroupTitle(MSG.common_label_filters());
+ setWidth100();
+ setPadding(5);
+ this.carousel = carousel;
+ }
+
+ @Override
+ public void setItems(FormItem... items) {
+ for (FormItem nextFormItem : items) {
+ nextFormItem.setWrapTitle(false);
+ nextFormItem.setWidth(300); // wider than default
+ if (nextFormItem instanceof TextItem) {
+ nextFormItem.addKeyPressHandler(this);
+ } else if (nextFormItem instanceof SelectItem) {
+ nextFormItem.addChangedHandler(this);
+ } else if (nextFormItem instanceof SearchBarItem) {
+ searchBarItem = (SearchBarItem) nextFormItem;
+ searchBarItem.getSearchBar().addKeyPressHandler(this);
+ String name = searchBarItem.getName();
+ searchBarItem.setName(name + "_hidden");
+ hiddenItem = new HiddenItem(name);
+ hiddenItem.setValue(searchBarItem.getSearchBar().getValue());
+ }
+ }
+
+ if (hiddenItem != null) {
+ FormItem[] tmpItems = new FormItem[items.length + 1];
+ System.arraycopy(items, 0, tmpItems, 0, items.length);
+ tmpItems[items.length] = hiddenItem;
+ items = tmpItems;
+ }
+
+ super.setItems(items);
+ }
+
+ private void fetchFilteredCarouselData() {
+ carousel.refresh();
+ }
+
+ public void onKeyPress(KeyPressEvent event) {
+ if (event.getKeyName().equals("Enter") == false) {
+ return;
+ }
+ fetchFilteredCarouselData();
+ }
+
+ public void onChanged(ChangedEvent event) {
+ fetchFilteredCarouselData();
+ }
+
+ public boolean hasContent() {
+ return super.getFields().length != 0;
+ }
+
+ @Override
+ public void onKeyPress(com.google.gwt.event.dom.client.KeyPressEvent event) {
+ if (event.getCharCode() != KeyCodes.KEY_ENTER) {
+ return;
+ }
+ // TODO: figure out why this event is being sent twice
+ hiddenItem.setValue(searchBarItem.getSearchBar().getValue());
+ fetchFilteredCarouselData();
+ }
+ }
+
+ public static class CarouselActionInfo {
+ private String locatorId;
+ private String title;
+ private String confirmMessage;
+ private LinkedHashMap<String, ? extends Object> valueMap;
+ private CarouselAction action;
+ private Canvas actionCanvas;
+
+ protected CarouselActionInfo(String locatorId, String title, String
confirmMessage,
+ LinkedHashMap<String, ? extends Object> valueMap, CarouselAction
action) {
+ this.locatorId = locatorId;
+ this.title = title;
+ this.confirmMessage = confirmMessage;
+ this.valueMap = valueMap;
+ this.action = action;
+ }
+
+ public String getLocatorId() {
+ return locatorId;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getConfirmMessage() {
+ return confirmMessage;
+ }
+
+ public LinkedHashMap<String, ? extends Object> getValueMap() {
+ return valueMap;
+ }
+
+ public Canvas getActionCanvas() {
+ return actionCanvas;
+ }
+
+ public void setActionCanvas(Canvas actionCanvas) {
+ this.actionCanvas = actionCanvas;
+ }
+
+ public CarouselAction getAction() {
+ return action;
+ }
+
+ public void setAction(CarouselAction action) {
+ this.action = action;
+ }
+
+ }
+
+ public boolean isShowFooterRefresh() {
+ return showFooterRefresh;
+ }
+
+ public void setShowFooterRefresh(boolean showFooterRefresh) {
+ this.showFooterRefresh = showFooterRefresh;
+ }
+
+ public Label getCarouselInfo() {
+ return carouselInfo;
+ }
+
+ public void setCarouselInfo(Label carouselInfo) {
+ this.carouselInfo = carouselInfo;
+ }
+
+ public boolean isShowFilterForm() {
+ return showFilterForm;
+ }
+
+ public void setShowFilterForm(boolean showFilterForm) {
+ this.showFilterForm = showFilterForm;
+ }
+
+ /*
+ * by default, no search bar is shown above this. if this represents a subsystem
that is capable
+ * of search, return the specific object here.
+ */
+ protected SearchSubsystem getSearchSubsystem() {
+ return null;
+ }
+
+ protected Integer getCarouselStartFilter() {
+ return carouselStartFilter;
+ }
+
+ protected void setCarouselStartFilter(Integer carouselStartFilter) {
+ this.carouselStartFilter = carouselStartFilter;
+ this.filterForm.getItem(FILTER_CAROUSEL_START).setValue(carouselStartFilter);
+ this.filterForm.getItem(FILTER_CAROUSEL_START).redraw();
+ }
+
+ protected Integer getCarouselSizeFilter() {
+ return carouselSizeFilter;
+ }
+
+ protected void setCarouselSizeFilter(Integer carouselSizeFilter) {
+ this.carouselSizeFilter = carouselSizeFilter;
+ this.filterForm.getItem(FILTER_CAROUSEL_SIZE).setValue(carouselSizeFilter);
+ this.filterForm.getItem(FILTER_CAROUSEL_SIZE).redraw();
+ }
+
+ protected boolean isCarouselDirty() {
+ return carouselDirty;
+ }
+
+ protected void setCarouselDirty(boolean carouselDirty) {
+ this.carouselDirty = carouselDirty;
+ }
+
+ protected boolean isCarouselUsingFixedWidths() {
+ return carouselUsingFixedWidths;
+ }
+
+ protected void setCarouselUsingFixedWidths(boolean carouselUsingFixedWidths) {
+ this.carouselUsingFixedWidths = carouselUsingFixedWidths;
+ }
+
+ private interface CarouselAction {
+
+ /**
+ * Returns true if the action should be enabled based on the currently selected
record(s).
+ *
+ * @param selection the currently selected record(s)
+ *
+ * @return true if the action should be enabled based on the currently selected
record(s)
+ */
+ boolean isEnabled(); //TODO add arg
+
+ /**
+ * Execute the action with the currently selected record(s) as the target(s).
+ *
+ * @param selection the currently selected record(s)
+ * @param actionValue a value optionally supplied by the action (for example, a
menuItem action's selection)
+ */
+ void executeAction(Object actionValue); //TODO add arg
+ }
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselMember.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselMember.java
new file mode 100644
index 0000000..5d6e8b8
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselMember.java
@@ -0,0 +1,35 @@
+/*
+ * 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.gui.coregui.client.components.carousel;
+
+import com.smartgwt.client.data.Criteria;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public interface CarouselMember {
+
+ /**
+ * Refresh the carousel member using, if applicable, the current criteria set for the
Carousel.
+ *
+ * @param criteria
+ */
+ void refresh(Criteria criteria);
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselWidget.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselWidget.java
new file mode 100644
index 0000000..48f650f
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/carousel/CarouselWidget.java
@@ -0,0 +1,28 @@
+/*
+ * 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.gui.coregui.client.components.carousel;
+
+import com.smartgwt.client.widgets.Canvas;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public interface CarouselWidget {
+ void refresh(Canvas[] carouselMembers);
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
index 60e52ee..c7ed1de 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
@@ -108,7 +108,7 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
private LocatableVLayout contents;
- private HTMLFlow title;
+ private HTMLFlow titleCanvas;
private HLayout titleLayout;
private Canvas titleComponent;
@@ -124,7 +124,7 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
private boolean showFooterRefresh = true;
private boolean showFilterForm = true;
- private String tableTitle;
+ private String titleString;
private Criteria initialCriteria;
private boolean initialCriteriaFixed = true;
private SortSpecifier[] sortSpecifiers;
@@ -186,7 +186,7 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
setHeight100();
setOverflow(Overflow.HIDDEN);
- this.tableTitle = tableTitle;
+ this.titleString = tableTitle;
this.initialCriteria = criteria;
this.sortSpecifiers = sortSpecifiers;
this.excludedFieldNames = excludedFieldNames;
@@ -296,8 +296,8 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
}
// Title
- this.title = new HTMLFlow();
- setTableTitle(this.tableTitle);
+ this.titleCanvas = new HTMLFlow();
+ updateTitleCanvas(this.titleString);
if (showHeader) {
titleLayout = new
LocatableHLayout(contents.extendLocatorId("Title"));
@@ -413,7 +413,7 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
titleLayout.addMember(img);
}
- titleLayout.addMember(title);
+ titleLayout.addMember(titleCanvas);
if (titleComponent != null) {
titleLayout.addMember(new LayoutSpacer());
@@ -568,17 +568,51 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
}
- public String getTitle() {
- return this.tableTitle;
+ public String getTitleString() {
+ return this.titleString;
}
- public void setTitle(String title) {
- this.tableTitle = title;
- if (this.title != null) {
- setTableTitle(title);
+ /**
+ * Set the Table's title string. This will subsequently call {@link
#updateTitleCanvas(String)}.
+ * @param titleString
+ */
+ public void setTitleString(String titleString) {
+ this.titleString = titleString;
+ if (this.titleCanvas != null) {
+ updateTitleCanvas(titleString);
}
}
+ public Canvas getTitleCanvas() {
+ return this.titleCanvas;
+ }
+
+ /**
+ * To set the Table's title, call {@link #setTitleString(String)}. This is
primarily declared for purposes of
+ * override.
+ * @param titleString
+ */
+ public void updateTitleCanvas(String titleString) {
+ if (titleString == null) {
+ titleString = "";
+ }
+ if (titleString.length() > 0) {
+ titleCanvas.setWidth100();
+ titleCanvas.setHeight(35);
+ titleCanvas.setContents(titleString);
+ titleCanvas.setPadding(4);
+ titleCanvas.setStyleName("HeaderLabel");
+ } else {
+ titleCanvas.setWidth100();
+ titleCanvas.setHeight(0);
+ titleCanvas.setContents(null);
+ titleCanvas.setPadding(0);
+ titleCanvas.setStyleName("normal");
+ }
+
+ titleCanvas.markForRedraw();
+ }
+
/**
* Returns the encompassing canvas that contains all content for this table
component.
* This content includes the list grid, the buttons, etc.
@@ -615,6 +649,18 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
}
}
+ protected Criteria getInitialCriteria() {
+ return initialCriteria;
+ }
+
+ /**
+ * Can be called in constructor to reset initialCriteria.
+ * @param initialCriteria
+ */
+ protected void setInitialCriteria(Criteria initialCriteria) {
+ this.initialCriteria = initialCriteria;
+ }
+
protected boolean isInitialCriteriaFixed() {
return initialCriteriaFixed;
}
@@ -693,27 +739,6 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
}
}
- public void setTableTitle(String titleString) {
- if (titleString == null) {
- titleString = "";
- }
- if (titleString.length() > 0) {
- title.setWidth100();
- title.setHeight(35);
- title.setContents(titleString);
- title.setPadding(4);
- title.setStyleName("HeaderLabel");
- } else {
- title.setWidth100();
- title.setHeight(0);
- title.setContents(null);
- title.setPadding(0);
- title.setStyleName("normal");
- }
-
- title.markForRedraw();
- }
-
public DS getDataSource() {
return dataSource;
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeDataSource.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeDataSource.java
index e8fb327..6935d42 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeDataSource.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeDataSource.java
@@ -36,7 +36,7 @@ import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.util.PageList;
import org.rhq.core.domain.util.PageOrdering;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
@@ -194,9 +194,9 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends
RPCDataSourc
@Override
public ListGridRecord copyValues(Object from) {
TreeNode node;
- if (from instanceof DriftConfiguration) {
- DriftConfiguration driftConfig = (DriftConfiguration) from;
- node = new
AbstractDriftChangeSetsTreeView.DriftConfigurationTreeNode(driftConfig);
+ if (from instanceof DriftDefinition) {
+ DriftDefinition driftConfig = (DriftDefinition) from;
+ node = new
AbstractDriftChangeSetsTreeView.DriftDefinitionTreeNode(driftConfig);
} else if (from instanceof DriftChangeSet) {
DriftChangeSet changeset = (DriftChangeSet) from;
node = new AbstractDriftChangeSetsTreeView.ChangeSetTreeNode(changeset);
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
index fb63830..329d331 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java
@@ -43,7 +43,7 @@ import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.ImageManager;
@@ -102,8 +102,8 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
TreeNode eventNode = event.getNode();
Menu menu = null;
- if (eventNode instanceof DriftConfigurationTreeNode) {
- menu =
buildDriftConfigurationTreeNodeContextMenu((DriftConfigurationTreeNode) eventNode);
+ if (eventNode instanceof DriftDefinitionTreeNode) {
+ menu =
buildDriftConfigurationTreeNodeContextMenu((DriftDefinitionTreeNode) eventNode);
} else if (eventNode instanceof ChangeSetTreeNode) {
menu = buildChangeSetTreeNodeContextMenu((ChangeSetTreeNode)
eventNode);
} else if (eventNode instanceof DriftTreeNode) {
@@ -182,21 +182,21 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
*
* @param doomedDriftConfig the drift config to remove
*/
- protected abstract void deleteDriftConfiguration(DriftConfiguration
doomedDriftConfig);
+ protected abstract void deleteDriftDefinition(DriftDefinition doomedDriftConfig);
/**
* Immediately asks for a drift detection scan to be run.
*
* @param driftConfiguration identifies the drift whose detection scan should be
initiated.
*/
- protected abstract void detectDrift(DriftConfiguration driftConfiguration);
+ protected abstract void detectDrift(DriftDefinition driftConfiguration);
/**
* Builds the right-mouse-click context menu for the given drift configuration node
* @param node the drift configuration node whose menu is to be displayed
* @return the context menu to display
*/
- protected Menu buildDriftConfigurationTreeNodeContextMenu(final
DriftConfigurationTreeNode node) {
+ protected Menu buildDriftConfigurationTreeNodeContextMenu(final
DriftDefinitionTreeNode node) {
Menu contextMenu = new Menu();
@@ -218,8 +218,8 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
deleteItem.setIcon(Window.getImgURL(ImageManager.getRemoveIcon()));
deleteItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
- DriftConfiguration driftConfig = node.getDriftConfiguration();
- deleteDriftConfiguration(driftConfig);
+ DriftDefinition driftConfig = node.getDriftConfiguration();
+ deleteDriftDefinition(driftConfig);
}
});
contextMenu.addItem(deleteItem);
@@ -228,7 +228,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
MenuItem detectNowItem = new MenuItem(MSG.view_drift_button_detectNow());
detectNowItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
- DriftConfiguration driftConfig = node.getDriftConfiguration();
+ DriftDefinition driftConfig = node.getDriftConfiguration();
detectDrift(driftConfig);
}
});
@@ -323,10 +323,10 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
return ((TreeNode) node).getTitle();
}
- static class DriftConfigurationTreeNode extends TreeNode {
+ static class DriftDefinitionTreeNode extends TreeNode {
public static final String ATTR_DRIFT_CONFIG_OBJECT = "object";
- public DriftConfigurationTreeNode(DriftConfiguration driftConfig) {
+ public DriftDefinitionTreeNode(DriftDefinition driftConfig) {
setIsFolder(true);
if (driftConfig.isEnabled()) {
setIcon("subsystems/drift/DriftConfig_Folder_16.png");
@@ -339,13 +339,13 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
setAttribute(ATTR_DRIFT_CONFIG_OBJECT, driftConfig);
}
- public int getDriftConfigurationId() {
+ public int getDriftDefinitionId() {
String idAttrib = getAttribute("id");
return Integer.parseInt(idAttrib);
}
- public DriftConfiguration getDriftConfiguration() {
- return (DriftConfiguration) getAttributeAsObject(ATTR_DRIFT_CONFIG_OBJECT);
+ public DriftDefinition getDriftConfiguration() {
+ return (DriftDefinition) getAttributeAsObject(ATTR_DRIFT_CONFIG_OBJECT);
}
@Override
@@ -353,7 +353,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
return super.getName();
}
- private String buildNodeName(DriftConfiguration driftConfig) {
+ private String buildNodeName(DriftDefinition driftConfig) {
return driftConfig.getName();
}
}
@@ -362,7 +362,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
public ChangeSetTreeNode(DriftChangeSet<?> changeset) {
setIsFolder(true);
setShowOpenIcon(true);
- String parentID = String.valueOf(changeset.getDriftConfigurationId());
+ String parentID = String.valueOf(changeset.getDriftDefinitionId());
setParentID(parentID);
setID(parentID + "_" + changeset.getId());
setName(padWithZeroes(changeset.getVersion())); // we sort on this column,
hence we make sure the version # is padded
@@ -405,7 +405,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends
LocatableTreeGrid
setIsFolder(false);
setIcon(ImageManager.getDriftCategoryIcon(drift.getCategory()));
DriftChangeSet<?> changeset = drift.getChangeSet();
- setParentID(String.valueOf(changeset.getDriftConfigurationId()) +
"_" + changeset.getId());
+ setParentID(String.valueOf(changeset.getDriftDefinitionId()) + "_"
+ changeset.getId());
setID('D' + drift.getId()); // prefix with a 'D' so it
doesn't conflict with driftConfig node IDs
setName(drift.getPath()); // we sort on this column
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselMemberView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselMemberView.java
new file mode 100644
index 0000000..2276dd9
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselMemberView.java
@@ -0,0 +1,189 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, 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.gui.coregui.client.drift;
+
+import java.util.ArrayList;
+import java.util.Date;
+
+import com.smartgwt.client.data.Criteria;
+import com.smartgwt.client.data.DSRequest;
+import com.smartgwt.client.types.Alignment;
+import com.smartgwt.client.types.ListGridFieldType;
+import com.smartgwt.client.widgets.Canvas;
+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.common.EntityContext;
+import org.rhq.core.domain.criteria.GenericDriftCriteria;
+import org.rhq.core.domain.drift.DriftChangeSet;
+import org.rhq.core.domain.resource.composite.ResourceComposite;
+import org.rhq.enterprise.gui.coregui.client.components.carousel.CarouselMember;
+import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter;
+
+/**
+ * @author Jay Shaughnessy
+ */
+@SuppressWarnings("unchecked")
+public class DriftCarouselMemberView extends DriftHistoryView implements CarouselMember
{
+
+ private DriftChangeSet changeSet;
+ private Criteria carouselCriteria;
+
+ public static DriftCarouselMemberView get(String locatorId, ResourceComposite
composite,
+ DriftChangeSet driftChangeSet) {
+ //String tableTitle = MSG.view_drift_table_resourceHistory();
+ EntityContext context =
EntityContext.forResource(composite.getResource().getId());
+ boolean hasWriteAccess = composite.getResourcePermission().isDrift();
+ return new DriftCarouselMemberView(locatorId, context, driftChangeSet,
hasWriteAccess);
+ }
+
+ public DriftCarouselMemberView(String locatorId, EntityContext context,
DriftChangeSet driftChangeSet,
+ boolean hasWriteAccess) {
+
+ super(locatorId, null, context, hasWriteAccess);
+
+ this.changeSet = driftChangeSet;
+ ((DriftCarouselDataSource)
getDataSource()).setChangeSetId(this.changeSet.getId());
+
+ // no need to refresh the drift instances, they are fixed.
+ setShowFooterRefresh(false);
+
+ //setWidth("500px");
+ }
+
+ @Override
+ public DriftDataSource getDataSource() {
+ if (null == dataSource) {
+ dataSource = new DriftCarouselDataSource(getContext());
+ }
+
+ return dataSource;
+ }
+
+ @Override
+ protected void configureTableFilters() {
+ // filter settings come from the Carousel view and are applied to all Drift
views
+ }
+
+ @Override
+ protected Criteria getCurrentCriteria() {
+ return carouselCriteria;
+ }
+
+ @Override
+ public void refresh(Criteria carouselCriteria) {
+ this.carouselCriteria = carouselCriteria;
+ super.refresh();
+ }
+
+ public void updateTitleCanvas(String titleString) {
+ StringBuilder sb = new StringBuilder("<span
class=\"HeaderLabel\">");
+ sb.append(MSG.view_drift_table_snapshot());
+ sb.append(" ");
+ sb.append(changeSet.getVersion());
+ sb.append("</span><br/>");
+ sb.append(TimestampCellFormatter.DATE_TIME_FORMAT_MEDIUM.format(new
Date(this.changeSet.getCtime())));
+
+ Canvas titleCanvas = getTitleCanvas();
+ titleCanvas.setWidth100();
+ titleCanvas.setHeight(35);
+ titleCanvas.setContents(sb.toString());
+ titleCanvas.setPadding(4);
+
+ titleCanvas.markForRedraw();
+ }
+
+ public static class DriftCarouselDataSource extends DriftDataSource {
+
+ private String changeSetId;
+
+ /**
+ * Note, the changeSetId must be set prior to any fetches.
+ * @param context
+ */
+ DriftCarouselDataSource(EntityContext context) {
+ super(context);
+ }
+
+ protected String getChangeSetId() {
+ return changeSetId;
+ }
+
+ protected void setChangeSetId(String changeSetId) {
+ this.changeSetId = changeSetId;
+ }
+
+ @Override
+ protected GenericDriftCriteria getFetchCriteria(DSRequest request) {
+ GenericDriftCriteria criteria = super.getFetchCriteria(request);
+
+ if (null == criteria) {
+ criteria = new GenericDriftCriteria();
+ }
+
+ criteria.addFilterChangeSetId(changeSetId);
+ return criteria;
+ }
+
+ /**
+ * The view that contains the list grid which will display this datasource's
data will call this
+ * method to get the field information which is used to control the display of
the data.
+ *
+ * @return list grid fields used to display the datasource data
+ */
+ @Override
+ public ArrayList<ListGridField> getListGridFields() {
+ ArrayList<ListGridField> fields = new
ArrayList<ListGridField>(7);
+
+ ListGridField categoryField = new ListGridField(ATTR_CATEGORY,
MSG.common_title_category());
+ categoryField.setType(ListGridFieldType.IMAGE);
+ categoryField.setAlign(Alignment.CENTER);
+ categoryField.setShowHover(true);
+ categoryField.setHoverCustomizer(new HoverCustomizer() {
+ @Override
+ public String hoverHTML(Object value, ListGridRecord record, int rowNum,
int colNum) {
+ String cat = record.getAttribute(ATTR_CATEGORY);
+ if (CATEGORY_ICON_ADD.equals(cat)) {
+ return MSG.view_drift_category_fileAdded();
+ } else if (CATEGORY_ICON_CHANGE.equals(cat)) {
+ return MSG.view_drift_category_fileChanged();
+ } else if (CATEGORY_ICON_REMOVE.equals(cat)) {
+ return MSG.view_drift_category_fileRemoved();
+ } else if (CATEGORY_ICON_NEW.equals(cat)) {
+ return MSG.view_drift_category_fileNew();
+ } else {
+ return ""; // will never get here
+ }
+ }
+ });
+ fields.add(categoryField);
+
+ ListGridField pathField = new ListGridField(ATTR_PATH,
MSG.common_title_path());
+ fields.add(pathField);
+
+ categoryField.setWidth(80);
+ pathField.setWidth("*");
+
+ return fields;
+ }
+ }
+
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
new file mode 100644
index 0000000..e653144
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftCarouselView.java
@@ -0,0 +1,201 @@
+/*
+ * 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.gui.coregui.client.drift;
+
+import java.util.LinkedHashMap;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+import com.smartgwt.client.widgets.form.fields.SelectItem;
+import com.smartgwt.client.widgets.form.fields.TextItem;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
+import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
+import org.rhq.core.domain.drift.DriftCategory;
+import org.rhq.core.domain.drift.DriftChangeSet;
+import org.rhq.core.domain.drift.DriftDefinition;
+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.ImageManager;
+import org.rhq.enterprise.gui.coregui.client.components.carousel.Carousel;
+import org.rhq.enterprise.gui.coregui.client.components.form.EnumSelectItem;
+import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTServiceAsync;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public class DriftCarouselView extends Carousel {
+
+ private static final int CAROUSEL_DEFAULT_SIZE = 4;
+ private static final String CAROUSEL_MEMBER_FIXED_WIDTH = "250px";
+
+ private int driftDefId;
+ private EntityContext context;
+ private boolean hasWriteAccess;
+
+ private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService();
+
+ public DriftCarouselView(String locatorId, EntityContext entityContext, int
driftDefId, boolean hasWriteAccess) {
+ super(locatorId);
+
+ this.context = entityContext;
+ this.driftDefId = driftDefId;
+ this.hasWriteAccess = hasWriteAccess;
+ }
+
+ @Override
+ protected void onDraw() {
+
+ DriftDefinitionCriteria defCriteria = new DriftDefinitionCriteria();
+ defCriteria.addFilterId(driftDefId);
+ defCriteria.fetchConfiguration(true);
+
+ driftService.findDriftDefinitionsByCriteria(defCriteria, new
AsyncCallback<PageList<DriftDefinition>>() {
+ public void onFailure(Throwable caught) {
+ CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_load(),
caught);
+ }
+
+ public void onSuccess(PageList<DriftDefinition> result) {
+ // Create and add the details canvas for the def
+ addTitleString(result.get(0));
+
+ buildCarousel(false);
+ }
+ });
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected void buildCarousel(final boolean isRefresh) {
+ super.buildCarousel(isRefresh);
+
+ // Fetch the ChangeSet headers
+ GenericDriftChangeSetCriteria changeSetCriteria = new
GenericDriftChangeSetCriteria();
+ changeSetCriteria.addFilterDriftDefinitionId(driftDefId);
+ setChangeSetVersionCriteria(changeSetCriteria);
+
+ changeSetCriteria.addSortVersion(PageOrdering.DESC);
+
+ driftService.findDriftChangeSetsByCriteria(changeSetCriteria,
+ new AsyncCallback<PageList<? extends DriftChangeSet>>() {
+
+ public void onSuccess(PageList<? extends DriftChangeSet> result) {
+
+ Integer carouselSize = getCarouselSizeFilter();
+ carouselSize = (null == carouselSize || carouselSize < 1) ?
CAROUSEL_DEFAULT_SIZE : carouselSize;
+ int size = carouselSize;
+ Integer carouselStart = null;
+
+ for (DriftChangeSet changeSet : result) {
+ DriftCarouselMemberView view = new
DriftCarouselMemberView(extendLocatorId(changeSet
+ .getId()), context, changeSet, hasWriteAccess);
+ addCarouselMember(view);
+
+ if (null == carouselStart) {
+ carouselStart = changeSet.getVersion();
+ }
+
+ if (--size == 0) {
+ break;
+ }
+ }
+
+ if (!isRefresh) {
+ DriftCarouselView.super.onDraw();
+ }
+
+ setCarouselStartFilter(carouselStart);
+ setCarouselSizeFilter(carouselSize);
+ setCarouselDirty(false);
+ }
+
+ public void onFailure(Throwable caught) {
+
CoreGUI.getErrorHandler().handleError(MSG.view_drift_snapshots_tree_loadFailure(),
caught);
+ }
+ });
+ }
+
+ @Override
+ protected int getDefaultCarouselSize() {
+ return CAROUSEL_DEFAULT_SIZE;
+ }
+
+ @Override
+ protected String getCarouselMemberFixedWidth() {
+ return CAROUSEL_MEMBER_FIXED_WIDTH;
+ }
+
+ private void setChangeSetVersionCriteria(GenericDriftChangeSetCriteria
changeSetCriteria) {
+ Integer carouselStart;
+
+ try {
+ carouselStart = Integer.valueOf(getCarouselStartFilter());
+ } catch (Exception e) {
+ carouselStart = null;
+ }
+
+ if (null != carouselStart) {
+ changeSetCriteria.addFilterEndVersion(String.valueOf(carouselStart));
+ }
+ changeSetCriteria.addFilterStartVersion("1");
+ }
+
+ private void addTitleString(DriftDefinition driftDef) {
+
+ setTitleString(driftDef.getName());
+ }
+
+ @Override
+ protected void configureCarouselFilters() {
+ // drift category filter
+ LinkedHashMap<String, String> categories = new LinkedHashMap<String,
String>(3);
+ categories.put(DriftCategory.FILE_ADDED.name(),
MSG.view_drift_category_fileAdded());
+ categories.put(DriftCategory.FILE_CHANGED.name(),
MSG.view_drift_category_fileChanged());
+ categories.put(DriftCategory.FILE_REMOVED.name(),
MSG.view_drift_category_fileRemoved());
+ LinkedHashMap<String, String> categoryIcons = new LinkedHashMap<String,
String>(3);
+ categoryIcons.put(DriftCategory.FILE_ADDED.name(),
ImageManager.getDriftCategoryIcon(DriftCategory.FILE_ADDED));
+ categoryIcons.put(DriftCategory.FILE_CHANGED.name(), ImageManager
+ .getDriftCategoryIcon(DriftCategory.FILE_CHANGED));
+ categoryIcons.put(DriftCategory.FILE_REMOVED.name(), ImageManager
+ .getDriftCategoryIcon(DriftCategory.FILE_REMOVED));
+ SelectItem categoryFilter = new EnumSelectItem(DriftDataSource.FILTER_CATEGORIES,
MSG.common_title_category(),
+ DriftCategory.class, categories, categoryIcons);
+
+ // drift file path filter
+ TextItem pathFilter = new TextItem(DriftDataSource.FILTER_PATH,
MSG.common_title_path());
+ pathFilter.setEndRow(true);
+
+ if (isShowFilterForm()) {
+ setFilterFormItems(categoryFilter, pathFilter);
+ }
+ }
+
+ @Override
+ protected String getCarouselStartFilterLabel() {
+ return MSG.view_drift_carousel_startFilterLabel();
+ }
+
+ @Override
+ protected String getCarouselSizeFilterLabel() {
+ return MSG.view_drift_carousel_sizeFilterLabel();
+ }
+
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationDataSource.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationDataSource.java
deleted file mode 100644
index 189f398..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationDataSource.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-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.Record;
-import com.smartgwt.client.rpc.RPCResponse;
-import com.smartgwt.client.types.Alignment;
-import com.smartgwt.client.types.ListGridFieldType;
-import com.smartgwt.client.widgets.grid.CellFormatter;
-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.common.EntityContext;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
-import org.rhq.core.domain.util.PageList;
-import org.rhq.enterprise.gui.coregui.client.CoreGUI;
-import org.rhq.enterprise.gui.coregui.client.ImageManager;
-import org.rhq.enterprise.gui.coregui.client.LinkManager;
-import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTServiceAsync;
-import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
-import org.rhq.enterprise.gui.coregui.client.inventory.resource.AncestryUtil;
-import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
-
-/**
- * @author Jay Shaughnessy
- * @author John Mazzitelli
- */
-public class DriftConfigurationDataSource extends RPCDataSource<DriftConfiguration,
DriftConfigurationCriteria> {
-
- public static final String ATTR_ENTITY = "object";
- public static final String ATTR_ID = "id";
- public static final String ATTR_NAME = "name";
- public static final String ATTR_INTERVAL = "interval";
- public static final String ATTR_DRIFT_HANDLING_MODE = "driftHandlingMode";
- public static final String ATTR_BASE_DIR_STRING = "baseDirString";
- public static final String ATTR_ENABLED = "enabled";
-
- public static final String DRIFT_HANDLING_MODE_NORMAL =
MSG.view_drift_table_driftHandlingMode_normal();
- public static final String DRIFT_HANDLING_MODE_PLANNED =
MSG.view_drift_table_driftHandlingMode_plannedChanges();
-
- private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService();
- private EntityContext entityContext;
-
- public DriftConfigurationDataSource() {
- this(EntityContext.forSubsystemView());
- }
-
- public DriftConfigurationDataSource(EntityContext context) {
- this.entityContext = context;
- addDataSourceFields();
- }
-
- /**
- * The view that contains the list grid which will display this datasource's data
will call this
- * method to get the field information which is used to control the display of the
data.
- *
- * @return list grid fields used to display the datasource data
- */
- public ArrayList<ListGridField> getListGridFields() {
- ArrayList<ListGridField> fields = new ArrayList<ListGridField>(6);
-
- ListGridField nameField = new ListGridField(ATTR_NAME, MSG.common_title_name());
- fields.add(nameField);
-
- ListGridField enabledField = new ListGridField(ATTR_ENABLED,
MSG.common_title_enabled());
- enabledField.setType(ListGridFieldType.IMAGE);
- enabledField.setAlign(Alignment.CENTER);
- fields.add(enabledField);
-
- ListGridField driftHandlingModeField = new
ListGridField(ATTR_DRIFT_HANDLING_MODE, MSG
- .view_drift_table_driftHandlingMode());
- fields.add(driftHandlingModeField);
-
- ListGridField intervalField = new ListGridField(ATTR_INTERVAL,
MSG.common_title_interval());
- fields.add(intervalField);
-
- ListGridField baseDirField = new ListGridField(ATTR_BASE_DIR_STRING,
MSG.view_drift_table_baseDir());
- // can't sort on this because it's not an entity field, it's derived
from the config only
- baseDirField.setCanSort(false);
- fields.add(baseDirField);
-
- if (this.entityContext.type != EntityContext.Type.Resource) {
- ListGridField resourceNameField = new
ListGridField(AncestryUtil.RESOURCE_NAME, MSG.common_title_resource());
- resourceNameField.setCellFormatter(new CellFormatter() {
- public String format(Object o, ListGridRecord listGridRecord, int i, int
i1) {
- Integer resourceId =
listGridRecord.getAttributeAsInt(AncestryUtil.RESOURCE_ID);
- String url = LinkManager.getResourceLink(resourceId);
- return SeleniumUtility.getLocatableHref(url, o.toString(), null);
- }
- });
- resourceNameField.setShowHover(true);
- resourceNameField.setHoverCustomizer(new HoverCustomizer() {
- public String hoverHTML(Object value, ListGridRecord listGridRecord, int
rowNum, int colNum) {
- return AncestryUtil.getResourceHoverHTML(listGridRecord, 0);
- }
- });
- fields.add(resourceNameField);
-
- ListGridField ancestryField = AncestryUtil.setupAncestryListGridField();
- fields.add(ancestryField);
-
- nameField.setWidth("20%");
- enabledField.setWidth(60);
- driftHandlingModeField.setWidth("10%");
- intervalField.setWidth(100);
- baseDirField.setWidth("*");
- resourceNameField.setWidth("20%");
- ancestryField.setWidth("40%");
- } else {
- nameField.setWidth("20%");
- enabledField.setWidth(60);
- driftHandlingModeField.setWidth("10%");
- intervalField.setWidth(100);
- baseDirField.setWidth("*");
- }
-
- return fields;
- }
-
- @Override
- protected void executeFetch(final DSRequest request, final DSResponse response,
- final DriftConfigurationCriteria criteria) {
- this.driftService.findDriftConfigurationsByCriteria(criteria,
- new AsyncCallback<PageList<DriftConfiguration>>() {
- public void onFailure(Throwable caught) {
- CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_load(),
caught);
- response.setStatus(RPCResponse.STATUS_FAILURE);
- processResponse(request.getRequestId(), response);
- }
-
- public void onSuccess(PageList<DriftConfiguration> result) {
- dataRetrieved(result, response, request);
- }
- });
- }
-
- /**
- * Additional processing to support entity-specific or cross-resource views, and
something that can be overidden.
- */
- protected void dataRetrieved(final PageList<DriftConfiguration> result, final
DSResponse response,
- final DSRequest request) {
- switch (entityContext.type) {
-
- // no need to disambiguate, the drift configs are for a single resource
- case Resource:
- response.setData(buildRecords(result));
- // for paging to work we have to specify size of full result set
- response.setTotalRows(getTotalRows(result, response, request));
- processResponse(request.getRequestId(), response);
- break;
-
- case ResourceGroup:
- //TODO
-
- default:
- throw new IllegalArgumentException("Unsupported Context Type: " +
entityContext);
- }
- }
-
- /**
- * Sub-classes can override this to add fine-grained control over the result set
size. By default the
- * total rows are set to the total result set for the query, allowing proper paging.
But some views (portlets)
- * may want to limit results to a small set (like most recent).
- * @param result
- * @param response
- * @param request
- *
- * @return should not exceed result.size().
- */
- protected int getTotalRows(final Collection<DriftConfiguration> result, final
DSResponse response,
- final DSRequest request) {
- return result.size();
- }
-
- @Override
- protected DriftConfigurationCriteria getFetchCriteria(DSRequest request) {
-
- DriftConfigurationCriteria criteria = new DriftConfigurationCriteria();
- switch (entityContext.getType()) {
- case Resource:
- criteria.addFilterResourceIds(entityContext.getResourceId());
- break;
-
- case ResourceGroup:
- //TODO
-
- default:
- // no filter
- }
-
- criteria.fetchConfiguration(true);
- criteria.setPageControl(getPageControl(request));
-
- return criteria;
- }
-
- /*
- @Override
- protected String getSortFieldForColumn(String columnName) {
- if (AncestryUtil.RESOURCE_ANCESTRY.equals(columnName)) {
- return "ancestry";
- }
-
- return super.getSortFieldForColumn(columnName);
- }
- */
-
- @Override
- public DriftConfiguration copyValues(Record from) {
- return (DriftConfiguration) from.getAttributeAsObject(ATTR_ENTITY);
- }
-
- @Override
- public ListGridRecord copyValues(DriftConfiguration from) {
- return convert(from);
- }
-
- public static ListGridRecord convert(DriftConfiguration from) {
- ListGridRecord record = new ListGridRecord();
-
- record.setAttribute(ATTR_ENTITY, from);
-
- record.setAttribute(ATTR_ID, from.getId());
- record.setAttribute(ATTR_NAME, from.getName());
- record.setAttribute(ATTR_DRIFT_HANDLING_MODE,
getDriftHandlingModeDisplayName(from.getDriftHandlingMode()));
- record.setAttribute(ATTR_INTERVAL, String.valueOf(from.getInterval()));
- record.setAttribute(ATTR_BASE_DIR_STRING, getBaseDirString(from.getBasedir()));
- record.setAttribute(ATTR_ENABLED,
ImageManager.getAvailabilityIcon(from.isEnabled()));
-
- // // for ancestry handling
- // Resource resource = ...
- // record.setAttribute(AncestryUtil.RESOURCE_ID, resource.getId());
- // record.setAttribute(AncestryUtil.RESOURCE_NAME, resource.getName());
- // record.setAttribute(AncestryUtil.RESOURCE_ANCESTRY, resource.getAncestry());
- // record.setAttribute(AncestryUtil.RESOURCE_TYPE_ID,
resource.getResourceType().getId());
-
- return record;
- }
-
- public static String getDriftHandlingModeDisplayName(DriftHandlingMode
driftHandlingMode) {
- switch (driftHandlingMode) {
- case plannedChanges:
- return DRIFT_HANDLING_MODE_PLANNED;
-
- default:
- return DRIFT_HANDLING_MODE_NORMAL;
- }
- }
-
- private static String getBaseDirString(BaseDirectory basedir) {
- return basedir.getValueContext() + ":" + basedir.getValueName();
- }
-
- protected EntityContext getEntityContext() {
- return entityContext;
- }
-
- protected void setEntityContext(EntityContext entityContext) {
- this.entityContext = entityContext;
- }
-
-}
\ No newline at end of file
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationEditView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationEditView.java
deleted file mode 100644
index 0ae1f7a..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationEditView.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift;
-
-import java.util.EnumSet;
-import java.util.Map;
-
-import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.smartgwt.client.types.Overflow;
-import com.smartgwt.client.widgets.IButton;
-import com.smartgwt.client.widgets.events.ClickEvent;
-import com.smartgwt.client.widgets.events.ClickHandler;
-import com.smartgwt.client.widgets.toolbar.ToolStrip;
-
-import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition;
-import org.rhq.enterprise.gui.coregui.client.CoreGUI;
-import org.rhq.enterprise.gui.coregui.client.LinkManager;
-import org.rhq.enterprise.gui.coregui.client.RefreshableView;
-import
org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor;
-import
org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent;
-import
org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener;
-import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
-import
org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceDetailView;
-import org.rhq.enterprise.gui.coregui.client.util.message.Message;
-import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
-
-/**
- * A view for editing a Resource's configuration.
- *
- * @author Jay Shaughnessy
- */
-public class DriftConfigurationEditView extends LocatableVLayout implements
PropertyValueChangeListener,
- RefreshableView {
-
- private EntityContext context;
- private int driftConfigId;
- private boolean hasWriteAccess;
- private ConfigurationEditor editor;
- private ToolStrip buttonbar;
- private IButton saveButton;
-
- private boolean refreshing = false;
-
- public DriftConfigurationEditView(String locatorId, EntityContext context, int
driftConfigId, boolean hasWriteAccess) {
- super(locatorId);
-
- this.context = context;
- this.driftConfigId = driftConfigId;
- this.hasWriteAccess = hasWriteAccess;
- }
-
- @Override
- protected void onDraw() {
- super.onDraw();
-
- this.buttonbar = new ToolStrip();
- buttonbar.setWidth100();
- buttonbar.setExtraSpace(10);
- buttonbar.setMembersMargin(5);
- buttonbar.setLayoutMargin(5);
-
- this.saveButton = new LocatableIButton(this.extendLocatorId("Save"),
MSG.common_button_save());
- this.saveButton.addClickHandler(new ClickHandler() {
- public void onClick(ClickEvent clickEvent) {
- save();
- }
- });
- buttonbar.addMember(saveButton);
- // The button bar will remain hidden until the configuration has been
successfully loaded.
- buttonbar.setVisible(false);
- addMember(buttonbar);
-
- refresh();
-
- if (!this.hasWriteAccess) {
- Message message = new Message(MSG.view_configurationDetails_noPermission(),
Message.Severity.Info, EnumSet
- .of(Message.Option.Transient, Message.Option.Sticky));
- CoreGUI.getMessageCenter().notify(message);
- }
- }
-
- @Override
- public void refresh() {
- if (this.refreshing) {
- return; // we are already in the process of refreshing, don't do it
again
- }
-
- this.refreshing = true;
- this.buttonbar.setVisible(false);
-
- if (editor != null) {
- editor.destroy();
- removeMember(editor);
- }
-
- GWTServiceLookup.getDriftService().getDriftConfiguration(driftConfigId,
- new AsyncCallback<DriftConfiguration>() {
- @Override
- public void onSuccess(final DriftConfiguration result) {
-
- editor = new ConfigurationEditor(extendLocatorId("Editor"),
DriftConfigurationDefinition
- .getInstanceForExistingConfiguration(),
result.getConfiguration());
- editor.setOverflow(Overflow.AUTO);
-
editor.addPropertyValueChangeListener(DriftConfigurationEditView.this);
- editor.setReadOnly(!hasWriteAccess);
- addMember(editor);
-
- saveButton.disable();
- buttonbar.setVisible(true);
- markForRedraw();
- refreshing = false;
- }
-
- @Override
- public void onFailure(Throwable caught) {
- refreshing = false;
- CoreGUI.getErrorHandler().handleError("Failed to load
configuration.", caught);
- }
- });
- }
-
- private void save() {
- Configuration updatedConfiguration = editor.getConfiguration();
-
- GWTServiceLookup.getDriftService().updateDriftConfiguration(context,
- new DriftConfiguration(updatedConfiguration), new AsyncCallback<Void>()
{
- public void onFailure(Throwable caught) {
-
CoreGUI.getErrorHandler().handleError(MSG.view_configurationDetails_error_updateFailure(),
caught);
- }
-
- public void onSuccess(Void result) {
- Message message = new Message(MSG.view_drift_success_defUpdated(),
Message.Severity.Info);
-
- switch (context.getType()) {
- case Resource:
- int resourceId = context.getResourceId();
-
- String driftHistoryUrl =
LinkManager.getResourceTabLink(resourceId,
- ResourceDetailView.Tab.DRIFT,
ResourceDetailView.ConfigurationSubTab.HISTORY);
- driftHistoryUrl = driftHistoryUrl.substring(1); // chop off the
leading '#'
- CoreGUI.goToView(driftHistoryUrl, message);
-
- break;
-
- default:
- throw new IllegalArgumentException("Entity Context Type not
supported [" + context + "]");
- }
- }
- });
- }
-
- @Override
- public void propertyValueChanged(PropertyValueChangeEvent event) {
- MessageCenter messageCenter = CoreGUI.getMessageCenter();
- Message message;
- if (event.isInvalidPropertySetChanged()) {
- Map<String, String> invalidPropertyNames =
event.getInvalidPropertyNames();
- if (invalidPropertyNames.isEmpty()) {
- this.saveButton.enable();
- message = new Message(MSG.view_configurationDetails_allPropertiesValid(),
Message.Severity.Info,
- EnumSet.of(Message.Option.Transient, Message.Option.Sticky));
- } else {
- this.saveButton.disable();
- message = new
Message(MSG.view_configurationDetails_somePropertiesInvalid(invalidPropertyNames.values()
- .toString()), Message.Severity.Error,
EnumSet.of(Message.Option.Transient, Message.Option.Sticky));
- }
- messageCenter.notify(message);
- } else {
- this.saveButton.enable();
- }
- }
-
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationView.java
deleted file mode 100644
index 00fa49f..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationView.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright 2011, 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.gui.coregui.client.drift;
-
-import java.util.ArrayList;
-
-import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.smartgwt.client.data.Criteria;
-import com.smartgwt.client.data.Record;
-import com.smartgwt.client.data.RecordList;
-import com.smartgwt.client.data.ResultSet;
-import com.smartgwt.client.data.SortSpecifier;
-import com.smartgwt.client.types.SortDirection;
-import com.smartgwt.client.widgets.Canvas;
-import com.smartgwt.client.widgets.grid.ListGrid;
-import com.smartgwt.client.widgets.grid.ListGridField;
-import com.smartgwt.client.widgets.grid.ListGridRecord;
-
-import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.drift.DriftCategory;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.enterprise.gui.coregui.client.CoreGUI;
-import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction;
-import org.rhq.enterprise.gui.coregui.client.components.table.TableAction;
-import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement;
-import org.rhq.enterprise.gui.coregui.client.components.table.TableSection;
-import org.rhq.enterprise.gui.coregui.client.components.view.ViewName;
-import org.rhq.enterprise.gui.coregui.client.drift.wizard.DriftAddConfigWizard;
-import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
-import org.rhq.enterprise.gui.coregui.client.util.message.Message;
-
-/**
- * A view that displays a paginated table of {@link
org.rhq.core.domain.drift.DriftConfiguration}s, along with the
- * ability to filter (maybe) those drift configs, sort those drift configs, double-click
a row to view/edit the
- * drift config, and perform various actionns: add/delete, etc.
- * This view full respects the user's authorization, and will not allow actions on
the drifts unless the user is
- * either the inventory manager or has MANAGE_DRIFT permission on every resource
corresponding to the drift configs
- * being operated on.
- *
- * @author Jay Shaughnessy
- */
-public class DriftConfigurationView extends
TableSection<DriftConfigurationDataSource> {
-
- public static final ViewName SUBSYSTEM_VIEW_ID = new ViewName("DriftDefs",
MSG.common_title_definitions());
-
- private static SortSpecifier DEFAULT_SORT_SPECIFIER = new
SortSpecifier(DriftConfigurationDataSource.ATTR_NAME,
- SortDirection.ASCENDING);
-
- private static final Criteria INITIAL_CRITERIA = new Criteria();
-
- private EntityContext context;
- private boolean hasWriteAccess;
- private DriftConfigurationDataSource dataSource;
-
- static {
- DriftCategory[] categoryValues = DriftCategory.values();
- String[] categoryNames = new String[categoryValues.length];
- int i = 0;
- for (DriftCategory c : categoryValues) {
- categoryNames[i++] = c.name();
- }
-
- // Add any INITIAL_CRITERIA here (non currently)
- }
-
- // for subsystem views
- public DriftConfigurationView(String locatorId) {
- this(locatorId, SUBSYSTEM_VIEW_ID.getTitle(), EntityContext.forSubsystemView(),
false);
- }
-
- public DriftConfigurationView(String locatorId, EntityContext entityContext) {
- this(locatorId, SUBSYSTEM_VIEW_ID.getTitle(), entityContext, false);
- }
-
- public DriftConfigurationView(String locatorId, String tableTitle, EntityContext
entityContext) {
- this(locatorId, tableTitle, entityContext, false);
- }
-
- protected DriftConfigurationView(String locatorId, String tableTitle, EntityContext
context, boolean hasWriteAccess) {
- super(locatorId, tableTitle, INITIAL_CRITERIA, new SortSpecifier[] {
DEFAULT_SORT_SPECIFIER });
- this.context = context;
- this.hasWriteAccess = hasWriteAccess;
-
- setInitialCriteriaFixed(false);
- setDataSource(getDataSource());
- }
-
- @Override
- public DriftConfigurationDataSource getDataSource() {
- if (null == this.dataSource) {
- this.dataSource = new DriftConfigurationDataSource(context);
- }
- return this.dataSource;
- }
-
- @Override
- protected void configureTableFilters() {
- // currently no table filters
- }
-
- @Override
- protected void configureTable() {
- ArrayList<ListGridField> dataSourceFields =
getDataSource().getListGridFields();
- getListGrid().setFields(dataSourceFields.toArray(new
ListGridField[dataSourceFields.size()]));
- setupTableInteractions(this.hasWriteAccess);
-
- super.configureTable();
- }
-
- private void setupTableInteractions(final boolean hasWriteAccess) {
- TableActionEnablement deleteEnablement = hasWriteAccess ?
TableActionEnablement.ANY
- : TableActionEnablement.NEVER;
- TableActionEnablement detectNowEnablement = hasWriteAccess ?
TableActionEnablement.SINGLE
- : TableActionEnablement.NEVER;
-
- addTableAction("Add", MSG.common_button_add(), null, new TableAction()
{
- public boolean isEnabled(ListGridRecord[] selection) {
- return hasWriteAccess;
- }
-
- public void executeAction(ListGridRecord[] selection, Object actionValue) {
- add();
- }
- });
-
- addTableAction("Delete", MSG.common_button_delete(),
MSG.view_drift_delete_configConfirm(),
- new AbstractTableAction(deleteEnablement) {
- public void executeAction(ListGridRecord[] selection, Object actionValue)
{
- delete(selection);
- }
- });
-
- addTableAction("DeleteAll", MSG.common_button_delete_all(),
MSG.view_drift_delete_configConfirmAll(),
- new TableAction() {
- public boolean isEnabled(ListGridRecord[] selection) {
- ListGrid grid = getListGrid();
- ResultSet resultSet = (null != grid) ? grid.getResultSet() : null;
- return (hasWriteAccess && grid != null && resultSet
!= null && !resultSet.isEmpty());
- }
-
- public void executeAction(ListGridRecord[] selection, Object actionValue)
{
- deleteAll();
- }
- });
-
- addTableAction("DetectNow", MSG.view_drift_button_detectNow(), null,
new AbstractTableAction(
- detectNowEnablement) {
- public void executeAction(ListGridRecord[] selection, Object actionValue) {
- detectDrift(selection); // will only ever be a single selection - see
detectNowEnablement variable
- }
- });
- }
-
- private void add() {
- DriftAddConfigWizard.showWizard(context, this);
- // we can refresh the table buttons immediately since the wizard is a dialog,
the
- // user can't access enabled buttons anyway.
- DriftConfigurationView.this.refreshTableInfo();
- }
-
- private void delete(ListGridRecord[] records) {
- final String[] driftConfigNames = new String[records.length];
- for (int i = 0, selectionLength = records.length; i < selectionLength; i++) {
- ListGridRecord record = records[i];
- String driftConfigName =
record.getAttribute(DriftConfigurationDataSource.ATTR_NAME);
- driftConfigNames[i] = driftConfigName;
- }
-
- deleteDriftConfigurationsByName(driftConfigNames);
- }
-
- private void deleteAll() {
- final RecordList records = getListGrid().getDataAsRecordList();
- final int numRecords = records.getLength();
- final String[] driftConfigNames = new String[numRecords];
- for (int i = 0; i < numRecords; i++) {
- Record record = records.get(i);
- String driftConfigName =
record.getAttribute(DriftConfigurationDataSource.ATTR_NAME);
- driftConfigNames[i] = driftConfigName;
- }
-
- deleteDriftConfigurationsByName(driftConfigNames);
- }
-
- private void deleteDriftConfigurationsByName(final String[] driftConfigNames) {
- GWTServiceLookup.getDriftService().deleteDriftConfigurationsByContext(context,
driftConfigNames,
- new AsyncCallback<Integer>() {
- public void onSuccess(Integer resultCount) {
- CoreGUI.getMessageCenter().notify(
- new
Message(MSG.view_drift_success_deleteConfigs(String.valueOf(resultCount)),
- Message.Severity.Info));
- refresh();
- }
-
- public void onFailure(Throwable caught) {
-
CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteDefs(), caught);
- }
- });
- }
-
- private void detectDrift(ListGridRecord[] records) {
- // we will only ever have a single record selected, hence why we can access the
[0] item
- DriftConfiguration driftConfig = (DriftConfiguration) records[0]
- .getAttributeAsObject(DriftConfigurationDataSource.ATTR_ENTITY);
- GWTServiceLookup.getDriftService().detectDrift(context, driftConfig, new
AsyncCallback<Void>() {
- public void onSuccess(Void result) {
- CoreGUI.getMessageCenter().notify(
- new Message(MSG.view_drift_success_detectNow(),
Message.Severity.Info));
- refresh();
- }
-
- public void onFailure(Throwable caught) {
- CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_detectNow(),
caught);
- }
- });
- }
-
- @Override
- public Canvas getDetailsView(Integer driftConfigId) {
- return new DriftConfigurationEditView(extendLocatorId("ConfigEdit"),
context, driftConfigId, hasWriteAccess);
- }
-
- public EntityContext getContext() {
- return context;
- }
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java
index cdb85b7..ba0dd8d 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java
@@ -73,7 +73,7 @@ public class DriftDataSource extends RPCDataSource<DriftComposite,
GenericDriftC
public static final String ATTR_CTIME = "ctime";
public static final String ATTR_CATEGORY = "category";
public static final String ATTR_CHANGESET_VERSION = "changeSetVersion";
- public static final String ATTR_CHANGESET_CONFIG = "changSetConfig";
+ public static final String ATTR_CHANGESET_DEF_NAME = "changSetDef";
public static final String ATTR_PATH = "path";
public static final String FILTER_CATEGORIES = "categories";
@@ -83,7 +83,7 @@ public class DriftDataSource extends RPCDataSource<DriftComposite,
GenericDriftC
private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService();
- private EntityContext entityContext;
+ protected EntityContext entityContext;
public DriftDataSource() {
this(EntityContext.forSubsystemView());
@@ -109,8 +109,8 @@ public class DriftDataSource extends RPCDataSource<DriftComposite,
GenericDriftC
ctimeField.setHoverCustomizer(TimestampCellFormatter.getHoverCustomizer(ATTR_CTIME));
fields.add(ctimeField);
- ListGridField changeSetConfigField = new ListGridField(ATTR_CHANGESET_CONFIG,
MSG.common_title_definition());
- fields.add(changeSetConfigField);
+ ListGridField changeSetDefField = new ListGridField(ATTR_CHANGESET_DEF_NAME,
MSG.common_title_definition());
+ fields.add(changeSetDefField);
ListGridField changeSetVersionField = new ListGridField(ATTR_CHANGESET_VERSION,
MSG.view_drift_table_snapshot());
fields.add(changeSetVersionField);
@@ -195,15 +195,15 @@ public class DriftDataSource extends
RPCDataSource<DriftComposite, GenericDriftC
}
public void onSuccess(PageList<DriftComposite> result) {
- // only get the desired config names (substring match)
+ // only get the desired def names (substring match)
// note - this does not alter the PageList row count, which, I think,
makes this
// ok without messing up paging.
- String configFilter = getFilter(request, FILTER_DEFINITION,
String.class);
- if (null != configFilter && !configFilter.isEmpty()) {
- configFilter = configFilter.toLowerCase();
+ String defFilter = getFilter(request, FILTER_DEFINITION, String.class);
+ if (null != defFilter && !defFilter.isEmpty()) {
+ defFilter = defFilter.toLowerCase();
for (Iterator<DriftComposite> i =
result.getValues().iterator(); i.hasNext();) {
DriftComposite composite = i.next();
- if
(!composite.getDriftConfigName().toLowerCase().contains(configFilter)) {
+ if
(!composite.getDriftDefinitionName().toLowerCase().contains(defFilter)) {
i.remove();
}
}
@@ -284,12 +284,13 @@ public class DriftDataSource extends
RPCDataSource<DriftComposite, GenericDriftC
DriftCategory[] categoriesFilter = getArrayFilter(request, FILTER_CATEGORIES,
DriftCategory.class);
if (categoriesFilter == null || categoriesFilter.length == 0) {
- return null; // user didn't select any priorities - return null to
indicate no data should be displayed
+ return null; // user didn't select any categories - return null to
indicate no data should be displayed
}
String changeSetFilter = getFilter(request, FILTER_SNAPSHOT, String.class);
String pathFilter = getFilter(request, FILTER_PATH, String.class);
- // note, this criteria does not allow for query-time config name filtering. That
filter is applied lazily
+
+ // NOTE! This criteria does not allow for query-time definition name filtering.
That filter is applied lazily
// to the query results.
GenericDriftCriteria criteria = new GenericDriftCriteria();
@@ -369,7 +370,7 @@ public class DriftDataSource extends RPCDataSource<DriftComposite,
GenericDriftC
break;
}
record.setAttribute(ATTR_PATH, drift.getPath());
- record.setAttribute(ATTR_CHANGESET_CONFIG, from.getDriftConfigName());
+ record.setAttribute(ATTR_CHANGESET_DEF_NAME, from.getDriftDefinitionName());
record.setAttribute(ATTR_CHANGESET_VERSION, drift.getChangeSet().getVersion());
// for ancestry handling
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionDataSource.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionDataSource.java
new file mode 100644
index 0000000..f9c5f1d
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionDataSource.java
@@ -0,0 +1,313 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+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.Record;
+import com.smartgwt.client.rpc.RPCResponse;
+import com.smartgwt.client.types.Alignment;
+import com.smartgwt.client.types.ListGridFieldType;
+import com.smartgwt.client.widgets.grid.CellFormatter;
+import com.smartgwt.client.widgets.grid.HoverCustomizer;
+import com.smartgwt.client.widgets.grid.ListGridField;
+import com.smartgwt.client.widgets.grid.ListGridRecord;
+import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
+import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.drift.DriftDefinition.BaseDirectory;
+import org.rhq.core.domain.util.PageList;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.ImageManager;
+import org.rhq.enterprise.gui.coregui.client.LinkManager;
+import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTServiceAsync;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+import org.rhq.enterprise.gui.coregui.client.inventory.resource.AncestryUtil;
+import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
+
+/**
+ * @author Jay Shaughnessy
+ * @author John Mazzitelli
+ */
+public class DriftDefinitionDataSource extends RPCDataSource<DriftDefinition,
DriftDefinitionCriteria> {
+
+ public static final String ATTR_ENTITY = "object";
+ public static final String ATTR_ID = "id";
+ public static final String ATTR_NAME = "name";
+ public static final String ATTR_INTERVAL = "interval";
+ public static final String ATTR_DRIFT_HANDLING_MODE = "driftHandlingMode";
+ public static final String ATTR_BASE_DIR_STRING = "baseDirString";
+ public static final String ATTR_ENABLED = "enabled";
+ public static final String ATTR_EDIT = "edit";
+
+ public static final String DRIFT_HANDLING_MODE_NORMAL =
MSG.view_drift_table_driftHandlingMode_normal();
+ public static final String DRIFT_HANDLING_MODE_PLANNED =
MSG.view_drift_table_driftHandlingMode_plannedChanges();
+
+ private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService();
+ private EntityContext entityContext;
+
+ public DriftDefinitionDataSource() {
+ this(EntityContext.forSubsystemView());
+ }
+
+ public DriftDefinitionDataSource(EntityContext context) {
+ this.entityContext = context;
+ addDataSourceFields();
+ }
+
+ /**
+ * The view that contains the list grid which will display this datasource's data
will call this
+ * method to get the field information which is used to control the display of the
data.
+ *
+ * @return list grid fields used to display the datasource data
+ */
+ public ArrayList<ListGridField> getListGridFields() {
+ ArrayList<ListGridField> fields = new ArrayList<ListGridField>(6);
+
+ ListGridField nameField = new ListGridField(ATTR_NAME, MSG.common_title_name());
+ fields.add(nameField);
+
+ ListGridField enabledField = new ListGridField(ATTR_ENABLED,
MSG.common_title_enabled());
+ enabledField.setType(ListGridFieldType.IMAGE);
+ enabledField.setAlign(Alignment.CENTER);
+ fields.add(enabledField);
+
+ ListGridField driftHandlingModeField = new
ListGridField(ATTR_DRIFT_HANDLING_MODE, MSG
+ .view_drift_table_driftHandlingMode());
+ fields.add(driftHandlingModeField);
+
+ ListGridField intervalField = new ListGridField(ATTR_INTERVAL,
MSG.common_title_interval());
+ fields.add(intervalField);
+
+ ListGridField baseDirField = new ListGridField(ATTR_BASE_DIR_STRING,
MSG.view_drift_table_baseDir());
+ // can't sort on this because it's not an entity field, it's derived
from the config only
+ baseDirField.setCanSort(false);
+ fields.add(baseDirField);
+
+ ListGridField editField = new ListGridField(ATTR_EDIT, "Edit?"); //TODO
I18N
+ editField.setType(ListGridFieldType.IMAGE);
+ editField.setAlign(Alignment.CENTER);
+ editField.addRecordClickHandler(new RecordClickHandler() {
+
+ public void onRecordClick(RecordClickEvent event) {
+ switch (entityContext.getType()) {
+ case Resource:
+
CoreGUI.goToView(LinkManager.getDriftDefinitionEditLink(entityContext.getResourceId(),
event
+ .getRecord().getAttributeAsInt(ATTR_ID)));
+ break;
+ default:
+ throw new IllegalArgumentException("Entity Type not
supported");
+ }
+ }
+ });
+ fields.add(editField);
+
+ if (this.entityContext.type != EntityContext.Type.Resource) {
+ ListGridField resourceNameField = new
ListGridField(AncestryUtil.RESOURCE_NAME, MSG.common_title_resource());
+ resourceNameField.setCellFormatter(new CellFormatter() {
+ public String format(Object o, ListGridRecord listGridRecord, int i, int
i1) {
+ Integer resourceId =
listGridRecord.getAttributeAsInt(AncestryUtil.RESOURCE_ID);
+ String url = LinkManager.getResourceLink(resourceId);
+ return SeleniumUtility.getLocatableHref(url, o.toString(), null);
+ }
+ });
+ resourceNameField.setShowHover(true);
+ resourceNameField.setHoverCustomizer(new HoverCustomizer() {
+ public String hoverHTML(Object value, ListGridRecord listGridRecord, int
rowNum, int colNum) {
+ return AncestryUtil.getResourceHoverHTML(listGridRecord, 0);
+ }
+ });
+ fields.add(resourceNameField);
+
+ ListGridField ancestryField = AncestryUtil.setupAncestryListGridField();
+ fields.add(ancestryField);
+
+ nameField.setWidth("20%");
+ enabledField.setWidth(60);
+ driftHandlingModeField.setWidth("10%");
+ intervalField.setWidth(100);
+ baseDirField.setWidth("*");
+ editField.setWidth(70);
+ resourceNameField.setWidth("20%");
+ ancestryField.setWidth("40%");
+ } else {
+ nameField.setWidth("20%");
+ enabledField.setWidth(60);
+ driftHandlingModeField.setWidth("10%");
+ intervalField.setWidth(100);
+ baseDirField.setWidth("*");
+ editField.setWidth(70);
+ }
+
+ return fields;
+ }
+
+ @Override
+ protected void executeFetch(final DSRequest request, final DSResponse response,
+ final DriftDefinitionCriteria criteria) {
+ this.driftService.findDriftDefinitionsByCriteria(criteria, new
AsyncCallback<PageList<DriftDefinition>>() {
+ public void onFailure(Throwable caught) {
+ CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_load(),
caught);
+ response.setStatus(RPCResponse.STATUS_FAILURE);
+ processResponse(request.getRequestId(), response);
+ }
+
+ public void onSuccess(PageList<DriftDefinition> result) {
+ dataRetrieved(result, response, request);
+ }
+ });
+ }
+
+ /**
+ * Additional processing to support entity-specific or cross-resource views, and
something that can be overidden.
+ */
+ protected void dataRetrieved(final PageList<DriftDefinition> result, final
DSResponse response,
+ final DSRequest request) {
+ switch (entityContext.type) {
+
+ // no need to disambiguate, the drift defs are for a single resource
+ case Resource:
+ response.setData(buildRecords(result));
+ // for paging to work we have to specify size of full result set
+ response.setTotalRows(getTotalRows(result, response, request));
+ processResponse(request.getRequestId(), response);
+ break;
+
+ case ResourceGroup:
+ //TODO
+
+ default:
+ throw new IllegalArgumentException("Unsupported Context Type: " +
entityContext);
+ }
+ }
+
+ /**
+ * Sub-classes can override this to add fine-grained control over the result set
size. By default the
+ * total rows are set to the total result set for the query, allowing proper paging.
But some views (portlets)
+ * may want to limit results to a small set (like most recent).
+ * @param result
+ * @param response
+ * @param request
+ *
+ * @return should not exceed result.size().
+ */
+ protected int getTotalRows(final Collection<DriftDefinition> result, final
DSResponse response,
+ final DSRequest request) {
+ return result.size();
+ }
+
+ @Override
+ protected DriftDefinitionCriteria getFetchCriteria(DSRequest request) {
+
+ DriftDefinitionCriteria criteria = new DriftDefinitionCriteria();
+ switch (entityContext.getType()) {
+ case Resource:
+ criteria.addFilterResourceIds(entityContext.getResourceId());
+ break;
+
+ case ResourceGroup:
+ //TODO
+
+ default:
+ // no filter
+ }
+
+ criteria.fetchConfiguration(true);
+ criteria.setPageControl(getPageControl(request));
+
+ return criteria;
+ }
+
+ /*
+ @Override
+ protected String getSortFieldForColumn(String columnName) {
+ if (AncestryUtil.RESOURCE_ANCESTRY.equals(columnName)) {
+ return "ancestry";
+ }
+
+ return super.getSortFieldForColumn(columnName);
+ }
+ */
+
+ @Override
+ public DriftDefinition copyValues(Record from) {
+ return (DriftDefinition) from.getAttributeAsObject(ATTR_ENTITY);
+ }
+
+ @Override
+ public ListGridRecord copyValues(DriftDefinition from) {
+ return convert(from);
+ }
+
+ public static ListGridRecord convert(DriftDefinition from) {
+ ListGridRecord record = new ListGridRecord();
+
+ record.setAttribute(ATTR_ENTITY, from);
+
+ record.setAttribute(ATTR_ID, from.getId());
+ record.setAttribute(ATTR_NAME, from.getName());
+ record.setAttribute(ATTR_DRIFT_HANDLING_MODE,
getDriftHandlingModeDisplayName(from.getDriftHandlingMode()));
+ record.setAttribute(ATTR_INTERVAL, String.valueOf(from.getInterval()));
+ record.setAttribute(ATTR_BASE_DIR_STRING, getBaseDirString(from.getBasedir()));
+ record.setAttribute(ATTR_ENABLED,
ImageManager.getAvailabilityIcon(from.isEnabled()));
+ // fixed value, just the edit icon
+ record.setAttribute(ATTR_EDIT, ImageManager.getEditIcon());
+
+ // // for ancestry handling
+ // Resource resource = ...
+ // record.setAttribute(AncestryUtil.RESOURCE_ID, resource.getId());
+ // record.setAttribute(AncestryUtil.RESOURCE_NAME, resource.getName());
+ // record.setAttribute(AncestryUtil.RESOURCE_ANCESTRY, resource.getAncestry());
+ // record.setAttribute(AncestryUtil.RESOURCE_TYPE_ID,
resource.getResourceType().getId());
+
+ return record;
+ }
+
+ public static String getDriftHandlingModeDisplayName(DriftHandlingMode
driftHandlingMode) {
+ switch (driftHandlingMode) {
+ case plannedChanges:
+ return DRIFT_HANDLING_MODE_PLANNED;
+
+ default:
+ return DRIFT_HANDLING_MODE_NORMAL;
+ }
+ }
+
+ private static String getBaseDirString(BaseDirectory basedir) {
+ return basedir.getValueContext() + ":" + basedir.getValueName();
+ }
+
+ protected EntityContext getEntityContext() {
+ return entityContext;
+ }
+
+ protected void setEntityContext(EntityContext entityContext) {
+ this.entityContext = entityContext;
+ }
+
+}
\ No newline at end of file
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionEditView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionEditView.java
new file mode 100644
index 0000000..1808dfa
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionEditView.java
@@ -0,0 +1,192 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift;
+
+import java.util.EnumSet;
+import java.util.Map;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+import com.smartgwt.client.types.Overflow;
+import com.smartgwt.client.widgets.IButton;
+import com.smartgwt.client.widgets.events.ClickEvent;
+import com.smartgwt.client.widgets.events.ClickHandler;
+import com.smartgwt.client.widgets.toolbar.ToolStrip;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.LinkManager;
+import org.rhq.enterprise.gui.coregui.client.RefreshableView;
+import
org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor;
+import
org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent;
+import
org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+import
org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceDetailView;
+import org.rhq.enterprise.gui.coregui.client.util.message.Message;
+import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+
+/**
+ * A view for editing a Resource's configuration.
+ *
+ * @author Jay Shaughnessy
+ */
+public class DriftDefinitionEditView extends LocatableVLayout implements
PropertyValueChangeListener, RefreshableView {
+
+ private EntityContext context;
+ private int driftDefId;
+ private boolean hasWriteAccess;
+ private ConfigurationEditor editor;
+ private ToolStrip buttonbar;
+ private IButton saveButton;
+
+ private boolean refreshing = false;
+
+ public DriftDefinitionEditView(String locatorId, EntityContext context, int
driftDefId, boolean hasWriteAccess) {
+ super(locatorId);
+
+ this.context = context;
+ this.driftDefId = driftDefId;
+ this.hasWriteAccess = hasWriteAccess;
+ }
+
+ @Override
+ protected void onDraw() {
+ super.onDraw();
+
+ this.buttonbar = new ToolStrip();
+ buttonbar.setWidth100();
+ buttonbar.setExtraSpace(10);
+ buttonbar.setMembersMargin(5);
+ buttonbar.setLayoutMargin(5);
+
+ this.saveButton = new LocatableIButton(this.extendLocatorId("Save"),
MSG.common_button_save());
+ this.saveButton.addClickHandler(new ClickHandler() {
+ public void onClick(ClickEvent clickEvent) {
+ save();
+ }
+ });
+ buttonbar.addMember(saveButton);
+ // The button bar will remain hidden until the definition has been successfully
loaded.
+ buttonbar.setVisible(false);
+ addMember(buttonbar);
+
+ refresh();
+
+ if (!this.hasWriteAccess) {
+ Message message = new Message(MSG.view_configurationDetails_noPermission(),
Message.Severity.Info, EnumSet
+ .of(Message.Option.Transient, Message.Option.Sticky));
+ CoreGUI.getMessageCenter().notify(message);
+ }
+ }
+
+ @Override
+ public void refresh() {
+ if (this.refreshing) {
+ return; // we are already in the process of refreshing, don't do it
again
+ }
+
+ this.refreshing = true;
+ this.buttonbar.setVisible(false);
+
+ if (editor != null) {
+ editor.destroy();
+ removeMember(editor);
+ }
+
+ GWTServiceLookup.getDriftService().getDriftDefinition(driftDefId, new
AsyncCallback<DriftDefinition>() {
+ @Override
+ public void onSuccess(final DriftDefinition result) {
+
+ editor = new ConfigurationEditor(extendLocatorId("Editor"),
DriftConfigurationDefinition
+ .getInstanceForExistingConfiguration(), result.getConfiguration());
+ editor.setOverflow(Overflow.AUTO);
+ editor.addPropertyValueChangeListener(DriftDefinitionEditView.this);
+ editor.setReadOnly(!hasWriteAccess);
+ addMember(editor);
+
+ saveButton.disable();
+ buttonbar.setVisible(true);
+ markForRedraw();
+ refreshing = false;
+ }
+
+ @Override
+ public void onFailure(Throwable caught) {
+ refreshing = false;
+ CoreGUI.getErrorHandler().handleError("Failed to load
definition.", caught);
+ }
+ });
+ }
+
+ private void save() {
+ Configuration updatedConfiguration = editor.getConfiguration();
+
+ GWTServiceLookup.getDriftService().updateDriftDefinition(context, new
DriftDefinition(updatedConfiguration),
+ new AsyncCallback<Void>() {
+ public void onFailure(Throwable caught) {
+
CoreGUI.getErrorHandler().handleError(MSG.view_configurationDetails_error_updateFailure(),
caught);
+ }
+
+ public void onSuccess(Void result) {
+ Message message = new Message(MSG.view_drift_success_defUpdated(),
Message.Severity.Info);
+
+ switch (context.getType()) {
+ case Resource:
+ int resourceId = context.getResourceId();
+
+ String driftHistoryUrl =
LinkManager.getResourceTabLink(resourceId,
+ ResourceDetailView.Tab.DRIFT,
ResourceDetailView.ConfigurationSubTab.HISTORY);
+ driftHistoryUrl = driftHistoryUrl.substring(1); // chop off the
leading '#'
+ CoreGUI.goToView(driftHistoryUrl, message);
+
+ break;
+
+ default:
+ throw new IllegalArgumentException("Entity Context Type not
supported [" + context + "]");
+ }
+ }
+ });
+ }
+
+ @Override
+ public void propertyValueChanged(PropertyValueChangeEvent event) {
+ MessageCenter messageCenter = CoreGUI.getMessageCenter();
+ Message message;
+ if (event.isInvalidPropertySetChanged()) {
+ Map<String, String> invalidPropertyNames =
event.getInvalidPropertyNames();
+ if (invalidPropertyNames.isEmpty()) {
+ this.saveButton.enable();
+ message = new Message(MSG.view_configurationDetails_allPropertiesValid(),
Message.Severity.Info,
+ EnumSet.of(Message.Option.Transient, Message.Option.Sticky));
+ } else {
+ this.saveButton.disable();
+ message = new
Message(MSG.view_configurationDetails_somePropertiesInvalid(invalidPropertyNames.values()
+ .toString()), Message.Severity.Error,
EnumSet.of(Message.Option.Transient, Message.Option.Sticky));
+ }
+ messageCenter.notify(message);
+ } else {
+ this.saveButton.enable();
+ }
+ }
+
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionsView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionsView.java
new file mode 100644
index 0000000..d858fc2
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDefinitionsView.java
@@ -0,0 +1,259 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, 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.gui.coregui.client.drift;
+
+import java.util.ArrayList;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+import com.smartgwt.client.data.Criteria;
+import com.smartgwt.client.data.Record;
+import com.smartgwt.client.data.RecordList;
+import com.smartgwt.client.data.ResultSet;
+import com.smartgwt.client.data.SortSpecifier;
+import com.smartgwt.client.types.SortDirection;
+import com.smartgwt.client.widgets.Canvas;
+import com.smartgwt.client.widgets.grid.ListGrid;
+import com.smartgwt.client.widgets.grid.ListGridField;
+import com.smartgwt.client.widgets.grid.ListGridRecord;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.drift.DriftCategory;
+import org.rhq.core.domain.drift.DriftDefinition;
+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.AbstractTableAction;
+import org.rhq.enterprise.gui.coregui.client.components.table.TableAction;
+import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement;
+import org.rhq.enterprise.gui.coregui.client.components.table.TableSection;
+import org.rhq.enterprise.gui.coregui.client.components.view.ViewName;
+import org.rhq.enterprise.gui.coregui.client.drift.wizard.DriftAddDefinitionWizard;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+import org.rhq.enterprise.gui.coregui.client.util.message.Message;
+
+/**
+ * A list view that displays a paginated table of {@link
org.rhq.core.domain.drift.DriftDefinition}s. It has offers various
+ * options on the list like filtering (maybe) and sorting, add new/delete. Double-click
drills down to the carousel view for
+ * inspecting drift for the definition. Also, allows an edit view for the def's
underlying Config. This view full respects
+ * the user's authorization, and will not allow actions on the drift defs unless the
user is either the inventory
+ * manager or has MANAGE_DRIFT permission on every resource corresponding to the drift
defs being operated on.
+ *
+ * @author Jay Shaughnessy
+ */
+public class DriftDefinitionsView extends TableSection<DriftDefinitionDataSource>
{
+
+ public static final ViewName SUBSYSTEM_VIEW_ID = new ViewName("DriftDefs",
MSG.common_title_definitions());
+
+ private static SortSpecifier DEFAULT_SORT_SPECIFIER = new
SortSpecifier(DriftDefinitionDataSource.ATTR_NAME,
+ SortDirection.ASCENDING);
+
+ private static final Criteria INITIAL_CRITERIA = new Criteria();
+
+ private EntityContext context;
+ private boolean hasWriteAccess;
+ private DriftDefinitionDataSource dataSource;
+ private boolean useCarouselDetailsView;
+
+ static {
+ DriftCategory[] categoryValues = DriftCategory.values();
+ String[] categoryNames = new String[categoryValues.length];
+ int i = 0;
+ for (DriftCategory c : categoryValues) {
+ categoryNames[i++] = c.name();
+ }
+
+ // Add any INITIAL_CRITERIA here (non currently)
+ }
+
+ // for subsystem views
+ public DriftDefinitionsView(String locatorId) {
+ this(locatorId, SUBSYSTEM_VIEW_ID.getTitle(), EntityContext.forSubsystemView(),
false);
+ }
+
+ public DriftDefinitionsView(String locatorId, EntityContext entityContext) {
+ this(locatorId, SUBSYSTEM_VIEW_ID.getTitle(), entityContext, false);
+ }
+
+ public DriftDefinitionsView(String locatorId, String tableTitle, EntityContext
entityContext) {
+ this(locatorId, tableTitle, entityContext, false);
+ }
+
+ protected DriftDefinitionsView(String locatorId, String tableTitle, EntityContext
context, boolean hasWriteAccess) {
+ super(locatorId, tableTitle, INITIAL_CRITERIA, new SortSpecifier[] {
DEFAULT_SORT_SPECIFIER });
+ this.context = context;
+ this.hasWriteAccess = hasWriteAccess;
+
+ setInitialCriteriaFixed(false);
+ setDataSource(getDataSource());
+ }
+
+ @Override
+ public DriftDefinitionDataSource getDataSource() {
+ if (null == this.dataSource) {
+ this.dataSource = new DriftDefinitionDataSource(context);
+ }
+ return this.dataSource;
+ }
+
+ @Override
+ protected void configureTableFilters() {
+ // currently no table filters
+ }
+
+ @Override
+ protected void configureTable() {
+ ArrayList<ListGridField> dataSourceFields =
getDataSource().getListGridFields();
+ getListGrid().setFields(dataSourceFields.toArray(new
ListGridField[dataSourceFields.size()]));
+ setupTableInteractions(this.hasWriteAccess);
+
+ super.configureTable();
+ }
+
+ private void setupTableInteractions(final boolean hasWriteAccess) {
+ TableActionEnablement deleteEnablement = hasWriteAccess ?
TableActionEnablement.ANY
+ : TableActionEnablement.NEVER;
+ TableActionEnablement detectNowEnablement = hasWriteAccess ?
TableActionEnablement.SINGLE
+ : TableActionEnablement.NEVER;
+
+ addTableAction("Add", MSG.common_button_add(), null, new TableAction()
{
+ public boolean isEnabled(ListGridRecord[] selection) {
+ return hasWriteAccess;
+ }
+
+ public void executeAction(ListGridRecord[] selection, Object actionValue) {
+ add();
+ }
+ });
+
+ addTableAction("Delete", MSG.common_button_delete(),
MSG.view_drift_delete_defConfirm(),
+ new AbstractTableAction(deleteEnablement) {
+ public void executeAction(ListGridRecord[] selection, Object actionValue)
{
+ delete(selection);
+ }
+ });
+
+ addTableAction("DeleteAll", MSG.common_button_delete_all(),
MSG.view_drift_delete_defConfirmAll(),
+ new TableAction() {
+ public boolean isEnabled(ListGridRecord[] selection) {
+ ListGrid grid = getListGrid();
+ ResultSet resultSet = (null != grid) ? grid.getResultSet() : null;
+ return (hasWriteAccess && grid != null && resultSet
!= null && !resultSet.isEmpty());
+ }
+
+ public void executeAction(ListGridRecord[] selection, Object actionValue)
{
+ deleteAll();
+ }
+ });
+
+ addTableAction("DetectNow", MSG.view_drift_button_detectNow(), null,
new AbstractTableAction(
+ detectNowEnablement) {
+ public void executeAction(ListGridRecord[] selection, Object actionValue) {
+ detectDrift(selection); // will only ever be a single selection - see
detectNowEnablement variable
+ }
+ });
+ }
+
+ private void add() {
+ DriftAddDefinitionWizard.showWizard(context, this);
+ // we can refresh the table buttons immediately since the wizard is a dialog,
the
+ // user can't access enabled buttons anyway.
+ DriftDefinitionsView.this.refreshTableInfo();
+ }
+
+ private void delete(ListGridRecord[] records) {
+ final String[] driftDefNames = new String[records.length];
+ for (int i = 0, selectionLength = records.length; i < selectionLength; i++) {
+ ListGridRecord record = records[i];
+ String driftDefName =
record.getAttribute(DriftDefinitionDataSource.ATTR_NAME);
+ driftDefNames[i] = driftDefName;
+ }
+
+ deleteDriftDefinitionsByName(driftDefNames);
+ }
+
+ private void deleteAll() {
+ final RecordList records = getListGrid().getDataAsRecordList();
+ final int numRecords = records.getLength();
+ final String[] driftDefNames = new String[numRecords];
+ for (int i = 0; i < numRecords; i++) {
+ Record record = records.get(i);
+ String driftDefName =
record.getAttribute(DriftDefinitionDataSource.ATTR_NAME);
+ driftDefNames[i] = driftDefName;
+ }
+
+ deleteDriftDefinitionsByName(driftDefNames);
+ }
+
+ private void deleteDriftDefinitionsByName(final String[] driftDefNames) {
+ GWTServiceLookup.getDriftService().deleteDriftDefinitionsByContext(context,
driftDefNames,
+ new AsyncCallback<Integer>() {
+ public void onSuccess(Integer resultCount) {
+ CoreGUI.getMessageCenter().notify(
+ new
Message(MSG.view_drift_success_deleteDefs(String.valueOf(resultCount)),
+ Message.Severity.Info));
+ refresh();
+ }
+
+ public void onFailure(Throwable caught) {
+
CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteDefs(), caught);
+ }
+ });
+ }
+
+ private void detectDrift(ListGridRecord[] records) {
+ // we will only ever have a single record selected, hence why we can access the
[0] item
+ DriftDefinition driftDef = (DriftDefinition) records[0]
+ .getAttributeAsObject(DriftDefinitionDataSource.ATTR_ENTITY);
+ GWTServiceLookup.getDriftService().detectDrift(context, driftDef, new
AsyncCallback<Void>() {
+ public void onSuccess(Void result) {
+ CoreGUI.getMessageCenter().notify(
+ new Message(MSG.view_drift_success_detectNow(),
Message.Severity.Info));
+ refresh();
+ }
+
+ public void onFailure(Throwable caught) {
+ CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_detectNow(),
caught);
+ }
+ });
+ }
+
+ @Override
+ public void renderView(ViewPath viewPath) {
+ // we have two detail views for drift defs, the config editor and the carousel.
figure out which one we're
+ // dealing with. The default is the carousel, anything further in the path we
assume to be /Edit
+ if (!viewPath.isEnd()) {
+ this.useCarouselDetailsView = viewPath.isNextEnd();
+ }
+
+ super.renderView(viewPath);
+ }
+
+ @Override
+ public Canvas getDetailsView(Integer driftDefId) {
+ if (this.useCarouselDetailsView) {
+ return new DriftCarouselView(extendLocatorId("Carousel"), context,
driftDefId, hasWriteAccess);
+ }
+
+ return new DriftDefinitionEditView(extendLocatorId("DefintionEdit"),
context, driftDefId, hasWriteAccess);
+ }
+
+ public EntityContext getContext() {
+ return context;
+ }
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java
index 6961071..8d7baf5 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java
@@ -215,7 +215,7 @@ public class DriftDetailsView extends LocatableVLayout {
changeSetVersion.setValue(changeSet.getVersion());
StaticTextItem changeSetDriftHandling = new
StaticTextItem("changeSetDriftHandling", MSG
.view_drift_table_driftHandlingMode());
-
changeSetDriftHandling.setValue(DriftConfigurationDataSource.getDriftHandlingModeDisplayName(changeSet
+
changeSetDriftHandling.setValue(DriftDefinitionDataSource.getDriftHandlingModeDisplayName(changeSet
.getDriftHandlingMode()));
changeSetForm.setItems(changeSetId, changeSetCategory, changeSetVersion,
changeSetDriftHandling);
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java
index ca5bcb8..970750a 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java
@@ -64,7 +64,8 @@ public class DriftHistoryView extends
StringIDTableSection<DriftDataSource> {
private EntityContext context;
private boolean hasWriteAccess;
- private DriftDataSource dataSource;
+
+ protected DriftDataSource dataSource;
static {
DriftCategory[] categoryValues = DriftCategory.values();
@@ -122,12 +123,12 @@ public class DriftHistoryView extends
StringIDTableSection<DriftDataSource> {
SelectItem categoryFilter = new EnumSelectItem(DriftDataSource.FILTER_CATEGORIES,
MSG.common_title_category(),
DriftCategory.class, categories, categoryIcons);
- TextItem configurationFilter = new TextItem(DriftDataSource.FILTER_DEFINITION,
MSG.common_title_definition());
+ TextItem definitionFilter = new TextItem(DriftDataSource.FILTER_DEFINITION,
MSG.common_title_definition());
TextItem changeSetFilter = new TextItem(DriftDataSource.FILTER_SNAPSHOT,
MSG.view_drift_table_snapshot());
TextItem pathFilter = new TextItem(DriftDataSource.FILTER_PATH,
MSG.common_title_path());
if (isShowFilterForm()) {
- setFilterFormItems(configurationFilter, changeSetFilter, categoryFilter,
pathFilter);
+ setFilterFormItems(definitionFilter, changeSetFilter, categoryFilter,
pathFilter);
}
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeDataSource.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeDataSource.java
index 4da7eac..6302503 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeDataSource.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeDataSource.java
@@ -28,7 +28,7 @@ import com.smartgwt.client.data.DSResponse;
import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.ResourceCriteria;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
@@ -57,10 +57,10 @@ public class ResourceDriftChangeSetsTreeDataSource extends
AbstractDriftChangeSe
protected void fetchDriftConfigurations(final DSRequest request, final DSResponse
response) {
ResourceCriteria criteria = new ResourceCriteria();
criteria.addFilterId(context.getResourceId());
- criteria.fetchDriftConfigurations(true);
+ criteria.fetchDriftDefinitions(true);
this.resourceService.findResourcesByCriteria(criteria, new
AsyncCallback<PageList<Resource>>() {
public void onSuccess(PageList<Resource> result) {
- Set<DriftConfiguration> driftConfigs =
result.get(0).getDriftConfigurations();
+ Set<DriftDefinition> driftConfigs =
result.get(0).getDriftDefinitions();
response.setData(buildRecords(driftConfigs));
response.setTotalRows(result.getTotalSize());
processResponse(request.getRequestId(), response);
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java
index 9869a24..17cc752 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java
@@ -23,7 +23,7 @@ import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.widgets.tree.TreeNode;
import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.LinkManager;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
@@ -55,21 +55,21 @@ public class ResourceDriftChangeSetsTreeView extends
AbstractDriftChangeSetsTree
String driftId = ((DriftTreeNode) node).getDriftId();
String path = LinkManager.getDriftHistoryLink(this.context.resourceId,
driftId);
return path;
- } else if (node instanceof DriftConfigurationTreeNode) {
- int driftConfigId = ((DriftConfigurationTreeNode)
node).getDriftConfigurationId();
- String path = LinkManager.getDriftConfigurationLink(this.context.resourceId,
driftConfigId);
+ } else if (node instanceof DriftDefinitionTreeNode) {
+ int driftDefId = ((DriftDefinitionTreeNode) node).getDriftDefinitionId();
+ String path = LinkManager.getDriftDefinitionEditLink(this.context.resourceId,
driftDefId);
return path;
}
return null;
}
@Override
- protected void deleteDriftConfiguration(DriftConfiguration doomedDriftConfig) {
- GWTServiceLookup.getDriftService().deleteDriftConfigurationsByContext(context,
- new String[] { doomedDriftConfig.getName() }, new
AsyncCallback<Integer>() {
+ protected void deleteDriftDefinition(DriftDefinition doomedDriftDef) {
+ GWTServiceLookup.getDriftService().deleteDriftDefinitionsByContext(context,
+ new String[] { doomedDriftDef.getName() }, new AsyncCallback<Integer>()
{
public void onSuccess(Integer resultCount) {
CoreGUI.getMessageCenter().notify(
- new
Message(MSG.view_drift_success_deleteConfigs(String.valueOf(resultCount)),
+ new
Message(MSG.view_drift_success_deleteDefs(String.valueOf(resultCount)),
Message.Severity.Info));
refresh();
}
@@ -82,8 +82,8 @@ public class ResourceDriftChangeSetsTreeView extends
AbstractDriftChangeSetsTree
}
@Override
- protected void detectDrift(DriftConfiguration driftConfig) {
- GWTServiceLookup.getDriftService().detectDrift(context, driftConfig, new
AsyncCallback<Void>() {
+ protected void detectDrift(DriftDefinition driftDef) {
+ GWTServiceLookup.getDriftService().detectDrift(context, driftDef, new
AsyncCallback<Void>() {
public void onSuccess(Void result) {
CoreGUI.getMessageCenter().notify(
new Message(MSG.view_drift_success_detectNow(),
Message.Severity.Info));
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftConfigurationView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftConfigurationView.java
deleted file mode 100644
index c6163ac..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftConfigurationView.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright 2011, 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.gui.coregui.client.drift;
-
-import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.resource.composite.ResourceComposite;
-
-/**
- * @author Jay Shaughnessy
- */
-public class ResourceDriftConfigurationView extends DriftConfigurationView {
- public static ResourceDriftConfigurationView get(String locatorId, ResourceComposite
composite) {
- String tableTitle = MSG.view_drift_table_resourceDef();
- EntityContext context =
EntityContext.forResource(composite.getResource().getId());
- boolean hasWriteAccess = composite.getResourcePermission().isDrift();
- return new ResourceDriftConfigurationView(locatorId, tableTitle, context,
hasWriteAccess);
- }
-
- private ResourceDriftConfigurationView(String locatorId, String tableTitle,
EntityContext context,
- boolean hasWriteAccess) {
- super(locatorId, tableTitle, context, hasWriteAccess);
- }
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftDefinitionsView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftDefinitionsView.java
new file mode 100644
index 0000000..a32638a
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftDefinitionsView.java
@@ -0,0 +1,40 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2011, 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.gui.coregui.client.drift;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.resource.composite.ResourceComposite;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public class ResourceDriftDefinitionsView extends DriftDefinitionsView {
+ public static ResourceDriftDefinitionsView get(String locatorId, ResourceComposite
composite) {
+ String tableTitle = MSG.view_drift_table_resourceDef();
+ EntityContext context =
EntityContext.forResource(composite.getResource().getId());
+ boolean hasWriteAccess = composite.getResourcePermission().isDrift();
+ return new ResourceDriftDefinitionsView(locatorId, tableTitle, context,
hasWriteAccess);
+ }
+
+ private ResourceDriftDefinitionsView(String locatorId, String tableTitle,
EntityContext context,
+ boolean hasWriteAccess) {
+ super(locatorId, tableTitle, context, hasWriteAccess);
+ }
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddConfigWizard.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddConfigWizard.java
deleted file mode 100644
index 545912a..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddConfigWizard.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift.wizard;
-
-import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard;
-import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardView;
-
-/**
- * @author Jay Shaughnessy
- */
-public abstract class AbstractDriftAddConfigWizard extends AbstractWizard {
-
- private EntityContext context;
- private ResourceType type;
-
- private Configuration newStartingConfiguration;
- private DriftConfiguration newDriftConfiguration;
-
- private WizardView view;
-
- public AbstractDriftAddConfigWizard(final EntityContext context, ResourceType type)
{
- if (context == null) {
- throw new NullPointerException("context == null");
- }
-
- if (type == null) {
- throw new NullPointerException("type == null");
- }
-
- this.context = context;
- this.type = type;
- }
-
- public String getSubtitle() {
- return null;
- }
-
- abstract public void execute();
-
- public void display() {
- view = new WizardView(this);
- view.displayDialog();
- }
-
- public EntityContext getEntityContext() {
- return context;
- }
-
- public ResourceType getType() {
- return type;
- }
-
- public Configuration getNewStartingConfiguration() {
- return newStartingConfiguration;
- }
-
- public void setNewStartingConfiguration(Configuration newStartingConfiguration) {
- this.newStartingConfiguration = newStartingConfiguration;
- }
-
- public DriftConfiguration getNewDriftConfiguration() {
- return newDriftConfiguration;
- }
-
- public void setNewConfiguration(Configuration newDriftConfiguration) {
- this.newDriftConfiguration = new DriftConfiguration(newDriftConfiguration);
- }
-
- public void cancel() {
- // nothing to do
- }
-
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddDefinitionWizard.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddDefinitionWizard.java
new file mode 100644
index 0000000..541c268
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/AbstractDriftAddDefinitionWizard.java
@@ -0,0 +1,93 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift.wizard;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard;
+import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardView;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public abstract class AbstractDriftAddDefinitionWizard extends AbstractWizard {
+
+ private EntityContext context;
+ private ResourceType type;
+
+ private Configuration newStartingConfiguration;
+ private DriftDefinition newDriftDefinition;
+
+ private WizardView view;
+
+ public AbstractDriftAddDefinitionWizard(final EntityContext context, ResourceType
type) {
+ if (context == null) {
+ throw new NullPointerException("context == null");
+ }
+
+ if (type == null) {
+ throw new NullPointerException("type == null");
+ }
+
+ this.context = context;
+ this.type = type;
+ }
+
+ public String getSubtitle() {
+ return null;
+ }
+
+ abstract public void execute();
+
+ public void display() {
+ view = new WizardView(this);
+ view.displayDialog();
+ }
+
+ public EntityContext getEntityContext() {
+ return context;
+ }
+
+ public ResourceType getType() {
+ return type;
+ }
+
+ public Configuration getNewStartingConfiguration() {
+ return newStartingConfiguration;
+ }
+
+ public void setNewStartingConfiguration(Configuration newStartingConfiguration) {
+ this.newStartingConfiguration = newStartingConfiguration;
+ }
+
+ public DriftDefinition getNewDriftDefinition() {
+ return newDriftDefinition;
+ }
+
+ public void setNewConfiguration(Configuration newDriftConfiguration) {
+ this.newDriftDefinition = new DriftDefinition(newDriftConfiguration);
+ }
+
+ public void cancel() {
+ // nothing to do
+ }
+
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizard.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizard.java
deleted file mode 100644
index 5af4465..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizard.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift.wizard;
-
-import java.util.ArrayList;
-
-import com.google.gwt.user.client.rpc.AsyncCallback;
-
-import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.criteria.ResourceCriteria;
-import org.rhq.core.domain.criteria.ResourceTypeCriteria;
-import org.rhq.core.domain.resource.Resource;
-import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.core.domain.util.PageList;
-import org.rhq.enterprise.gui.coregui.client.CoreGUI;
-import org.rhq.enterprise.gui.coregui.client.components.table.Table;
-import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardStep;
-import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
-import org.rhq.enterprise.gui.coregui.client.util.message.Message;
-
-/**
- * @author Jay Shaughnessy
- */
-public class DriftAddConfigWizard extends AbstractDriftAddConfigWizard {
-
- private Table<?> table;
-
- public DriftAddConfigWizard(EntityContext context, ResourceType type, Table<?>
table) {
-
- super(context, type);
- this.table = table;
-
- final ArrayList<WizardStep> steps = new ArrayList<WizardStep>();
-
- steps.add(new DriftAddConfigWizardInfoStep(DriftAddConfigWizard.this));
- steps.add(new DriftAddConfigWizardConfigStep(DriftAddConfigWizard.this));
-
- setSteps(steps);
- }
-
- public String getWindowTitle() {
- return MSG.view_drift_wizard_addDef_windowTitle();
- }
-
- public String getTitle() {
- return MSG.view_drift_wizard_addDef_title(getType().getName());
- }
-
- public String getSubtitle() {
- return null;
- }
-
- public void execute() {
- EntityContext context = getEntityContext();
- switch (context.getType()) {
- case Resource:
-
- ResourceCriteria rc = new ResourceCriteria();
- rc.addFilterId(context.getResourceId());
- rc.fetchResourceType(true);
- GWTServiceLookup.getDriftService().updateDriftConfiguration(context,
getNewDriftConfiguration(),
- new AsyncCallback<Void>() {
- public void onSuccess(Void result) {
- CoreGUI.getMessageCenter().notify(
- new
Message(MSG.view_drift_wizard_addDef_success(getNewDriftConfiguration().getName()),
- Message.Severity.Info));
- getView().closeDialog();
- DriftAddConfigWizard.this.table.refresh();
- }
-
- public void onFailure(Throwable caught) {
- CoreGUI.getErrorHandler().handleError(
-
MSG.view_drift_wizard_addDef_failure(getNewDriftConfiguration().getName()), caught);
- getView().closeDialog();
- }
- });
-
- break;
-
- default:
- throw new IllegalArgumentException("Entity Context Type not supported
[" + context + "]");
- }
-
- }
-
- public static void showWizard(final EntityContext context, final Table<?>
table) {
- assert context != null;
-
- switch (context.getType()) {
- case Resource:
- ResourceCriteria rc = new ResourceCriteria();
- rc.addFilterId(context.getResourceId());
- rc.fetchResourceType(true);
- GWTServiceLookup.getResourceService().findResourcesByCriteria(rc, new
AsyncCallback<PageList<Resource>>() {
- public void onSuccess(PageList<Resource> result) {
- if (result.isEmpty()) {
- throw new IllegalArgumentException("Entity not found ["
+ context + "]");
- }
-
- final Resource resource = result.get(0);
-
- // bypass type cache because this is infrequent an we don't need
to cache the
- // drift config templates
- ResourceTypeCriteria rtc = new ResourceTypeCriteria();
- rtc.addFilterId(resource.getResourceType().getId());
- rtc.fetchDriftConfigurationTemplates(true);
-
GWTServiceLookup.getResourceTypeGWTService().findResourceTypesByCriteria(rtc,
- new AsyncCallback<PageList<ResourceType>>() {
- public void onSuccess(PageList<ResourceType> result) {
- if (result.isEmpty()) {
- throw new IllegalArgumentException("Resource
Type not found ["
- + resource.getResourceType().getId() +
"]");
- }
-
- DriftAddConfigWizard wizard = new
DriftAddConfigWizard(context, result.get(0), table);
- wizard.startWizard();
- }
-
- public void onFailure(Throwable caught) {
-
CoreGUI.getErrorHandler().handleError(MSG.widget_typeTree_loadFail(), caught);
- }
- });
-
- }
-
- public void onFailure(Throwable caught) {
-
CoreGUI.getErrorHandler().handleError(MSG.view_inventory_resources_loadFailed(), caught);
- }
- });
-
- break;
-
- default:
- throw new IllegalArgumentException("Entity Context Type not supported
[" + context + "]");
- }
- }
-
- @Override
- public void cancel() {
- super.cancel();
- }
-
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardConfigStep.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardConfigStep.java
deleted file mode 100644
index c450086..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardConfigStep.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift.wizard;
-
-import com.smartgwt.client.types.Overflow;
-import com.smartgwt.client.widgets.Canvas;
-
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition;
-import
org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor;
-import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
-
-/**
- * @author Jay Shaughnessy
- */
-public class DriftAddConfigWizardConfigStep extends AbstractWizardStep {
-
- private LocatableVLayout vLayout;
- private ConfigurationEditor editor;
- AbstractDriftAddConfigWizard wizard;
-
- public DriftAddConfigWizardConfigStep(AbstractDriftAddConfigWizard wizard) {
- this.wizard = wizard;
- }
-
- public Canvas getCanvas(Locatable parent) {
- // This VLayout allows us to set overflow on it and be able to scroll the config
editor but always
- // be able to see the wizard's next/cancel buttons. This vlayout also
provides for easier expansion if we add more items.
- if (vLayout == null) {
- String locatorId = (null == parent) ? "DriftConfig" :
parent.extendLocatorId("DriftConfig");
- vLayout = new LocatableVLayout(locatorId);
-
- vLayout.setOverflow(Overflow.AUTO);
-
- ConfigurationDefinition def = DriftConfigurationDefinition.getInstance();
- Configuration startingConfig = wizard.getNewStartingConfiguration();
- editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"),
def, startingConfig);
- vLayout.addMember(editor);
- }
-
- return vLayout;
- }
-
- public boolean nextPage() {
- if (editor != null && editor.validate()) {
- wizard.setNewConfiguration(editor.getConfiguration());
- wizard.execute();
- return true;
- }
-
- return false;
- }
-
- public String getName() {
- return MSG.widget_resourceFactoryWizard_editConfigStepName();
- }
-}
\ No newline at end of file
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardInfoStep.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardInfoStep.java
deleted file mode 100644
index 6abc7e6..0000000
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddConfigWizardInfoStep.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * RHQ Management Platform
- * Copyright (C) 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.gui.coregui.client.drift.wizard;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import com.smartgwt.client.types.Alignment;
-import com.smartgwt.client.types.TitleOrientation;
-import com.smartgwt.client.widgets.Canvas;
-import com.smartgwt.client.widgets.form.fields.FormItem;
-import com.smartgwt.client.widgets.form.fields.SelectItem;
-import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
-import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
-
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
-import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep;
-import org.rhq.enterprise.gui.coregui.client.util.FormUtility;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
-
-/**
- * @author Jay Shaughnessy
- */
-public class DriftAddConfigWizardInfoStep extends AbstractWizardStep {
-
- private LocatableDynamicForm form;
- private AbstractDriftAddConfigWizard wizard;
- private Map<String, ConfigurationTemplate> templates;
-
- public DriftAddConfigWizardInfoStep(AbstractDriftAddConfigWizard wizard) {
- this.wizard = wizard;
- }
-
- public Canvas getCanvas(Locatable parent) {
- if (form == null) {
-
- if (parent != null) {
- form = new
LocatableDynamicForm(parent.extendLocatorId("DriftAddConfigInfo"));
- } else {
- form = new LocatableDynamicForm("DriftAddConfigInfo");
- }
- form.setNumCols(1);
- List<FormItem> formItems = new ArrayList<FormItem>(2);
-
- SelectItem templateSelect = new SelectItem("template",
MSG.view_drift_wizard_addDef_templatePrompt());
- templateSelect.setTitleOrientation(TitleOrientation.TOP);
- templateSelect.setAlign(Alignment.LEFT);
- templateSelect.setWidth(300);
- templateSelect.setRequired(true);
- FormUtility.addContextualHelp(templateSelect,
MSG.view_drift_wizard_addDef_templateHelp());
-
- Set<ConfigurationTemplate> templates =
wizard.getType().getDriftConfigurationTemplates();
- final HashMap<String, ConfigurationTemplate> templatesMap = new
HashMap<String, ConfigurationTemplate>(
- templates.size());
- if (!templates.isEmpty()) {
- for (ConfigurationTemplate template : templates) {
- templatesMap.put(template.getName(), template);
- }
- } else {
- // there should be at least one template for any resource type that
supports drift monitoring
- throw new IllegalStateException(
- "At least one drift configuration template should exist for the
resource type");
- }
-
- Set<String> templatesMapKeySet = templatesMap.keySet();
- String[] templatesMapKeySetArray = templatesMapKeySet.toArray(new
String[templatesMap.size()]);
- templateSelect.setValueMap(templatesMapKeySetArray);
- if (templatesMapKeySetArray.length == 1) {
- // there is only one, select it for the user
- String theOne = templatesMapKeySetArray[0];
- templateSelect.setValue(theOne);
-
wizard.setNewStartingConfiguration(templatesMap.get(theOne).createConfiguration());
- }
- templateSelect.addChangedHandler(new ChangedHandler() {
- public void onChanged(ChangedEvent event) {
- Object value = event.getValue();
- if (value == null) {
- value = "";
- }
-
wizard.setNewStartingConfiguration(templatesMap.get(value).createConfiguration());
- }
- });
-
- formItems.add(templateSelect);
-
- form.setItems(formItems.toArray(new FormItem[formItems.size()]));
- }
-
- return form;
- }
-
- public boolean nextPage() {
- return form.validate();
- }
-
- public String getName() {
- return MSG.view_drift_wizard_addDef_infoStepName();
- }
-
- public Configuration getStartingConfiguration() {
- String template = form.getValueAsString("template");
- return templates.get(template).createConfiguration();
- }
-}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizard.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizard.java
new file mode 100644
index 0000000..d61ee51
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizard.java
@@ -0,0 +1,160 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift.wizard;
+
+import java.util.ArrayList;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+
+import org.rhq.core.domain.common.EntityContext;
+import org.rhq.core.domain.criteria.ResourceCriteria;
+import org.rhq.core.domain.criteria.ResourceTypeCriteria;
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.domain.util.PageList;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.components.table.Table;
+import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardStep;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+import org.rhq.enterprise.gui.coregui.client.util.message.Message;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public class DriftAddDefinitionWizard extends AbstractDriftAddDefinitionWizard {
+
+ private Table<?> table;
+
+ public DriftAddDefinitionWizard(EntityContext context, ResourceType type,
Table<?> table) {
+
+ super(context, type);
+ this.table = table;
+
+ final ArrayList<WizardStep> steps = new ArrayList<WizardStep>();
+
+ steps.add(new DriftAddDefinitionWizardInfoStep(DriftAddDefinitionWizard.this));
+ steps.add(new
DriftAddDefinitionWizardConfigStep(DriftAddDefinitionWizard.this));
+
+ setSteps(steps);
+ }
+
+ public String getWindowTitle() {
+ return MSG.view_drift_wizard_addDef_windowTitle();
+ }
+
+ public String getTitle() {
+ return MSG.view_drift_wizard_addDef_title(getType().getName());
+ }
+
+ public String getSubtitle() {
+ return null;
+ }
+
+ public void execute() {
+ EntityContext context = getEntityContext();
+ switch (context.getType()) {
+ case Resource:
+
+ ResourceCriteria rc = new ResourceCriteria();
+ rc.addFilterId(context.getResourceId());
+ rc.fetchResourceType(true);
+ GWTServiceLookup.getDriftService().updateDriftDefinition(context,
getNewDriftDefinition(),
+ new AsyncCallback<Void>() {
+ public void onSuccess(Void result) {
+ CoreGUI.getMessageCenter().notify(
+ new
Message(MSG.view_drift_wizard_addDef_success(getNewDriftDefinition().getName()),
+ Message.Severity.Info));
+ getView().closeDialog();
+ DriftAddDefinitionWizard.this.table.refresh();
+ }
+
+ public void onFailure(Throwable caught) {
+ CoreGUI.getErrorHandler().handleError(
+
MSG.view_drift_wizard_addDef_failure(getNewDriftDefinition().getName()), caught);
+ getView().closeDialog();
+ }
+ });
+
+ break;
+
+ default:
+ throw new IllegalArgumentException("Entity Context Type not supported
[" + context + "]");
+ }
+
+ }
+
+ public static void showWizard(final EntityContext context, final Table<?>
table) {
+ assert context != null;
+
+ switch (context.getType()) {
+ case Resource:
+ ResourceCriteria rc = new ResourceCriteria();
+ rc.addFilterId(context.getResourceId());
+ rc.fetchResourceType(true);
+ GWTServiceLookup.getResourceService().findResourcesByCriteria(rc, new
AsyncCallback<PageList<Resource>>() {
+ public void onSuccess(PageList<Resource> result) {
+ if (result.isEmpty()) {
+ throw new IllegalArgumentException("Entity not found ["
+ context + "]");
+ }
+
+ final Resource resource = result.get(0);
+
+ // bypass type cache because this is infrequent an we don't need
to cache the
+ // drift def templates
+ ResourceTypeCriteria rtc = new ResourceTypeCriteria();
+ rtc.addFilterId(resource.getResourceType().getId());
+ rtc.fetchDriftDefinitionTemplates(true);
+
GWTServiceLookup.getResourceTypeGWTService().findResourceTypesByCriteria(rtc,
+ new AsyncCallback<PageList<ResourceType>>() {
+ public void onSuccess(PageList<ResourceType> result) {
+ if (result.isEmpty()) {
+ throw new IllegalArgumentException("Resource
Type not found ["
+ + resource.getResourceType().getId() +
"]");
+ }
+
+ DriftAddDefinitionWizard wizard = new
DriftAddDefinitionWizard(context, result.get(0),
+ table);
+ wizard.startWizard();
+ }
+
+ public void onFailure(Throwable caught) {
+
CoreGUI.getErrorHandler().handleError(MSG.widget_typeTree_loadFail(), caught);
+ }
+ });
+
+ }
+
+ public void onFailure(Throwable caught) {
+
CoreGUI.getErrorHandler().handleError(MSG.view_inventory_resources_loadFailed(), caught);
+ }
+ });
+
+ break;
+
+ default:
+ throw new IllegalArgumentException("Entity Context Type not supported
[" + context + "]");
+ }
+ }
+
+ @Override
+ public void cancel() {
+ super.cancel();
+ }
+
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardConfigStep.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardConfigStep.java
new file mode 100644
index 0000000..52a8667
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardConfigStep.java
@@ -0,0 +1,76 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift.wizard;
+
+import com.smartgwt.client.types.Overflow;
+import com.smartgwt.client.widgets.Canvas;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition;
+import
org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor;
+import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public class DriftAddDefinitionWizardConfigStep extends AbstractWizardStep {
+
+ private LocatableVLayout vLayout;
+ private ConfigurationEditor editor;
+ AbstractDriftAddDefinitionWizard wizard;
+
+ public DriftAddDefinitionWizardConfigStep(AbstractDriftAddDefinitionWizard wizard) {
+ this.wizard = wizard;
+ }
+
+ public Canvas getCanvas(Locatable parent) {
+ // This VLayout allows us to set overflow on it and be able to scroll the config
editor but always
+ // be able to see the wizard's next/cancel buttons. This vlayout also
provides for easier expansion if we add more items.
+ if (vLayout == null) {
+ String locatorId = (null == parent) ? "DriftDefConfig" :
parent.extendLocatorId("DriftDefConfig");
+ vLayout = new LocatableVLayout(locatorId);
+
+ vLayout.setOverflow(Overflow.AUTO);
+
+ ConfigurationDefinition def = DriftConfigurationDefinition.getInstance();
+ Configuration startingConfig = wizard.getNewStartingConfiguration();
+ editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"),
def, startingConfig);
+ vLayout.addMember(editor);
+ }
+
+ return vLayout;
+ }
+
+ public boolean nextPage() {
+ if (editor != null && editor.validate()) {
+ wizard.setNewConfiguration(editor.getConfiguration());
+ wizard.execute();
+ return true;
+ }
+
+ return false;
+ }
+
+ public String getName() {
+ return MSG.widget_resourceFactoryWizard_editConfigStepName();
+ }
+}
\ No newline at end of file
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardInfoStep.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardInfoStep.java
new file mode 100644
index 0000000..5cacee2
--- /dev/null
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/wizard/DriftAddDefinitionWizardInfoStep.java
@@ -0,0 +1,125 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.gui.coregui.client.drift.wizard;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.smartgwt.client.types.Alignment;
+import com.smartgwt.client.types.TitleOrientation;
+import com.smartgwt.client.widgets.Canvas;
+import com.smartgwt.client.widgets.form.fields.FormItem;
+import com.smartgwt.client.widgets.form.fields.SelectItem;
+import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
+import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
+import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep;
+import org.rhq.enterprise.gui.coregui.client.util.FormUtility;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
+
+/**
+ * @author Jay Shaughnessy
+ */
+public class DriftAddDefinitionWizardInfoStep extends AbstractWizardStep {
+
+ private LocatableDynamicForm form;
+ private AbstractDriftAddDefinitionWizard wizard;
+ private Map<String, ConfigurationTemplate> templates;
+
+ public DriftAddDefinitionWizardInfoStep(AbstractDriftAddDefinitionWizard wizard) {
+ this.wizard = wizard;
+ }
+
+ public Canvas getCanvas(Locatable parent) {
+ if (form == null) {
+
+ if (parent != null) {
+ form = new
LocatableDynamicForm(parent.extendLocatorId("DriftAddDefInfo"));
+ } else {
+ form = new LocatableDynamicForm("DriftAddDefInfo");
+ }
+ form.setNumCols(1);
+ List<FormItem> formItems = new ArrayList<FormItem>(2);
+
+ SelectItem templateSelect = new SelectItem("template",
MSG.view_drift_wizard_addDef_templatePrompt());
+ templateSelect.setTitleOrientation(TitleOrientation.TOP);
+ templateSelect.setAlign(Alignment.LEFT);
+ templateSelect.setWidth(300);
+ templateSelect.setRequired(true);
+ FormUtility.addContextualHelp(templateSelect,
MSG.view_drift_wizard_addDef_templateHelp());
+
+ Set<ConfigurationTemplate> templates =
wizard.getType().getDriftDefinitionTemplates();
+ final HashMap<String, ConfigurationTemplate> templatesMap = new
HashMap<String, ConfigurationTemplate>(
+ templates.size());
+ if (!templates.isEmpty()) {
+ for (ConfigurationTemplate template : templates) {
+ templatesMap.put(template.getName(), template);
+ }
+ } else {
+ // there should be at least one template for any resource type that
supports drift monitoring
+ throw new IllegalStateException(
+ "At least one drift definition template should exist for the
resource type");
+ }
+
+ Set<String> templatesMapKeySet = templatesMap.keySet();
+ String[] templatesMapKeySetArray = templatesMapKeySet.toArray(new
String[templatesMap.size()]);
+ templateSelect.setValueMap(templatesMapKeySetArray);
+ if (templatesMapKeySetArray.length == 1) {
+ // there is only one, select it for the user
+ String theOne = templatesMapKeySetArray[0];
+ templateSelect.setValue(theOne);
+
wizard.setNewStartingConfiguration(templatesMap.get(theOne).createConfiguration());
+ }
+ templateSelect.addChangedHandler(new ChangedHandler() {
+ public void onChanged(ChangedEvent event) {
+ Object value = event.getValue();
+ if (value == null) {
+ value = "";
+ }
+
wizard.setNewStartingConfiguration(templatesMap.get(value).createConfiguration());
+ }
+ });
+
+ formItems.add(templateSelect);
+
+ form.setItems(formItems.toArray(new FormItem[formItems.size()]));
+ }
+
+ return form;
+ }
+
+ public boolean nextPage() {
+ return form.validate();
+ }
+
+ public String getName() {
+ return MSG.view_drift_wizard_addDef_infoStepName();
+ }
+
+ public Configuration getStartingConfiguration() {
+ String template = form.getValueAsString("template");
+ return templates.get(template).createConfiguration();
+ }
+}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
index d4faced..0b99c87 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java
@@ -22,13 +22,13 @@ import com.google.gwt.user.client.rpc.RemoteService;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftComposite;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.drift.FileDiffReport;
@@ -42,24 +42,23 @@ public interface DriftGWTService extends RemoteService {
DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria)
throws RuntimeException;
/**
- * Delete all named drift configurations for the specified context if the current
user has permission to do so (i.e. either
+ * Delete all named drift definitions for the specified context if the current user
has permission to do so (i.e. either
* the MANAGE_INVENTORY global permission, or the MANAGE_DRIFT permission for all
corresponding resources).
*
* @param entityContext the context for deletion
- * @param driftConfigNames the names of the configs to delete
- * @return the number of drift configs deleted
+ * @param driftDefNames the names of the definitions to delete
+ * @return the number of drift definisions deleted
*/
- int deleteDriftConfigurationsByContext(EntityContext entityContext, String[]
driftConfigNames)
- throws RuntimeException;
+ int deleteDriftDefinitionsByContext(EntityContext entityContext, String[]
driftDefNames) throws RuntimeException;
/**
- * One time on-demand request to detect drift on the specified entities, using the
supplied config.
+ * One time on-demand request to detect drift on the specified entities, using the
supplied def.
*
* @param entityContext
- * @param driftConfig
+ * @param driftDef
* @throws RuntimeException
*/
- void detectDrift(EntityContext entityContext, DriftConfiguration driftConfig) throws
RuntimeException;
+ void detectDrift(EntityContext entityContext, DriftDefinition driftDef) throws
RuntimeException;
/**
* Find all drift changesets that match the specified criteria.
@@ -74,14 +73,13 @@ public interface DriftGWTService extends RemoteService {
PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria
criteria) throws RuntimeException;
/**
- * Find all drift configurations that match the specified criteria.
+ * Find all drift definitions that match the specified criteria.
*
* @param criteria the criteria
*
- * @return all drift configurations that matches the specified criteria
+ * @return all drift definitions that matches the specified criteria
*/
- PageList<DriftConfiguration>
findDriftConfigurationsByCriteria(DriftConfigurationCriteria criteria)
- throws RuntimeException;
+ PageList<DriftDefinition>
findDriftDefinitionsByCriteria(DriftDefinitionCriteria criteria) throws RuntimeException;
/**
* Find all drifts that match the specified criteria.
@@ -93,28 +91,28 @@ public interface DriftGWTService extends RemoteService {
PageList<? extends Drift<?, ?>> findDriftsByCriteria(GenericDriftCriteria
criteria) throws RuntimeException;
/**
- * Get the specified drift configuration.
+ * Get the specified drift definition.
*
- * @param driftConfigId
+ * @param driftDefId
* @return
* @throws RuntimeException
*/
- DriftConfiguration getDriftConfiguration(int driftConfigId) throws RuntimeException;
+ DriftDefinition getDriftDefinition(int driftDefId) throws RuntimeException;
/**
- * Update the provided driftConfig (identified by name) on the specified
EntityContext. If it exists it will be replaced. If not it will
+ * Update the provided driftDef (identified by name) on the specified EntityContext.
If it exists it will be replaced. If not it will
* be added. Agents, if available, will be notified of the change.
*
* @param entityContext
- * @param driftConfig
+ * @param driftDef
*/
- void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration
driftConfig) throws RuntimeException;
+ void updateDriftDefinition(EntityContext entityContext, DriftDefinition driftDef)
throws RuntimeException;
String getDriftFileBits(String hash) throws RuntimeException;
- FileDiffReport generateUnifiedDiff(Drift drift) throws RuntimeException;
+ FileDiffReport generateUnifiedDiff(Drift<?, ?> drift) throws RuntimeException;
- boolean isBinaryFile(Drift drift) throws RuntimeException;
+ boolean isBinaryFile(Drift<?, ?> drift) throws RuntimeException;
DriftDetails getDriftDetails(String driftId) throws RuntimeException;
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java
index 1ecd83f..3b553ca 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java
@@ -51,7 +51,7 @@ import
org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTab;
import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSelectedEvent;
import org.rhq.enterprise.gui.coregui.client.components.view.ViewFactory;
import org.rhq.enterprise.gui.coregui.client.components.view.ViewName;
-import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftConfigurationView;
+import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftDefinitionsView;
import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftHistoryView;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.inventory.InventoryView;
@@ -471,7 +471,7 @@ public class ResourceGroupDetailView extends
AbstractTwoLevelTabSetView<Resource
updateSubTab(this.driftTab, this.driftConfig, true, true, new ViewFactory()
{
@Override
public Canvas createView() {
- return
ResourceDriftConfigurationView.get(driftConfig.extendLocatorId("View"), null);
+ return
ResourceDriftDefinitionsView.get(driftConfig.extendLocatorId("View"), null);
}
});
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
index ae39e50..40d9388 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
@@ -51,7 +51,7 @@ import
org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTab;
import org.rhq.enterprise.gui.coregui.client.components.view.ViewFactory;
import org.rhq.enterprise.gui.coregui.client.components.view.ViewName;
import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftChangeSetsView;
-import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftConfigurationView;
+import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftDefinitionsView;
import org.rhq.enterprise.gui.coregui.client.drift.ResourceDriftHistoryView;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.inventory.InventoryView;
@@ -540,7 +540,7 @@ public class ResourceDetailView extends
AbstractTwoLevelTabSetView<ResourceCompo
updateSubTab(this.driftTab, this.driftDefinitions, true, true, new
ViewFactory() {
@Override
public Canvas createView() {
- return
ResourceDriftConfigurationView.get(driftDefinitions.extendLocatorId("View"),
+ return
ResourceDriftDefinitionsView.get(driftDefinitions.extendLocatorId("View"),
resourceComposite);
}
});
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java
index d9689aa..b9cd91b 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypeRepository.java
@@ -247,7 +247,7 @@ public class ResourceTypeRepository {
criteria.fetchSubCategory(true);
break;
case driftConfigurationTemplates:
- criteria.fetchDriftConfigurationTemplates(true);
+ criteria.fetchDriftDefinitionTemplates(true);
break;
default:
Log.error("ERROR: metadataType " + metadataType.name()
@@ -353,12 +353,12 @@ public class ResourceTypeRepository {
cachedType.setSubCategory(type.getSubCategory());
break;
case driftConfigurationTemplates:
- if (cachedType.getDriftConfigurationTemplates() !=
null) {
-
cachedType.getDriftConfigurationTemplates().clear(); // remove any old ones hanging
around
+ if (cachedType.getDriftDefinitionTemplates() != null)
{
+ cachedType.getDriftDefinitionTemplates().clear();
// remove any old ones hanging around
}
- if (type.getDriftConfigurationTemplates() != null) {
- for (ConfigurationTemplate ct :
type.getDriftConfigurationTemplates()) {
-
cachedType.addDriftConfigurationTemplate(ct);
+ if (type.getDriftDefinitionTemplates() != null) {
+ for (ConfigurationTemplate ct :
type.getDriftDefinitionTemplates()) {
+ cachedType.addDriftDefinitionTemplate(ct);
}
}
break;
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestDataSourceResponseStatisticsView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestDataSourceResponseStatisticsView.java
index 83a8579..26a7177 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestDataSourceResponseStatisticsView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestDataSourceResponseStatisticsView.java
@@ -162,7 +162,7 @@ public class TestDataSourceResponseStatisticsView extends Table {
timerTitleString = null;
}
- setTableTitle(getTableTitle());
+ updateTitleCanvas(getTableTitle());
if (window != null) {
window.setTitle(getTableTitle());
}
@@ -263,7 +263,7 @@ public class TestDataSourceResponseStatisticsView extends Table {
timerTitleString = " (refresh every " + timeout +
"s)";
}
- setTableTitle(getTableTitle());
+ updateTitleCanvas(getTableTitle());
if (window != null) {
window.setTitle(getTableTitle());
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestRemoteServiceStatisticsView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestRemoteServiceStatisticsView.java
index 8195198..af14f3b 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestRemoteServiceStatisticsView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestRemoteServiceStatisticsView.java
@@ -200,13 +200,13 @@ public class TestRemoteServiceStatisticsView extends Table {
refreshOnPageChange = false;
if (timeout.intValue() == -1) {
- setTableTitle(TABLE_TITLE);
+ updateTitleCanvas(TABLE_TITLE);
} else if (timeout.intValue() == 0) {
refreshOnPageChange = true;
- setTableTitle(TABLE_TITLE + " (refresh on page
change)");
+ updateTitleCanvas(TABLE_TITLE + " (refresh on page
change)");
} else {
refreshTimer.scheduleRepeating(timeout.intValue() * 1000);
- setTableTitle(TABLE_TITLE + " (refresh every " +
timeout + "s)");
+ updateTitleCanvas(TABLE_TITLE + " (refresh every "
+ timeout + "s)");
}
refreshTableInfo();
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java
index 1a6b896..be1edfc 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java
@@ -138,7 +138,7 @@ public class MessageCenterView extends Table implements
MessageCenter.MessageLis
protected void configureTable() {
getListGrid().setEmptyMessage(MSG.view_messageCenter_noRecentMessages());
-
setTableTitle(MSG.view_messageCenter_lastNMessages(String.valueOf(CoreGUI.getMessageCenter().getMaxMessages())));
+
updateTitleCanvas(MSG.view_messageCenter_lastNMessages(String.valueOf(CoreGUI.getMessageCenter().getMaxMessages())));
ListGridField severityField = new ListGridField(FIELD_SEVERITY);
severityField.setType(ListGridFieldType.ICON);
@@ -259,7 +259,7 @@ public class MessageCenterView extends Table implements
MessageCenter.MessageLis
try {
Integer maxSize = (Integer) actionValue;
CoreGUI.getMessageCenter().setMaxMessages(maxSize.intValue());
-
setTableTitle(MSG.view_messageCenter_lastNMessages(maxSize.toString()));
+
updateTitleCanvas(MSG.view_messageCenter_lastNMessages(maxSize.toString()));
refresh();
} catch (Throwable e) {
Log.error("Cannot set max messages", e);
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
index 55f9f7e..6e41279 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java
@@ -20,13 +20,13 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftComposite;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.drift.FileDiffReport;
@@ -45,22 +45,22 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
private DriftManagerLocal driftManager = LookupUtil.getDriftManager();
@Override
- public int deleteDriftConfigurationsByContext(EntityContext entityContext, String[]
driftConfigNames)
+ public int deleteDriftDefinitionsByContext(EntityContext entityContext, String[]
driftDefinitionNames)
throws RuntimeException {
try {
- for (String driftConfigName : driftConfigNames) {
- this.driftManager.deleteDriftConfiguration(getSessionSubject(),
entityContext, driftConfigName);
+ for (String driftDefName : driftDefinitionNames) {
+ this.driftManager.deleteDriftDefinition(getSessionSubject(),
entityContext, driftDefName);
}
- return driftConfigNames.length;
+ return driftDefinitionNames.length;
} catch (Throwable t) {
throw getExceptionToThrowToClient(t);
}
}
@Override
- public void detectDrift(EntityContext entityContext, DriftConfiguration driftConfig)
throws RuntimeException {
+ public void detectDrift(EntityContext entityContext, DriftDefinition driftDef) throws
RuntimeException {
try {
- this.driftManager.detectDrift(getSessionSubject(), entityContext,
driftConfig);
+ this.driftManager.detectDrift(getSessionSubject(), entityContext, driftDef);
} catch (Throwable t) {
throw getExceptionToThrowToClient(t);
}
@@ -101,12 +101,12 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
}
@Override
- public PageList<DriftConfiguration>
findDriftConfigurationsByCriteria(DriftConfigurationCriteria criteria)
+ public PageList<DriftDefinition>
findDriftDefinitionsByCriteria(DriftDefinitionCriteria criteria)
throws RuntimeException {
try {
- PageList<DriftConfiguration> results =
driftManager.findDriftConfigurationsByCriteria(getSessionSubject(),
+ PageList<DriftDefinition> results =
driftManager.findDriftDefinitionsByCriteria(getSessionSubject(),
criteria);
- return SerialUtility.prepare(results,
"DriftService.findDriftConfigurationsByCriteria");
+ return SerialUtility.prepare(results,
"DriftService.findDriftDefinitionsByCriteria");
} catch (Throwable t) {
throw getExceptionToThrowToClient(t);
}
@@ -123,20 +123,19 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
}
@Override
- public DriftConfiguration getDriftConfiguration(int driftConfigId) throws
RuntimeException {
+ public DriftDefinition getDriftDefinition(int driftDefId) throws RuntimeException {
try {
- DriftConfiguration driftConfig =
driftManager.getDriftConfiguration(getSessionSubject(), driftConfigId);
- return SerialUtility.prepare(driftConfig,
"DriftService.getDriftConfiguration");
+ DriftDefinition driftDef =
driftManager.getDriftDefinition(getSessionSubject(), driftDefId);
+ return SerialUtility.prepare(driftDef,
"DriftService.getDriftDefinition");
} catch (Throwable t) {
throw getExceptionToThrowToClient(t);
}
}
@Override
- public void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration
driftConfig)
- throws RuntimeException {
+ public void updateDriftDefinition(EntityContext entityContext, DriftDefinition
driftDef) throws RuntimeException {
try {
- this.driftManager.updateDriftConfiguration(getSessionSubject(),
entityContext, driftConfig);
+ this.driftManager.updateDriftDefinition(getSessionSubject(), entityContext,
driftDef);
} catch (Throwable t) {
throw getExceptionToThrowToClient(t);
}
@@ -152,7 +151,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
}
@Override
- public FileDiffReport generateUnifiedDiff(Drift drift) throws RuntimeException {
+ public FileDiffReport generateUnifiedDiff(Drift<?, ?> drift) throws
RuntimeException {
try {
return driftManager.generateUnifiedDiff(drift);
} catch (Throwable t) {
@@ -171,7 +170,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl
implements Drift
}
@Override
- public boolean isBinaryFile(Drift drift) throws RuntimeException {
+ public boolean isBinaryFile(Drift<?, ?> drift) throws RuntimeException {
try {
return driftManager.isBinaryFile(drift);
} catch (Throwable t) {
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 9e4311a..bbb8889 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
@@ -25,6 +25,7 @@ common_button_disable = Disable
common_button_edit = Edit
common_button_enable = Enable
common_button_finish = Finish
+common_button_fixedWidth = Fixed Width
common_button_import = Import
common_button_new = New
common_button_next = Next
@@ -34,6 +35,7 @@ common_button_purgeAll = Purge All
common_button_refresh = Refresh
common_button_reset = Reset
common_button_save = Save
+common_button_scaleToFit = Scale To Fit
common_button_schedule = Schedule
common_button_search = Search
common_button_set = Set
@@ -55,6 +57,7 @@ common_label_ago = ago
common_label_all = ALL
common_label_all_resources = all resources
common_label_day = day
+common_label_filters = Filters
common_label_hour = hour
common_label_item = item
common_label_items = items
@@ -1117,12 +1120,14 @@ view_dashboards_portlets_refresh_success1 = Updated interval for
portlets that a
view_dashboards_portlets_refresh_success2 = Stopping reload for portlets that
auto-refresh
view_dashboards_title = Dashboard
view_drift_button_detectNow = Detect Now
+view_drift_carousel_sizeFilterLabel = Number of Snapshots
+view_drift_carousel_startFilterLabel = Starting Snapshot
view_drift_category_fileAdded = File Added
view_drift_category_fileChanged = File Changed
view_drift_category_fileNew = Newly Detected
view_drift_category_fileRemoved = File Removed
-view_drift_delete_configConfirm = Delete the selected drift detection definition(s)?
-view_drift_delete_configConfirmAll = Delete all drift detection definition?
+view_drift_delete_defConfirm = Delete the selected drift detection definition(s)?
+view_drift_delete_defConfirmAll = Delete all drift detection definition?
view_drift_failure_deleteDefs = Failed to delete some or all drift detection
definitions.
view_drift_failure_detectNow = Failed to submit drift detection run request
view_drift_failure_load = Failed to fetch drift instances
@@ -1132,7 +1137,7 @@ view_drift_snapshots_tree_loadDefFailure = Failed to load drift
detection defini
view_drift_snapshots_tree_loadFailure = Failed to load drift snapshot tree.
view_drift_success_defUpdated = Drift detection definition updated and will affect the
next detection run as applicable.
view_drift_success_delete = Successfully deleted {0} drift instances
-view_drift_success_deleteConfigs = Successfully deleted {0} drift detection definitions
+view_drift_success_deleteDefs = Successfully deleted {0} drift detection definitions
view_drift_success_detectNow = Successfully submitted drift detection run request
view_drift_table_baseDir = Base Directory
view_drift_table_driftHandlingMode = Drift Handling
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 2c84b0b..a3a5d9f 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
@@ -27,6 +27,7 @@ common_button_disable = Deaktivieren
common_button_edit = Bearbeiten
common_button_enable = Aktivieren
common_button_finish = Beenden
+##common_button_fixedWidth = Fixed Width
common_button_import = Importieren
common_button_new = Neu
common_button_next = Weiter
@@ -36,6 +37,7 @@ common_button_purgeAll = Alle löschen
common_button_refresh = Neu laden
common_button_reset = Zurücksetzen
common_button_save = Speichern
+##common_button_scaleToFit = Scale To Fit
common_button_schedule = Planen
common_button_search = Suchen
common_button_set = Setzen
@@ -57,6 +59,7 @@ common_calendar_september_short = Sept
common_label_all = ALLE
common_label_all_resources = Alle Ressourcen
common_label_day = Tag
+##common_label_filters = Filters
common_label_hour = Stunde
common_label_item = Eintrag
common_label_items = Einträge
@@ -949,12 +952,14 @@ view_dashboardsManager_message_title_details = <h1>Willkommen
bei RHQ</h1>\n<p>D
view_dashboards_confirm1 = Sind Sie sicher, dass Sie löschen möchten
view_dashboards_title = Dashboard
##view_drift_button_detectNow = Detect Now
+##view_drift_carousel_sizeFilterLabel = Number of Snapshots
+##view_drift_carousel_startFilterLabel = Starting Snapshot
##view_drift_category_fileAdded = File Added
##view_drift_category_fileChanged = File Changed
##view_drift_category_fileNew = Newly Detected
##view_drift_category_fileRemoved = File Removed
-##view_drift_delete_configConfirm = Delete the selected drift detection definition(s)?
-##view_drift_delete_configConfirmAll = Delete all drift detection definition?
+view_drift_delete_defConfirm = Delete the selected drift detection definition(s)?
+view_drift_delete_defConfirmAll = Delete all drift detection definition?
##view_drift_failure_deleteDefs = Failed to delete some or all drift detection
definitions.
##view_drift_failure_detectNow = Failed to submit drift detection run request
##view_drift_failure_load = Failed to fetch drift instances
@@ -964,7 +969,7 @@ view_dashboards_title = Dashboard
##view_drift_snapshots_tree_loadFailure = Failed to load drift snapshot tree.
##view_drift_success_defUpdated = Drift detection definition updated and will affect the
next detection run as applicable.
##view_drift_success_delete = Successfully deleted {0} drift instances
-##view_drift_success_deleteConfigs = Successfully deleted {0} drift detection
definitions
+view_drift_success_deleteDefs = Successfully deleted {0} drift detection definitions
##view_drift_success_detectNow = Successfully submitted drift detection run request
##view_drift_table_baseDir = Base Directory
##view_drift_table_driftHandlingMode = Drift Handling
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 0730e55..6c726ea 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
@@ -27,6 +27,7 @@ common_button_disable = 無効
common_button_edit = 編集
common_button_enable = 有効
common_button_finish = 完了
+##common_button_fixedWidth = Fixed Width
common_button_import = インポート
common_button_new = 新規
common_button_next = 次へ
@@ -36,6 +37,7 @@ common_button_purgeAll = すべてをパージ
common_button_refresh = リフレッシュ
common_button_reset = リセット
common_button_save = 保存
+##common_button_scaleToFit = Scale To Fit
common_button_schedule = スケジュール
common_button_search = 検索
common_button_set = 設定
@@ -57,6 +59,7 @@ common_label_ago = 前
common_label_all = すべての
common_label_all_resources = すべてのリソース
common_label_day = 日
+##common_label_filters = Filters
common_label_hour = 時間
common_label_item = 項目
common_label_items = 項目
@@ -1109,12 +1112,14 @@ view_dashboards_portlets_refresh_success1 = ポートレットの自動リフレ
view_dashboards_portlets_refresh_success2 = 自動リフレッシュするポートレットのリロードを停止しています
view_dashboards_title = ダッシュボード
##view_drift_button_detectNow = Detect Now
+##view_drift_carousel_sizeFilterLabel = Number of Snapshots
+##view_drift_carousel_startFilterLabel = Starting Snapshot
##view_drift_category_fileAdded = File Added
##view_drift_category_fileChanged = File Changed
##view_drift_category_fileNew = Newly Detected
##view_drift_category_fileRemoved = File Removed
-##view_drift_delete_configConfirm = Delete the selected drift detection definition(s)?
-##view_drift_delete_configConfirmAll = Delete all drift detection definition?
+view_drift_delete_defConfirm = Delete the selected drift detection definition(s)?
+view_drift_delete_defConfirmAll = Delete all drift detection definition?
##view_drift_failure_deleteDefs = Failed to delete some or all drift detection
definitions.
##view_drift_failure_detectNow = Failed to submit drift detection run request
##view_drift_failure_load = Failed to fetch drift instances
@@ -1124,7 +1129,7 @@ view_dashboards_title = ダッシュボード
##view_drift_snapshots_tree_loadFailure = Failed to load drift snapshot tree.
##view_drift_success_defUpdated = Drift detection definition updated and will affect the
next detection run as applicable.
##view_drift_success_delete = Successfully deleted {0} drift instances
-##view_drift_success_deleteConfigs = Successfully deleted {0} drift detection
definitions
+view_drift_success_deleteDefs = Successfully deleted {0} drift detection definitions
##view_drift_success_detectNow = Successfully submitted drift detection run request
##view_drift_table_baseDir = Base Directory
##view_drift_table_driftHandlingMode = Drift Handling
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 fe0c5dc..825ef50 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
@@ -25,6 +25,7 @@ common_button_disable = Desabilitar
common_button_edit = Editar
common_button_enable = Habilitar
common_button_finish = Finalizar
+##common_button_fixedWidth = Fixed Width
common_button_import = Importar
common_button_new = Novo
common_button_next = Pr\u00F3ximo
@@ -34,6 +35,7 @@ common_button_purgeAll = Remover Todos
common_button_refresh = Atualizar
common_button_reset = Limpar
common_button_save = Salvar
+##common_button_scaleToFit = Scale To Fit
common_button_schedule = Agendar
common_button_search = Procurar
common_button_set = Definir
@@ -55,6 +57,7 @@ common_calendar_september_short = set
common_label_all = TODOS
common_label_all_resources = todos os recursos
common_label_day = dia
+##common_label_filters = Filters
common_label_hour = hora
common_label_item = item
common_label_items = itens
@@ -1137,12 +1140,14 @@ view_dashboards_portlets_refresh_success1 = Intervalo de
atualiza\u00E7\u00E3o d
view_dashboards_portlets_refresh_success2 = Parando a atualiza\u00E7\u00E3o
autom\u00E1tica dos portlets din\u00E2micos
view_dashboards_title = Dashboard
view_drift_button_detectNow = Detectar agora
+##view_drift_carousel_sizeFilterLabel = Number of Snapshots
+##view_drift_carousel_startFilterLabel = Starting Snapshot
view_drift_category_fileAdded = Arquivo adicionado
view_drift_category_fileChanged = Arquivo alterado
##view_drift_category_fileNew = Newly Detected
##view_drift_category_fileRemoved = Arquivo removido
-##view_drift_delete_configConfirm = Delete the selected drift detection definition(s)?
-##view_drift_delete_configConfirmAll = Delete all drift detection definition?
+view_drift_delete_defConfirm = Delete the selected drift detection definition(s)?
+view_drift_delete_defConfirmAll = Delete all drift detection definition?
##view_drift_failure_deleteDefs = Failed to delete some or all drift detection
definitions.
view_drift_failure_detectNow = Falha ao submeter a requisi��o de detec��o do drift
view_drift_failure_load = Falha ao recuperar os dados do drift
@@ -1152,7 +1157,7 @@ view_drift_failure_load = Falha ao recuperar os dados do drift
##view_drift_snapshots_tree_loadFailure = Failed to load drift snapshot tree.
##view_drift_success_defUpdated = Drift detection definition updated and will affect the
next detection run as applicable.
view_drift_success_delete = Drifts {0} exclu�dos com sucesso!
-##view_drift_success_deleteConfigs = Successfully deleted {0} drift detection
definitions
+view_drift_success_deleteDefs = Successfully deleted {0} drift detection definitions
view_drift_success_detectNow = Requisi��o de detec��o de drift submetida com sucesso.
##view_drift_table_baseDir = Diret�rio Base
##view_drift_table_driftHandlingMode = Drift Handling
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 1905e96..9214c91 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
@@ -25,6 +25,7 @@ common_button_disable = \u7981\u7528
common_button_edit = \u7f16\u8f91
common_button_enable = \u542f\u7528
common_button_finish = \u5b8c\u6210
+##common_button_fixedWidth = Fixed Width
common_button_import = \u5bfc\u5165
common_button_new = \u65b0\u5efa
common_button_next = \u4e0b\u4e00\u6b65
@@ -34,6 +35,7 @@ common_button_purgeAll = \u6e05\u9664\u6240\u6709
common_button_refresh = \u5237\u65b0
common_button_reset = \u91cd\u7f6e
common_button_save = \u4fdd\u5b58
+##common_button_scaleToFit = Scale To Fit
common_button_schedule = \u8ba1\u5212
common_button_search = \u68c0\u7d22
common_button_set = Set
@@ -55,6 +57,7 @@ common_calendar_september_short = \u4e5d\u6708
common_label_all = \u6240\u6709
common_label_all_resources = \u6240\u6709\u8d44\u6e90
common_label_day = \u5929
+##common_label_filters = Filters
common_label_hour = \u5c0f\u65f6
common_label_item = \u9879
common_label_items = \u9879
@@ -1117,12 +1120,14 @@ view_dashboards_portlets_refresh_success1 =
\u6210\u529f\u4fee\u6539portlets\u81
view_dashboards_portlets_refresh_success2 =
\u6210\u529f\u505c\u7528portlets\u81ea\u52a8\u5237\u65b0\u7684\u91cd\u8f7d
view_dashboards_title = \u7edf\u8ba1\u8868\u76d8
##view_drift_button_detectNow = Detect Now
+##view_drift_carousel_sizeFilterLabel = Number of Snapshots
+##view_drift_carousel_startFilterLabel = Starting Snapshot
##view_drift_category_fileAdded = File Added
##view_drift_category_fileChanged = File Changed
##view_drift_category_fileNew = Newly Detected
##view_drift_category_fileRemoved = File Removed
-##view_drift_delete_configConfirm = Delete the selected drift detection definition(s)?
-##view_drift_delete_configConfirmAll = Delete all drift detection definition?
+view_drift_delete_defConfirm = Delete the selected drift detection definition(s)?
+view_drift_delete_defConfirmAll = Delete all drift detection definition?
##view_drift_failure_deleteDefs = Failed to delete some or all drift detection
definitions.
##view_drift_failure_detectNow = Failed to submit drift detection run request
##view_drift_failure_load = Failed to fetch drift instances
@@ -1132,7 +1137,7 @@ view_dashboards_title = \u7edf\u8ba1\u8868\u76d8
##view_drift_snapshots_tree_loadFailure = Failed to load drift snapshot tree.
##view_drift_success_defUpdated = Drift detection definition updated and will affect the
next detection run as applicable.
##view_drift_success_delete = Successfully deleted {0} drift instances
-##view_drift_success_deleteConfigs = Successfully deleted {0} drift detection
definitions
+view_drift_success_deleteDefs = Successfully deleted {0} drift detection definitions
##view_drift_success_detectNow = Successfully submitted drift detection run request
##view_drift_table_baseDir = Base Directory
##view_drift_table_driftHandlingMode = Drift Handling
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/engine/model/DriftCacheElement.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/engine/model/DriftCacheElement.java
index 7527fdc..1abb690 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/engine/model/DriftCacheElement.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/alert/engine/model/DriftCacheElement.java
@@ -65,7 +65,7 @@ public class DriftCacheElement extends
AbstractCacheElement<Object> {
}
if (driftConfigNameRegex != null) {
- if
(!driftConfigNameRegex.matcher(summary.getDriftConfigurationName()).matches()) {
+ if
(!driftConfigNameRegex.matcher(summary.getDriftDefinitionName()).matches()) {
return false; // drift config name did not match, our condition is
false so don't alert
}
}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
index aafd0bb..de0f3bf 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java
@@ -18,6 +18,10 @@
*/
package org.rhq.enterprise.server.drift;
+import static java.util.Arrays.asList;
+import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
+
import java.io.File;
import java.io.InputStream;
import java.util.HashSet;
@@ -37,6 +41,9 @@ import javax.jms.Session;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
+import difflib.DiffUtils;
+import difflib.Patch;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -46,22 +53,22 @@ import org.rhq.core.clientapi.agent.drift.DriftAgentService;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
import org.rhq.core.domain.criteria.DriftCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftComposite;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfigurationComparator;
-import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode;
import org.rhq.core.domain.drift.DriftConfigurationDefinition;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.drift.DriftDefinition;
+import org.rhq.core.domain.drift.DriftDefinitionComparator;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.drift.FileDiffReport;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.drift.DriftDefinitionComparator.CompareMode;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.server.RHQConstants;
@@ -79,13 +86,6 @@ import org.rhq.enterprise.server.util.CriteriaQueryGenerator;
import org.rhq.enterprise.server.util.CriteriaQueryRunner;
import org.rhq.enterprise.server.util.LookupUtil;
-import difflib.DiffUtils;
-import difflib.Patch;
-
-import static java.util.Arrays.asList;
-import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
-
/**
* The SLSB supporting Drift management to clients.
*
@@ -226,7 +226,7 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
- public void detectDrift(Subject subject, EntityContext context, DriftConfiguration
driftConfig) {
+ public void detectDrift(Subject subject, EntityContext context, DriftDefinition
driftDef) {
switch (context.getType()) {
case Resource:
int resourceId = context.getResourceId();
@@ -240,11 +240,11 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
// this is a one-time on-demand call. If it fails throw an exception to make
sure the user knows it
// did not happen. But clean it up a bit if it's a connect exception
try {
- service.detectDrift(resourceId, driftConfig);
+ service.detectDrift(resourceId, driftDef);
} catch (CannotConnectException e) {
throw new IllegalStateException(
"Agent could not be reached and may be down (see server logs for
more). Could not perform drift detection request ["
- + driftConfig + "]");
+ + driftDef + "]");
}
break;
@@ -256,52 +256,52 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
@Override
@TransactionAttribute(NOT_SUPPORTED)
- public void deleteDriftConfiguration(Subject subject, EntityContext entityContext,
String driftConfigName) {
+ public void deleteDriftDefinition(Subject subject, EntityContext entityContext,
String driftDefName) {
switch (entityContext.getType()) {
case Resource:
int resourceId = entityContext.getResourceId();
- DriftConfigurationCriteria criteria = new DriftConfigurationCriteria();
- criteria.addFilterName(driftConfigName);
+ DriftDefinitionCriteria criteria = new DriftDefinitionCriteria();
+ criteria.addFilterName(driftDefName);
criteria.addFilterResourceIds(resourceId);
criteria.setStrict(true);
- PageList<DriftConfiguration> results =
driftManager.findDriftConfigurationsByCriteria(subject, criteria);
- DriftConfiguration doomedDriftConfig = null;
+ PageList<DriftDefinition> results =
driftManager.findDriftDefinitionsByCriteria(subject, criteria);
+ DriftDefinition doomedDriftDef = null;
if (results != null && results.size() == 1) {
- doomedDriftConfig = results.get(0);
+ doomedDriftDef = results.get(0);
}
- if (doomedDriftConfig != null) {
+ if (doomedDriftDef != null) {
// TODO security check!
- // tell the agent first - we don't want the agent reporting on the
drift config after we delete it
+ // tell the agent first - we don't want the agent reporting on the
drift def after we delete it
boolean unscheduledOnAgent = false;
try {
AgentClient agentClient =
agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
DriftAgentService service = agentClient.getDriftAgentService();
- service.unscheduleDriftDetection(resourceId, doomedDriftConfig);
+ service.unscheduleDriftDetection(resourceId, doomedDriftDef);
unscheduledOnAgent = true;
} catch (Exception e) {
- log.warn(" Unable to inform agent of unscheduled drift detection
[" + doomedDriftConfig + "]", e);
+ log.warn(" Unable to inform agent of unscheduled drift detection
[" + doomedDriftDef + "]", e);
}
- // purge all data related to this drift configuration
+ // purge all data related to this drift definition
try {
- driftManager.purgeByDriftConfigurationName(subject, resourceId,
doomedDriftConfig.getName());
+ driftManager.purgeByDriftDefinitionName(subject, resourceId,
doomedDriftDef.getName());
} catch (Exception e) {
- String warnMessage = "Failed to purge data for drift
configuration [" + driftConfigName
+ String warnMessage = "Failed to purge data for drift definition
[" + driftDefName
+ "] for resource [" + resourceId + "].";
if (unscheduledOnAgent) {
- warnMessage += " The agent was told to stop detecting drift
for that configuration.";
+ warnMessage += " The agent was told to stop detecting drift
for that definition.";
}
log.warn(warnMessage, e);
}
- // now purge the drift config itself
- driftManager.deleteResourceDriftConfiguration(subject, resourceId,
doomedDriftConfig.getId());
+ // now purge the drift def itself
+ driftManager.deleteResourceDriftDefinition(subject, resourceId,
doomedDriftDef.getId());
} else {
- throw new IllegalArgumentException("Resource does not have drift
config named [" + driftConfigName
+ throw new IllegalArgumentException("Resource does not have drift
definition named [" + driftDefName
+ "]");
}
break;
@@ -312,8 +312,8 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
- public void deleteResourceDriftConfiguration(Subject subject, int resourceId, int
driftConfigId) {
- DriftConfiguration doomed = entityManager.getReference(DriftConfiguration.class,
driftConfigId);
+ public void deleteResourceDriftDefinition(Subject subject, int resourceId, int
driftDefId) {
+ DriftDefinition doomed = entityManager.getReference(DriftDefinition.class,
driftDefId);
doomed.getResource().setAgentSynchronizationNeeded();
entityManager.remove(doomed);
return;
@@ -335,13 +335,12 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
- public PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject
subject,
- DriftConfigurationCriteria criteria) {
+ public PageList<DriftDefinition> findDriftDefinitionsByCriteria(Subject
subject, DriftDefinitionCriteria criteria) {
CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject,
criteria);
- CriteriaQueryRunner<DriftConfiguration> queryRunner = new
CriteriaQueryRunner<DriftConfiguration>(criteria,
+ CriteriaQueryRunner<DriftDefinition> queryRunner = new
CriteriaQueryRunner<DriftDefinition>(criteria,
generator, entityManager);
- PageList<DriftConfiguration> result = queryRunner.execute();
+ PageList<DriftDefinition> result = queryRunner.execute();
return result;
}
@@ -354,11 +353,11 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
- public DriftConfiguration getDriftConfiguration(Subject subject, int driftConfigId)
{
- DriftConfiguration result = entityManager.find(DriftConfiguration.class,
driftConfigId);
+ public DriftDefinition getDriftDefinition(Subject subject, int driftDefId) {
+ DriftDefinition result = entityManager.find(DriftDefinition.class, driftDefId);
if (null == result) {
- throw new IllegalArgumentException("Drift Configuration Id [" +
driftConfigId + "] not found.");
+ throw new IllegalArgumentException("Drift Definition Id [" +
driftDefId + "] not found.");
}
// force lazy loads
@@ -394,19 +393,19 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
/**
- * This purges the persisted data related to drift configuration, but it does NOT
talk to the agent to tell the agent
- * about this nor does it actually delete the drift config itself.
+ * This purges the persisted data related to drift definition, but it does NOT talk
to the agent to tell the agent
+ * about this nor does it actually delete the drift def itself.
*
- * If you want to delete a drift configuration and all that that entails, you must
use
- * {@link #deleteDriftConfiguration(Subject, EntityContext, String)} instead.
+ * If you want to delete a drift definition and all that that entails, you must use
+ * {@link #deleteDriftDefinition(Subject, EntityContext, String)} instead.
*
* This method is really for internal use only.
*/
@Override
@TransactionAttribute(NOT_SUPPORTED)
- public void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception {
+ public void purgeByDriftDefinitionName(Subject subject, int resourceId, String
driftDefName) throws Exception {
DriftServerPluginFacet driftServerPlugin = getServerPlugin();
- driftServerPlugin.purgeByDriftConfigurationName(subject, resourceId,
driftConfigName);
+ driftServerPlugin.purgeByDriftDefinitionName(subject, resourceId, driftDefName);
}
@Override
@@ -454,12 +453,12 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
}
@Override
- public void updateDriftConfiguration(Subject subject, EntityContext entityContext,
DriftConfiguration driftConfig) {
+ public void updateDriftDefinition(Subject subject, EntityContext entityContext,
DriftDefinition driftDef) {
- // before we do anything, make sure the drift config name is valid
- if
(!driftConfig.getName().matches(DriftConfigurationDefinition.PROP_NAME_REGEX_PATTERN)) {
+ // before we do anything, make sure the drift def name is valid
+ if
(!driftDef.getName().matches(DriftConfigurationDefinition.PROP_NAME_REGEX_PATTERN)) {
throw new IllegalArgumentException("Drift configuration name contains
invalid characters: "
- + driftConfig.getName());
+ + driftDef.getName());
}
switch (entityContext.getType()) {
@@ -470,28 +469,28 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
throw new IllegalArgumentException("Entity not found [" +
entityContext + "]");
}
- // Update or add the driftConfig as necessary
- DriftConfigurationComparator comparator = new DriftConfigurationComparator(
+ // Update or add the driftDef as necessary
+ DriftDefinitionComparator comparator = new DriftDefinitionComparator(
CompareMode.ONLY_DIRECTORY_SPECIFICATIONS);
boolean isUpdated = false;
- for (DriftConfiguration dc : resource.getDriftConfigurations()) {
- if (dc.getName().equals(driftConfig.getName())) {
+ for (DriftDefinition dc : resource.getDriftDefinitions()) {
+ if (dc.getName().equals(driftDef.getName())) {
// compare the directory specs (basedir/includes-excludes filters
only - if they are different, abort.
- // you cannot update drift config that changes
basedir/includes/excludes from the original.
- // the user must delete the drift config and create a new one, as
opposed to trying to update the existing one.
- if (comparator.compare(driftConfig, dc) == 0) {
- dc.setConfiguration(driftConfig.getConfiguration());
+ // you cannot update drift def that changes basedir/includes/excludes
from the original.
+ // the user must delete the drift def and create a new one, as
opposed to trying to update the existing one.
+ if (comparator.compare(driftDef, dc) == 0) {
+ dc.setConfiguration(driftDef.getConfiguration());
isUpdated = true;
break;
} else {
throw new IllegalArgumentException(
- "You cannot change an existing drift configuration's
base directory or includes/excludes filters.");
+ "You cannot change an existing drift definition's
base directory or includes/excludes filters.");
}
}
}
if (!isUpdated) {
- resource.addDriftConfiguration(driftConfig);
+ resource.addDriftDefinition(driftDef);
}
resource.setAgentSynchronizationNeeded();
resource = entityManager.merge(resource);
@@ -504,9 +503,9 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
AgentClient agentClient =
agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
DriftAgentService service = agentClient.getDriftAgentService();
try {
- service.updateDriftDetection(resourceId, driftConfig);
+ service.updateDriftDetection(resourceId, driftDef);
} catch (Exception e) {
- log.warn(" Unable to inform agent of unscheduled drift detection
[" + driftConfig + "]", e);
+ log.warn(" Unable to inform agent of unscheduled drift detection
[" + driftDef + "]", e);
}
break;
@@ -591,7 +590,7 @@ public class DriftManagerBean implements DriftManagerLocal,
DriftManagerRemote {
private DriftChangeSet<?> loadPreviousChangeSet(Subject subject, Drift<?,
?> drift) {
GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
criteria.addFilterResourceId(drift.getChangeSet().getResourceId());
-
criteria.addFilterDriftConfigurationId(drift.getChangeSet().getDriftConfigurationId());
+
criteria.addFilterDriftDefinitionId(drift.getChangeSet().getDriftDefinitionId());
criteria.addFilterVersion(Integer.toString(drift.getChangeSet().getVersion() -
1));
PageList<? extends DriftChangeSet<?>> results =
findDriftChangeSetsByCriteria(subject, criteria);
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
index c11482e..194d0b0 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java
@@ -26,9 +26,9 @@ import javax.ejb.Local;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.drift.Drift;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftDetails;
import org.rhq.core.domain.drift.FileDiffReport;
import org.rhq.core.domain.util.PageList;
@@ -65,47 +65,47 @@ public interface DriftManagerLocal extends DriftServerPluginFacet,
DriftManagerR
File changeSetFilesZip) throws Exception;
/**
- * Remove the provided driftConfig (identified by name) on the specified
entityContext.
+ * Remove the provided driftDef (identified by name) on the specified entityContext.
* Agents, if available, will be notified of the change.
* @param subject
* @param entityContext
- * @param driftConfigName
+ * @param driftDefName
*/
- void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String
driftConfigName);
+ void deleteDriftDefinition(Subject subject, EntityContext entityContext, String
driftDefName);
/**
* This is for internal use only - do not call it unless you know what you are
doing.
*/
- void deleteResourceDriftConfiguration(Subject subject, int resourceId, int
driftConfigId);
+ void deleteResourceDriftDefinition(Subject subject, int resourceId, int driftDefId);
/**
- * One time on-demand request to detect drift on the specified entities, using the
supplied config.
+ * One time on-demand request to detect drift on the specified entities, using the
supplied def.
*
* @param entityContext
- * @param driftConfig
+ * @param driftDef
* @throws RuntimeException
*/
- void detectDrift(Subject subject, EntityContext context, DriftConfiguration
driftConfig);
+ void detectDrift(Subject subject, EntityContext context, DriftDefinition driftDef);
- PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject subject,
DriftConfigurationCriteria criteria);
+ PageList<DriftDefinition> findDriftDefinitionsByCriteria(Subject subject,
DriftDefinitionCriteria criteria);
/**
- * Get the specified drift configuration. Note, the full Configuration is fetched.
+ * Get the specified drift definition. Note, the full Configuration is fetched.
*
- * @param driftConfigId
- * @return The drift configuration
- * @throws RuntimeException, IllegalArgumentException if entity or driftConfig not
found.
+ * @param driftDefId
+ * @return The drift definition
+ * @throws RuntimeException, IllegalArgumentException if entity or driftDef not
found.
*/
- DriftConfiguration getDriftConfiguration(Subject subject, int driftConfigId);
+ DriftDefinition getDriftDefinition(Subject subject, int driftDefId);
/**
- * Update the provided driftConfig (identified by name) on the specified
EntityContext. If it exists it will be replaced. If not it will
+ * Update the provided driftDef (identified by name) on the specified EntityContext.
If it exists it will be replaced. If not it will
* be added. Agents, if available, will be notified of the change.
* @param subject
* @param entityContext
- * @param driftConfig
+ * @param driftDef
*/
- void updateDriftConfiguration(Subject subject, EntityContext entityContext,
DriftConfiguration driftConfig);
+ void updateDriftDefinition(Subject subject, EntityContext entityContext,
DriftDefinition driftDef);
/**
* This will remove all drift files that are no longer referenced by drift entries.
This is a maintenance method
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
index c017ca3..0e57f71 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerServiceImpl.java
@@ -19,6 +19,9 @@
*/
package org.rhq.enterprise.server.drift;
+import static org.rhq.enterprise.server.util.LookupUtil.getDriftManager;
+import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
+
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
@@ -29,15 +32,11 @@ import java.util.Set;
import org.rhq.core.clientapi.server.drift.DriftServerService;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
-import org.rhq.core.domain.criteria.DriftConfigurationCriteria;
+import org.rhq.core.domain.criteria.DriftDefinitionCriteria;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftSnapshot;
import org.rhq.core.domain.util.PageList;
-import org.rhq.core.domain.util.PageOrdering;
-
-import static org.rhq.enterprise.server.util.LookupUtil.getDriftManager;
-import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
public class DriftServerServiceImpl implements DriftServerService {
@Override
@@ -51,31 +50,30 @@ public class DriftServerServiceImpl implements DriftServerService {
}
@Override
- public void sendFilesZip(int resourceId, String driftConfigName, String token, long
zipSize,
- InputStream zipStream) {
+ public void sendFilesZip(int resourceId, long zipSize, InputStream zipStream) {
try {
DriftManagerLocal driftManager = getDriftManager();
- driftManager.addFiles(resourceId, driftConfigName, token, zipSize,
zipStream);
+ driftManager.addFiles(resourceId, zipSize, zipStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
- public Map<Integer, List<DriftConfiguration>>
getDriftConfigurations(Set<Integer> resourceIds) {
- DriftConfigurationCriteria criteria = new DriftConfigurationCriteria();
+ public Map<Integer, List<DriftDefinition>>
getDriftDefinitions(Set<Integer> resourceIds) {
+ DriftDefinitionCriteria criteria = new DriftDefinitionCriteria();
criteria.addFilterResourceIds(resourceIds.toArray(new
Integer[resourceIds.size()]));
criteria.fetchConfiguration(true);
Subject overlord = getSubjectManager().getOverlord();
- PageList<DriftConfiguration> configs =
getDriftManager().findDriftConfigurationsByCriteria(overlord, criteria);
+ PageList<DriftDefinition> configs =
getDriftManager().findDriftDefinitionsByCriteria(overlord, criteria);
- Map<Integer, List<DriftConfiguration>> map = new HashMap<Integer,
List<DriftConfiguration>>();
+ Map<Integer, List<DriftDefinition>> map = new HashMap<Integer,
List<DriftDefinition>>();
for (Integer resourceId : resourceIds) {
- map.put(resourceId, new ArrayList<DriftConfiguration>());
+ map.put(resourceId, new ArrayList<DriftDefinition>());
}
- for (DriftConfiguration c : configs) {
- List<DriftConfiguration> list = map.get(c.getResource().getId());
+ for (DriftDefinition c : configs) {
+ List<DriftDefinition> list = map.get(c.getResource().getId());
list.add(c);
map.put(c.getResource().getId(), list);
}
@@ -86,8 +84,7 @@ public class DriftServerServiceImpl implements DriftServerService {
@Override
public DriftSnapshot getCurrentSnapshot(int driftConfigurationId) {
DriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
- criteria.addFilterDriftConfigurationId(driftConfigurationId);
- criteria.addSortVersion(PageOrdering.ASC);
+ criteria.addFilterDriftDefinitionId(driftConfigurationId);
Subject overlord = getSubjectManager().getOverlord();
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
index e808b92..575fd74 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java
@@ -19,6 +19,9 @@
*/
package org.rhq.enterprise.server.drift;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
+import static org.rhq.core.domain.drift.DriftFileStatus.LOADED;
+
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
@@ -55,7 +58,7 @@ import org.rhq.core.domain.criteria.JPADriftCriteria;
import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftComposite;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftFileStatus;
import org.rhq.core.domain.drift.DriftSnapshot;
@@ -77,9 +80,6 @@ import org.rhq.enterprise.server.plugin.pc.drift.DriftChangeSetSummary;
import org.rhq.enterprise.server.util.CriteriaQueryGenerator;
import org.rhq.enterprise.server.util.CriteriaQueryRunner;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
-import static org.rhq.core.domain.drift.DriftFileStatus.LOADED;
-
/**
* The SLSB method implementation needed to support the JPA (RHQ Default) Drift Server
Plugin.
*
@@ -114,26 +114,26 @@ public class JPADriftServerBean implements JPADriftServerLocal {
@Override
@TransactionAttribute(REQUIRES_NEW)
- public void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception {
+ public void purgeByDriftDefinitionName(Subject subject, int resourceId, String
driftDefName) throws Exception {
int driftsDeleted;
int changeSetsDeleted;
StopWatch timer = new StopWatch();
// purge all drift entities first
- Query q =
entityManager.createNamedQuery(JPADrift.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE);
+ Query q =
entityManager.createNamedQuery(JPADrift.QUERY_DELETE_BY_DRIFTDEF_RESOURCE);
q.setParameter("resourceId", resourceId);
- q.setParameter("driftConfigurationName", driftConfigName);
+ q.setParameter("driftDefinitionName", driftDefName);
driftsDeleted = q.executeUpdate();
// now purge all changesets
- q =
entityManager.createNamedQuery(JPADriftChangeSet.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE);
+ q =
entityManager.createNamedQuery(JPADriftChangeSet.QUERY_DELETE_BY_DRIFTDEF_RESOURCE);
q.setParameter("resourceId", resourceId);
- q.setParameter("driftConfigurationName", driftConfigName);
+ q.setParameter("driftDefinitionName", driftDefName);
changeSetsDeleted = q.executeUpdate();
log.info("Purged [" + driftsDeleted + "] drift items and [" +
changeSetsDeleted
- + "] changesets associated with drift config [" + driftConfigName +
"] from resource [" + resourceId
+ + "] changesets associated with drift def [" + driftDefName +
"] from resource [" + resourceId
+ "]. Elapsed time=[" + timer.getElapsed() + "]ms");
return;
}
@@ -176,8 +176,8 @@ public class JPADriftServerBean implements JPADriftServerLocal {
PageList<DriftComposite> result = new PageList<DriftComposite>();
for (JPADrift drift : drifts) {
JPADriftChangeSet changeSet = drift.getChangeSet();
- DriftConfiguration driftConfig = changeSet.getDriftConfiguration();
- result.add(new DriftComposite(drift, changeSet.getResource(),
driftConfig.getName()));
+ DriftDefinition driftDef = changeSet.getDriftDefinition();
+ result.add(new DriftComposite(drift, changeSet.getResource(),
driftDef.getName()));
}
return result;
@@ -247,9 +247,9 @@ public class JPADriftServerBean implements JPADriftServerLocal {
stream)), false);
// store the new change set info (not the actual blob)
- DriftConfiguration config = findDriftConfiguration(resource,
reader.getHeaders());
- if (config == null) {
- log.error("Unable to locate DriftConfiguration for
Resource [" + resource
+ DriftDefinition driftDef = findDriftDefinition(resource,
reader.getHeaders());
+ if (driftDef == null) {
+ log.error("Unable to locate DriftDefinition for Resource
[" + resource
+ "]. Change set cannot be saved.");
return false;
}
@@ -262,13 +262,13 @@ public class JPADriftServerBean implements JPADriftServerLocal {
int version = reader.getHeaders().getVersion();
DriftChangeSetCategory category = reader.getHeaders().getType();
- driftChangeSet = new JPADriftChangeSet(resource, version,
category, config);
+ driftChangeSet = new JPADriftChangeSet(resource, version,
category, driftDef);
entityManager.persist(driftChangeSet);
summary.setCategory(category);
summary.setResourceId(resourceId);
-
summary.setDriftConfigurationName(reader.getHeaders().getDriftConfigurationName());
- summary.setDriftHandlingMode(config.getDriftHandlingMode());
+
summary.setDriftDefinitionName(reader.getHeaders().getDriftDefinitionName());
+ summary.setDriftHandlingMode(driftDef.getDriftHandlingMode());
summary.setCreatedTime(driftChangeSet.getCtime());
for (FileEntry entry : reader) {
@@ -357,29 +357,10 @@ public class JPADriftServerBean implements JPADriftServerLocal {
return result;
}
- /**
- * This method only exists temporarily until the version header is added to the
change
- * set meta data file. This method determines the version by looking at the number
of
- * change sets in the database.
- *
- * @param r The resource
- * @param c The drift configuration
- * @return The next change set version number
- */
- private int getChangeSetVersion(Resource r, DriftConfiguration c) {
- JPADriftChangeSetCriteria criteria = new JPADriftChangeSetCriteria();
- criteria.addFilterResourceId(r.getId());
- criteria.addFilterDriftConfigurationId(c.getId());
- List<? extends DriftChangeSet<?>> changeSets =
findDriftChangeSetsByCriteria(subjectManager.getOverlord(),
- criteria);
-
- return changeSets.size();
- }
-
- private DriftConfiguration findDriftConfiguration(Resource resource, Headers headers)
{
- for (DriftConfiguration driftConfig : resource.getDriftConfigurations()) {
- if (driftConfig.getName().equals(headers.getDriftConfigurationName())) {
- return driftConfig;
+ private DriftDefinition findDriftDefinition(Resource resource, Headers headers) {
+ for (DriftDefinition driftDef : resource.getDriftDefinitions()) {
+ if (driftDef.getName().equals(headers.getDriftDefinitionName())) {
+ return driftDef;
}
}
return null;
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java
index 841b45e..534cce5 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java
@@ -115,7 +115,7 @@ public interface JPADriftServerLocal {
* This is for internal use only - do not call it unless you know what you are
doing.
* This purges all drift entities and changeset entities associated with the drift
config.
*/
- void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception;
+ void purgeByDriftDefinitionName(Subject subject, int resourceId, String
driftConfigName) throws Exception;
/**
* SUPPORTS JPA DRIFT SERVER PLUGIN
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftChangeSetSummary.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftChangeSetSummary.java
index 045a3dc..7ac2365 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftChangeSetSummary.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftChangeSetSummary.java
@@ -39,7 +39,7 @@ public class DriftChangeSetSummary {
private long createdTime;
private DriftChangeSetCategory category;
private int resourceId;
- private String driftConfigurationName;
+ private String driftDefinitionName;
private DriftHandlingMode driftHandlingMode;
private List<String> driftPathnames;
@@ -51,11 +51,10 @@ public class DriftChangeSetSummary {
public String toString() {
if (category == DriftChangeSetCategory.COVERAGE) {
return "[" + new Date(createdTime) + "] Initial drift coverage
includes ["
- + obtainDriftPathnamesList().size() + "] files using drift
configuration [" + driftConfigurationName
- + "]";
+ + obtainDriftPathnamesList().size() + "] files using drift
definition [" + driftDefinitionName + "]";
} else {
return "[" + new Date(createdTime) + "] Drift detected in
[" + obtainDriftPathnamesList().size()
- + "] files using drift configuration [" +
driftConfigurationName + "]";
+ + "] files using drift definition [" + driftDefinitionName +
"]";
}
}
@@ -83,12 +82,12 @@ public class DriftChangeSetSummary {
this.resourceId = resourceId;
}
- public String getDriftConfigurationName() {
- return driftConfigurationName;
+ public String getDriftDefinitionName() {
+ return driftDefinitionName;
}
- public void setDriftConfigurationName(String driftConfigurationName) {
- this.driftConfigurationName = driftConfigurationName;
+ public void setDriftDefinitionName(String driftDefinitionName) {
+ this.driftDefinitionName = driftDefinitionName;
}
public List<String> getDriftPathnames() {
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
index cedf437..2167f95 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
@@ -86,14 +86,14 @@ public interface DriftServerPluginFacet {
void saveChangeSetFiles(Subject subject, File changeSetFilesZip) throws Exception;
/**
- * When a user wants to completely remove all data related to a drift configuration,
+ * When a user wants to completely remove all data related to a drift definition,
* this method will be called to give the plugin a chance to clean up any data
related
- * to the drift configuration that is going to be deleted.
+ * to the drift definition that is going to be deleted.
* @param Subject
- * @param resourceId the resource whose drift configuration is being purged
- * @param driftConfigName identifies the data that is to be purged
+ * @param resourceId the resource whose drift definition is being purged
+ * @param driftDefName identifies the data that is to be purged
*/
- void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception;
+ void purgeByDriftDefinitionName(Subject subject, int resourceId, String driftDefName)
throws Exception;
/**
* This will remove all drift files that are no longer referenced by drift entries.
This is a maintenance method
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java
index 6a10c30..0006b33 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java
@@ -417,8 +417,8 @@ public class ResourceManagerBean implements ResourceManagerLocal,
ResourceManage
// our unidirectional one-to-many mapping of drift config makes it not possible
to easily bulk delete drift config
// so remove them here and let cascading of delete_orphan do the work
- if (attachedResource.getDriftConfigurations() != null) {
- attachedResource.getDriftConfigurations().clear();
+ if (attachedResource.getDriftDefinitions() != null) {
+ attachedResource.getDriftDefinitions().clear();
}
// one more thing, delete any autogroup backing groups
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java
index 7e9bc1a..6b1c7dd 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBean.java
@@ -459,8 +459,8 @@ public class ResourceMetadataManagerBean implements
ResourceMetadataManagerLocal
// are different do we have to do anything to the persisted metadata.
//
- Set<ConfigurationTemplate> existingDriftTemplates =
existingType.getDriftConfigurationTemplates();
- Set<ConfigurationTemplate> newDriftTemplates =
resourceType.getDriftConfigurationTemplates();
+ Set<ConfigurationTemplate> existingDriftTemplates =
existingType.getDriftDefinitionTemplates();
+ Set<ConfigurationTemplate> newDriftTemplates =
resourceType.getDriftDefinitionTemplates();
if (existingDriftTemplates.size() != newDriftTemplates.size()) {
isSame = false;
} else {
@@ -508,11 +508,11 @@ public class ResourceMetadataManagerBean implements
ResourceMetadataManagerLocal
for (ConfigurationTemplate doomed : existingDriftTemplates) {
entityManager.remove(doomed);
}
- existingType.getDriftConfigurationTemplates().clear();
+ existingType.getDriftDefinitionTemplates().clear();
for (ConfigurationTemplate toPersist : newDriftTemplates) {
entityManager.persist(toPersist);
- existingType.addDriftConfigurationTemplate(toPersist);
+ existingType.addDriftDefinitionTemplate(toPersist);
}
}
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
index ab84ce5..2544540 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java
@@ -18,6 +18,13 @@
*/
package org.rhq.enterprise.server.drift;
+import static org.apache.commons.io.FileUtils.deleteDirectory;
+import static org.apache.commons.io.FileUtils.toFile;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.common.drift.FileEntry.changedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+
import java.io.File;
import java.util.Iterator;
import java.util.List;
@@ -45,11 +52,11 @@ import org.rhq.core.domain.criteria.ResourceCriteria;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftCategory;
import org.rhq.core.domain.drift.DriftChangeSet;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftFileStatus;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+import org.rhq.core.domain.drift.DriftDefinition.BaseDirectory;
import org.rhq.core.domain.resource.Agent;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
@@ -63,13 +70,6 @@ import org.rhq.enterprise.server.test.AbstractEJB3Test;
import org.rhq.enterprise.server.test.TestServerCommunicationsService;
import org.rhq.enterprise.server.util.LookupUtil;
-import static org.apache.commons.io.FileUtils.deleteDirectory;
-import static org.apache.commons.io.FileUtils.toFile;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
-import static org.rhq.common.drift.FileEntry.changedFileEntry;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
-import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
-
/**
* Test for {@link DriftManagerBean} SLSB.
*
@@ -104,7 +104,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
driftServerService = new DriftServerServiceImpl();
TestServerCommunicationsService agentServiceContainer = prepareForTestAgents();
- agentServiceContainer.driftService = new TestConfigService();
+ agentServiceContainer.driftService = new TestDefService();
}
@AfterClass
@@ -141,8 +141,8 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
Headers headers = new Headers();
headers.setResourceId(newResource.getId());
- headers.setDriftCofigurationId(1);
- headers.setDriftConfigurationName("test-1");
+ headers.setDriftDefinitionId(1);
+ headers.setDriftDefinitionName("test-1");
headers.setBasedir(rootDir.getAbsolutePath());
headers.setType(COVERAGE);
headers.setVersion(0);
@@ -212,100 +212,96 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
}
@Test(enabled = ENABLE_TESTS)
- public void testDriftConfig() throws Exception {
+ public void testDriftDef() throws Exception {
Configuration config = new Configuration();
- DriftConfiguration driftConfigPojo = new DriftConfiguration(config);
- driftConfigPojo.setName("testDriftConfig");
- driftConfigPojo.setInterval(60L);
- driftConfigPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"foo/bar"));
+ DriftDefinition driftDefPojo = new DriftDefinition(config);
+ driftDefPojo.setName("testDriftDef");
+ driftDefPojo.setInterval(60L);
+ driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"foo/bar"));
- driftManager
- .updateDriftConfiguration(overlord,
EntityContext.forResource(newResource.getId()), driftConfigPojo);
+ driftManager.updateDriftDefinition(overlord,
EntityContext.forResource(newResource.getId()), driftDefPojo);
ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
ResourceCriteria c = new ResourceCriteria();
c.addFilterId(newResource.getId());
- c.fetchDriftConfigurations(true);
+ c.fetchDriftDefinitions(true);
List<Resource> resources =
resourceManager.findResourcesByCriteria(overlord, c);
assertEquals(1, resources.size());
- Set<DriftConfiguration> driftConfigs =
resources.get(0).getDriftConfigurations();
- assertNotNull(driftConfigs);
- assertEquals(3, driftConfigs.size());
- DriftConfiguration driftConfig = null;
- for (Iterator<DriftConfiguration> i = driftConfigs.iterator();
i.hasNext();) {
- driftConfig = i.next();
- if (driftConfigPojo.getName().equals(driftConfig.getName()))
+ Set<DriftDefinition> driftDefs = resources.get(0).getDriftDefinitions();
+ assertNotNull(driftDefs);
+ assertEquals(3, driftDefs.size());
+ DriftDefinition driftDef = null;
+ for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext();) {
+ driftDef = i.next();
+ if (driftDefPojo.getName().equals(driftDef.getName()))
break;
}
- assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted
- assertEquals(driftConfigPojo.getName(), driftConfig.getName());
- assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir());
- assertEquals(driftConfigPojo.getInterval(), driftConfig.getInterval());
+ assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
+ assertEquals(driftDefPojo.getName(), driftDef.getName());
+ assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
+ assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
- driftConfigPojo.setInterval(120L);
- driftManager
- .updateDriftConfiguration(overlord,
EntityContext.forResource(newResource.getId()), driftConfigPojo);
+ driftDefPojo.setInterval(120L);
+ driftManager.updateDriftDefinition(overlord,
EntityContext.forResource(newResource.getId()), driftDefPojo);
resources = resourceManager.findResourcesByCriteria(overlord, c);
assertEquals(1, resources.size());
- driftConfigs = resources.get(0).getDriftConfigurations();
- assertNotNull(driftConfigs);
- assertEquals(3, driftConfigs.size());
- driftConfig = null;
- for (Iterator<DriftConfiguration> i = driftConfigs.iterator();
i.hasNext();) {
- driftConfig = i.next();
- if (driftConfigPojo.getName().equals(driftConfig.getName()))
+ driftDefs = resources.get(0).getDriftDefinitions();
+ assertNotNull(driftDefs);
+ assertEquals(3, driftDefs.size());
+ driftDef = null;
+ for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext();) {
+ driftDef = i.next();
+ if (driftDefPojo.getName().equals(driftDef.getName()))
break;
}
- assertEquals(driftConfigPojo.getName(), driftConfig.getName());
- assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted
- assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir());
- assertEquals(120L, driftConfig.getInterval());
+ assertEquals(driftDefPojo.getName(), driftDef.getName());
+ assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
+ assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
+ assertEquals(120L, driftDef.getInterval());
- driftConfigPojo.setName("testDriftConfig-2");
- driftConfigPojo.setInterval(30L);
- driftConfigPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"foo/baz"));
+ driftDefPojo.setName("testDriftDef-2");
+ driftDefPojo.setInterval(30L);
+ driftDefPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"foo/baz"));
- driftManager
- .updateDriftConfiguration(overlord,
EntityContext.forResource(newResource.getId()), driftConfigPojo);
+ driftManager.updateDriftDefinition(overlord,
EntityContext.forResource(newResource.getId()), driftDefPojo);
resources = resourceManager.findResourcesByCriteria(overlord, c);
assertEquals(1, resources.size());
- driftConfigs = resources.get(0).getDriftConfigurations();
- assertNotNull(driftConfigs);
- assertEquals(4, driftConfigs.size());
- for (Iterator<DriftConfiguration> i = driftConfigs.iterator();
i.hasNext();) {
- driftConfig = i.next();
- if ("testDriftConfig".equals(driftConfig.getName())) {
- assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted
- assertEquals("foo/bar",
driftConfig.getBasedir().getValueName());
- assertEquals(BaseDirValueContext.fileSystem,
driftConfig.getBasedir().getValueContext());
- assertEquals(120L, driftConfig.getInterval());
- } else if ("testDriftConfig-2".equals(driftConfig.getName())) {
- assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted
- assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir());
- assertEquals(driftConfigPojo.getInterval(), driftConfig.getInterval());
- } else if (!"test-1".equals(driftConfig.getName()) &&
!"test-2".equals(driftConfig.getName())) {
- fail("Unexpected drift config name: " +
driftConfig.getName());
+ driftDefs = resources.get(0).getDriftDefinitions();
+ assertNotNull(driftDefs);
+ assertEquals(4, driftDefs.size());
+ for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext();) {
+ driftDef = i.next();
+ if ("testDriftDef".equals(driftDef.getName())) {
+ assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
+ assertEquals("foo/bar", driftDef.getBasedir().getValueName());
+ assertEquals(BaseDirValueContext.fileSystem,
driftDef.getBasedir().getValueContext());
+ assertEquals(120L, driftDef.getInterval());
+ } else if ("testDriftDef-2".equals(driftDef.getName())) {
+ assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
+ assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
+ assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
+ } else if (!"test-1".equals(driftDef.getName()) &&
!"test-2".equals(driftDef.getName())) {
+ fail("Unexpected drift def name: " + driftDef.getName());
}
}
- driftManager.deleteDriftConfiguration(overlord,
EntityContext.forResource(newResource.getId()),
- "testDriftConfig");
+ driftManager.deleteDriftDefinition(overlord,
EntityContext.forResource(newResource.getId()), "testDriftDef");
resources = resourceManager.findResourcesByCriteria(overlord, c);
assertEquals(1, resources.size());
- driftConfigs = resources.get(0).getDriftConfigurations();
- assertNotNull(driftConfigs);
- assertEquals(3, driftConfigs.size());
- for (Iterator<DriftConfiguration> i = driftConfigs.iterator();
i.hasNext();) {
- driftConfig = i.next();
- if (driftConfigPojo.getName().equals(driftConfig.getName()))
+ driftDefs = resources.get(0).getDriftDefinitions();
+ assertNotNull(driftDefs);
+ assertEquals(3, driftDefs.size());
+ for (Iterator<DriftDefinition> i = driftDefs.iterator(); i.hasNext();) {
+ driftDef = i.next();
+ if (driftDefPojo.getName().equals(driftDef.getName()))
break;
}
- assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted
- assertEquals(driftConfigPojo.getName(), driftConfig.getName());
- assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir());
- assertEquals(driftConfigPojo.getInterval(), driftConfig.getInterval());
+ assertTrue(driftDef.getConfiguration().getId() > 0); // persisted
+ assertEquals(driftDefPojo.getName(), driftDef.getName());
+ assertEquals(driftDefPojo.getBasedir(), driftDef.getBasedir());
+ assertEquals(driftDefPojo.getInterval(), driftDef.getInterval());
}
private void deleteDriftFiles() throws Exception {
@@ -349,18 +345,18 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
em.persist(agent);
em.flush();
- DriftConfiguration test1Config = new DriftConfiguration(new
Configuration());
- test1Config.setName("test-1");
+ DriftDefinition test1Def = new DriftDefinition(new Configuration());
+ test1Def.setName("test-1");
- DriftConfiguration test2Config = new DriftConfiguration(new
Configuration());
- test2Config.setName("test-2");
+ DriftDefinition test2Def = new DriftDefinition(new Configuration());
+ test2Def.setName("test-2");
resource = new Resource("reskey" + System.currentTimeMillis(),
"resname", resourceType);
resource.setUuid("" + new Random().nextInt());
resource.setAgent(agent);
resource.setInventoryStatus(InventoryStatus.COMMITTED);
- resource.addDriftConfiguration(test1Config);
- resource.addDriftConfiguration(test2Config);
+ resource.addDriftDefinition(test1Def);
+ resource.addDriftDefinition(test2Def);
em.persist(resource);
} catch (Exception e) {
@@ -424,7 +420,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
return digestGenerator.calcDigestString(s);
}
- private class TestConfigService implements DriftAgentService {
+ private class TestDefService implements DriftAgentService {
@Override
public boolean requestDriftFiles(int resourceId, Headers headers, List<?
extends DriftFile> driftFiles) {
@@ -432,20 +428,20 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
}
@Override
- public void scheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void scheduleDriftDetection(int resourceId, DriftDefinition
DriftDefinition) {
}
@Override
- public void detectDrift(int resourceId, DriftConfiguration driftConfiguration) {
+ public void detectDrift(int resourceId, DriftDefinition DriftDefinition) {
}
@Override
- public void unscheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void unscheduleDriftDetection(int resourceId, DriftDefinition
DriftDefinition) {
}
@Override
- public void updateDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void updateDriftDetection(int resourceId, DriftDefinition DriftDefinition)
{
}
@Override
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java
index 403fc25..02696b8 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/inventory/UninventoryTest.java
@@ -30,9 +30,9 @@ import org.testng.annotations.Test;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
-import org.rhq.core.domain.drift.DriftConfiguration;
-import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
+import org.rhq.core.domain.drift.DriftDefinition.BaseDirectory;
import org.rhq.core.domain.resource.Agent;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
@@ -57,45 +57,45 @@ public class UninventoryTest extends AbstractEJB3Test {
}
}
- public void testDriftConfigRemoval() throws Exception {
+ public void testDriftDefRemoval() throws Exception {
ResourceTypeCreator rtCreator = new ResourceTypeCreator() {
public void modifyResourceTypeToPersist(ResourceType resourceType,
EntityManager em) {
- ConfigurationTemplate template = new
ConfigurationTemplate("drift1", "drift config template");
+ ConfigurationTemplate template = new
ConfigurationTemplate("drift1", "drift def template");
Configuration config = new Configuration();
- DriftConfiguration driftConfig = new DriftConfiguration(config);
- driftConfig.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"/"));
- driftConfig.setName("drift1");
- template.setConfiguration(driftConfig.getConfiguration());
- resourceType.addDriftConfigurationTemplate(template);
+ DriftDefinition driftDef = new DriftDefinition(config);
+ driftDef.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"/"));
+ driftDef.setName("drift1");
+ template.setConfiguration(driftDef.getConfiguration());
+ resourceType.addDriftDefinitionTemplate(template);
}
};
ResourceCreator rCreator = new ResourceCreator() {
public void modifyResourceToPersist(Resource resource, EntityManager em) {
Configuration config = new Configuration();
- DriftConfiguration driftConfig = new DriftConfiguration(config);
- driftConfig.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"/boo"));
- driftConfig.setName("drift-config-name");
- resource.addDriftConfiguration(driftConfig);
+ DriftDefinition driftDef = new DriftDefinition(config);
+ driftDef.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem,
"/boo"));
+ driftDef.setName("drift-def-name");
+ resource.addDriftDefinition(driftDef);
}
};
Resource resource = createNewResource(rtCreator, rCreator);
- int templateId =
resource.getResourceType().getDriftConfigurationTemplates().iterator().next().getId();
- int driftConfigId = resource.getDriftConfigurations().iterator().next().getId();
+ int templateId =
resource.getResourceType().getDriftDefinitionTemplates().iterator().next().getId();
+ int driftDefId = resource.getDriftDefinitions().iterator().next().getId();
// sanity check, make sure things are in the DB now
Query qTemplate;
- Query qConfig;
+ Query qDef;
String qTemplateString = "select ct from ConfigurationTemplate ct where
ct.id = :id";
- String qConfigString = "select dc from DriftConfiguration dc where dc.id =
:id";
+ String qDefString = "select dc from DriftDefinition dc where dc.id =
:id";
getTransactionManager().begin();
try {
qTemplate =
getEntityManager().createQuery(qTemplateString).setParameter("id", templateId);
- qConfig =
getEntityManager().createQuery(qConfigString).setParameter("id",
driftConfigId);
+ qDef =
getEntityManager().createQuery(qDefString).setParameter("id", driftDefId);
assertEquals("drift template didn't get added", 1,
qTemplate.getResultList().size());
- assertEquals("drift template config didn't get added", 1,
qConfig.getResultList().size());
+ assertEquals("drift template def didn't get added", 1,
qDef.getResultList().size());
} finally {
getTransactionManager().commit();
}
@@ -107,9 +107,9 @@ public class UninventoryTest extends AbstractEJB3Test {
getTransactionManager().begin();
try {
qTemplate =
getEntityManager().createQuery(qTemplateString).setParameter("id", templateId);
- qConfig =
getEntityManager().createQuery(qConfigString).setParameter("id",
driftConfigId);
+ qDef =
getEntityManager().createQuery(qDefString).setParameter("id", driftDefId);
assertEquals("drift template didn't get purged", 0,
qTemplate.getResultList().size());
- assertEquals("drift template config didn't get purged", 0,
qConfig.getResultList().size());
+ assertEquals("drift template def didn't get purged", 0,
qDef.getResultList().size());
} finally {
getTransactionManager().commit();
}
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java
index ca9ee2a..7f895b9 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java
@@ -30,7 +30,7 @@ import org.rhq.core.domain.content.PackageType;
import org.rhq.core.domain.criteria.OperationDefinitionCriteria;
import org.rhq.core.domain.criteria.ResourceCriteria;
import org.rhq.core.domain.criteria.ResourceTypeCriteria;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftConfigurationDefinition;
import org.rhq.core.domain.drift.Filter;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
@@ -66,7 +66,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest {
Query qConfig;
String qTemplateString = "select ct from ConfigurationTemplate ct where
ct.id = :id";
String qConfigString = "select c from Configuration c where c.id =
:id";
- ConfigurationTemplate driftTemplate =
type1.getDriftConfigurationTemplates().iterator().next();
+ ConfigurationTemplate driftTemplate =
type1.getDriftDefinitionTemplates().iterator().next();
Configuration bundleConfig =
type1.getResourceTypeBundleConfiguration().getBundleConfiguration();
Configuration driftConfig = driftTemplate.getConfiguration();
@@ -163,11 +163,11 @@ public class ResourceMetadataManagerBeanTest extends
MetadataBeanTest {
ResourceType type = assertResourceTypeAssociationEquals("ServerA",
"TestPlugin", "driftConfigurationTemplates",
asList("drift-pc", "drift-fs"));
- DriftConfiguration driftConfig = null;
- Set<ConfigurationTemplate> drifts = type.getDriftConfigurationTemplates();
+ DriftDefinition driftConfig = null;
+ Set<ConfigurationTemplate> drifts = type.getDriftDefinitionTemplates();
for (ConfigurationTemplate drift : drifts) {
if (drift.getName().equals("drift-pc")) {
- driftConfig = new DriftConfiguration(drift.getConfiguration());
+ driftConfig = new DriftDefinition(drift.getConfiguration());
assertTrue(driftConfig.isEnabled());
assertEquals(BaseDirValueContext.pluginConfiguration,
driftConfig.getBasedir().getValueContext());
assertEquals("connectionPropertyX",
driftConfig.getBasedir().getValueName());
@@ -184,7 +184,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest
{
assertEquals("/hello", filter.getPath());
assertEquals("", filter.getPattern());
} else if (drift.getName().equals("drift-fs")) {
- driftConfig = new DriftConfiguration(drift.getConfiguration());
+ driftConfig = new DriftDefinition(drift.getConfiguration());
assertTrue(driftConfig.isEnabled());
assertEquals(BaseDirValueContext.fileSystem,
driftConfig.getBasedir().getValueContext());
assertEquals("/", driftConfig.getBasedir().getValueName());
@@ -285,11 +285,11 @@ public class ResourceMetadataManagerBeanTest extends
MetadataBeanTest {
ResourceType type = assertResourceTypeAssociationEquals("ServerA",
"TestPlugin", "driftConfigurationTemplates",
asList("drift-rc", "drift-mt"));
- DriftConfiguration driftConfig = null;
- Set<ConfigurationTemplate> drifts = type.getDriftConfigurationTemplates();
+ DriftDefinition driftConfig = null;
+ Set<ConfigurationTemplate> drifts = type.getDriftDefinitionTemplates();
for (ConfigurationTemplate drift : drifts) {
if (drift.getName().equals("drift-rc")) {
- driftConfig = new DriftConfiguration(drift.getConfiguration());
+ driftConfig = new DriftDefinition(drift.getConfiguration());
assertTrue(driftConfig.isEnabled());
assertEquals(BaseDirValueContext.resourceConfiguration,
driftConfig.getBasedir().getValueContext());
assertEquals("resourceConfig1",
driftConfig.getBasedir().getValueName());
@@ -297,7 +297,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest
{
assertEquals(0, driftConfig.getIncludes().size());
assertEquals(0, driftConfig.getExcludes().size());
} else if (drift.getName().equals("drift-mt")) {
- driftConfig = new DriftConfiguration(drift.getConfiguration());
+ driftConfig = new DriftDefinition(drift.getConfiguration());
assertTrue(driftConfig.isEnabled());
assertEquals(BaseDirValueContext.measurementTrait,
driftConfig.getBasedir().getValueContext());
assertEquals("trait1",
driftConfig.getBasedir().getValueName());
diff --git
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
index 43d0ded..1515869 100644
---
a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
+++
b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/TestAgentClient.java
@@ -58,7 +58,7 @@ import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
import org.rhq.core.domain.discovery.AvailabilityReport;
import org.rhq.core.domain.discovery.MergeResourceResponse;
import org.rhq.core.domain.discovery.ResourceSyncInfo;
-import org.rhq.core.domain.drift.DriftConfiguration;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.MeasurementData;
@@ -336,19 +336,19 @@ public class TestAgentClient implements AgentClient,
BundleAgentService, DriftAg
}
@Override
- public void scheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void scheduleDriftDetection(int resourceId, DriftDefinition
driftConfiguration) {
}
@Override
- public void detectDrift(int resourceId, DriftConfiguration driftConfiguration) {
+ public void detectDrift(int resourceId, DriftDefinition driftConfiguration) {
}
@Override
- public void unscheduleDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void unscheduleDriftDetection(int resourceId, DriftDefinition
driftConfiguration) {
}
@Override
- public void updateDriftDetection(int resourceId, DriftConfiguration
driftConfiguration) {
+ public void updateDriftDetection(int resourceId, DriftDefinition driftConfiguration)
{
}
@Override
diff --git
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index ceeacfd..1c78182 100644
---
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -127,13 +127,13 @@ public class MongoDBDriftServer implements DriftServerPluginFacet,
ServerPluginC
MongoDBChangeSet changeSet = new MongoDBChangeSet();
changeSet.setCategory(headers.getType());
changeSet.setResourceId(resourceId);
- changeSet.setDriftConfigurationId(headers.getDriftCofigurationId());
+ changeSet.setDriftDefinitionId(headers.getDriftDefinitionId());
changeSet.setDriftHandlingMode(DriftHandlingMode.normal);
changeSet.setVersion(headers.getVersion());
summary.setCategory(headers.getType());
summary.setResourceId(resourceId);
- summary.setDriftConfigurationName(headers.getDriftConfigurationName());
+ summary.setDriftDefinitionName(headers.getDriftDefinitionName());
summary.setCreatedTime(changeSet.getCtime());
for (FileEntry fileEntry : reader) {
@@ -294,7 +294,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet,
ServerPluginC
}
@Override
- public void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception {
+ public void purgeByDriftDefinitionName(Subject subject, int resourceId, String
driftDefName) throws Exception {
// TODO implement me!
}
@@ -328,7 +328,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet,
ServerPluginC
DriftChangeSetDTO dto = new DriftChangeSetDTO();
dto.setId(changeSet.getId());
// TODO copy resource id
- dto.setDriftConfigurationId(changeSet.getDriftConfigurationId());
+ dto.setDriftDefinitionId(changeSet.getDriftDefinitionId());
dto.setVersion(changeSet.getVersion());
dto.setCtime(changeSet.getCtime());
dto.setCategory(changeSet.getCategory());
diff --git
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
index 0bdd2fd..d13466b 100644
---
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
+++
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
@@ -114,12 +114,12 @@ public class MongoDBChangeSet implements
DriftChangeSet<MongoDBChangeSetEntry>,
}
@Override
- public int getDriftConfigurationId() {
+ public int getDriftDefinitionId() {
return configId;
}
@Override
- public void setDriftConfigurationId(int id) {
+ public void setDriftDefinitionId(int id) {
configId = id;
}
diff --git
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index e236266..df8cad2 100644
---
a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++
b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -35,7 +35,7 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet,
MongoDBFil
/**
* This is the path relative to the base directory defined in the
- * {@link org.rhq.core.domain.drift.DriftConfiguration}
+ * {@link org.rhq.core.domain.drift.DriftDefinition}
*/
private String path;
diff --git
a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 1c3c3c7..6abaaac 100644
---
a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++
b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -90,7 +90,7 @@ public class ChangeSetDAOTest {
MongoDBChangeSet expected = new MongoDBChangeSet();
expected.setCategory(COVERAGE);
expected.setVersion(1);
- expected.setDriftConfigurationId(1);
+ expected.setDriftDefinitionId(1);
expected.setResourceId(1);
expected.setDriftHandlingMode(normal);
@@ -105,7 +105,7 @@ public class ChangeSetDAOTest {
MongoDBChangeSet expected = new MongoDBChangeSet();
expected.setCategory(DRIFT);
expected.setResourceId(1);
- expected.setDriftConfigurationId(1);
+ expected.setDriftDefinitionId(1);
expected.setVersion(1);
MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry();
@@ -137,7 +137,7 @@ public class ChangeSetDAOTest {
expected.setCategory(DRIFT);
expected.setVersion(1);
expected.setResourceId(1);
- expected.setDriftConfigurationId(1);
+ expected.setDriftDefinitionId(1);
expected.add(new MongoDBChangeSetEntry("foo", FILE_ADDED)).add(new
MongoDBChangeSetEntry("bar", FILE_ADDED));
dao.save(expected);
@@ -153,14 +153,14 @@ public class ChangeSetDAOTest {
c1.setCategory(DRIFT);
c1.setVersion(1);
c1.setResourceId(1);
- c1.setDriftConfigurationId(1);
+ c1.setDriftDefinitionId(1);
dao.save(c1);
MongoDBChangeSet c2 = new MongoDBChangeSet();
c2.setCategory(DRIFT);
c2.setVersion(1);
c2.setResourceId(2);
- c2.setDriftConfigurationId(2);
+ c2.setDriftDefinitionId(2);
GenericDriftCriteria criteria = new GenericDriftCriteria();
criteria.addFilterResourceIds(1);
@@ -427,7 +427,7 @@ public class ChangeSetDAOTest {
changeSet.setCategory(category);
changeSet.setVersion(version);
changeSet.setResourceId(resourceId);
- changeSet.setDriftConfigurationId(driftConfigId);
+ changeSet.setDriftDefinitionId(driftConfigId);
return changeSet;
}
diff --git
a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
index ee542d0..ef962b2 100644
---
a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
+++
b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
@@ -115,8 +115,8 @@ public class JPADriftServerPluginComponent implements
DriftServerPluginFacet, Se
}
@Override
- public void purgeByDriftConfigurationName(Subject subject, int resourceId, String
driftConfigName) throws Exception {
- getJPADriftServer().purgeByDriftConfigurationName(subject, resourceId,
driftConfigName);
+ public void purgeByDriftDefinitionName(Subject subject, int resourceId, String
driftDefName) throws Exception {
+ getJPADriftServer().purgeByDriftDefinitionName(subject, resourceId,
driftDefName);
}
@Override
commit 2f32a3fa1b23531126c5b10d300e2cc4f4960702
Merge: a594d1b b31e834
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 29 14:36:13 2011 -0400
Merge branch 'master' into code-smell
* master:
BZ 738029 - partially revert the change of BZ 536496, so that plugins that still use
the deprecated (and useless) attribute can be deployed. Spit out a warning to the
console.
commit a594d1bbafdcde8f2a35ea7f169ac8360e9ff953
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 29 14:35:16 2011 -0400
revert inlined returns to non-inlined returns so folks can place a breakpoint on the
return
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
index 7722508..eee311b 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
@@ -300,9 +300,10 @@ public class CreateNewPackageChildResourceUIBean {
deployTimeConfigurationTemplates = configDef.getDefaultTemplate();
}
- return (deployTimeConfigurationTemplates != null) ?
deployTimeConfigurationTemplates
+ Configuration deployTimeConfiguration = (deployTimeConfigurationTemplates !=
null) ? deployTimeConfigurationTemplates
.createConfiguration()
: new Configuration();
+ return deployTimeConfiguration;
}
// Accessors --------------------------------------------
@@ -331,7 +332,8 @@ public class CreateNewPackageChildResourceUIBean {
}
}
- return selectItemsList.toArray(new SelectItem[selectItemsList.size()]);
+ SelectItem[] items = selectItemsList.toArray(new
SelectItem[selectItemsList.size()]);
+ return items;
}
public CreateResourceHistory getRetryCreateItem() {
commit b31e834a96dd20f864736447bee74c9194b4884a
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Thu Sep 29 17:44:14 2011 +0200
BZ 738029 - partially revert the change of BZ 536496, so that plugins that still use
the deprecated (and useless) attribute can be deployed. Spit out a warning to the
console.
diff --git
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java
index facde3c..ef8717b 100644
---
a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java
+++
b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java
@@ -29,6 +29,10 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.JAXBElement;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import org.rhq.core.clientapi.agent.configuration.ConfigurationUtility;
import org.rhq.core.clientapi.descriptor.configuration.ConfigurationDescriptor;
import org.rhq.core.clientapi.descriptor.configuration.ConfigurationProperty;
@@ -74,6 +78,9 @@ import org.rhq.core.domain.util.StringUtils;
* @author Ian Springer
*/
public class ConfigurationMetadataParser {
+
+ private static Log log = LogFactory.getLog("ConfigurationMetadataParser");
+
public static ConfigurationDefinition parse(String configurationName,
ConfigurationDescriptor descriptor)
throws InvalidPluginDescriptorException {
if (descriptor == null) {
@@ -285,6 +292,10 @@ public class ConfigurationMetadataParser {
name = option.getValue();
}
+ if (option.isDefault()) {
+ log.warn("!!\nFor simple-property [" + parentProperty.getName()
+ "], attribute 'default' on c:option is useless and deprecated.\n Please
use the 'default' attribute on the c:simple-property.\n The deprecated attribute
will be removed in the future.\n!!");
+ }
+
PropertyDefinitionEnumeration enumeration = new
PropertyDefinitionEnumeration(name, option.getValue());
parentProperty.addEnumeratedValues(enumeration);
}
diff --git a/modules/core/client-api/src/main/resources/rhq-configuration.xsd
b/modules/core/client-api/src/main/resources/rhq-configuration.xsd
index 4b706d8..e4e9789 100644
--- a/modules/core/client-api/src/main/resources/rhq-configuration.xsd
+++ b/modules/core/client-api/src/main/resources/rhq-configuration.xsd
@@ -505,6 +505,17 @@
<xs:restriction base="xs:string"/>
</xs:simpleType>
</xs:attribute>
+ <xs:attribute name="default" default="false"
use="optional">
+ <xs:annotation>
+ <xs:documentation>Was supposed to indicate that this item is the
default item in the list.
+ This does not work and will be deprecated in later versions.
+ Please use the 'default' attribute on the parents
simple-property.
+ </xs:documentation>
+ </xs:annotation>
+ <xs:simpleType>
+ <xs:restriction base="xs:boolean"/>
+ </xs:simpleType>
+ </xs:attribute>
</xs:complexType>
<!-- == Property Constraints ================= -->
commit 5c127ed94b8f25fb37fcdca514fc389dd8e3fdfd
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 29 10:07:09 2011 -0400
revert some inlining; some folks seem to prefer non-inlined returns as a breakpoint
spot
diff --git a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
index 88e7705..cdacd46 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
@@ -98,7 +98,8 @@ public class EntitySerializer {
Collections.sort(serializableFields, fieldComparator);
- return serializableFields.toArray(new Field[serializableFields.size()]);
+ Field[] results = serializableFields.toArray(new
Field[serializableFields.size()]);
+ return results;
}
private static List<Field> getNonEntityFieldList(Object object) {
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
index ff402b5..e9695fb 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
@@ -57,7 +57,8 @@ public class DownloadsUIBean implements Serializable {
public List<File> getConnectorDownloadFiles() throws Exception {
File downloadDir = getConnectorDownloadsDir();
- return getFiles(downloadDir);
+ List<File> files = getFiles(downloadDir);
+ return files;
}
private File getConnectorDownloadsDir() throws Exception {
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
index 8a97186..2a08598 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
@@ -132,7 +132,8 @@ public class CreateNewPackageUIBean {
selectedArchitectureId = getBackingPackageArchitectureId();
selectedPackageTypeId = getBackingPackageTypeId();
}
- return createNewPackage(packageName, version, selectedArchitectureId,
selectedPackageTypeId);
+ String response = createNewPackage(packageName, version, selectedArchitectureId,
selectedPackageTypeId);
+ return response;
}
public String createNewPackage(String packageName, String version, int
architectureId, int packageTypeId) {
@@ -539,4 +540,4 @@ public class CreateNewPackageUIBean {
return repoId;
}
-}
\ No newline at end of file
+}
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
index fcb75b4..7722508 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
@@ -281,7 +281,8 @@ public class CreateNewPackageChildResourceUIBean {
resourceType = lookupResourceType();
}
ContentManagerLocal contentManager = LookupUtil.getContentManager();
- return contentManager.getResourceCreationPackageType(this.resourceType.getId());
+ PackageType packageType =
contentManager.getResourceCreationPackageType(this.resourceType.getId());
+ return packageType;
}
protected ConfigurationDefinition lookupConfigurationDefinition() {
@@ -433,4 +434,4 @@ public class CreateNewPackageChildResourceUIBean {
return items;
}
-}
\ No newline at end of file
+}
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
index a08e977..a69f928 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
@@ -146,7 +146,8 @@ public class ApplicationServerDiscoveryComponent implements
ResourceDiscoveryCom
} catch (IOException e) {
throw new InvalidPluginConfigurationException(e);
}
- return createResourceDetails(discoveryContext, pluginConfig, processInfo,
installInfo);
+ DiscoveredResourceDetails resourceDetails =
createResourceDetails(discoveryContext, pluginConfig, processInfo, installInfo);
+ return resourceDetails;
}
@SuppressWarnings("unchecked")
diff --git
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index c5bf3ff..388b614 100644
---
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -197,7 +197,8 @@ public abstract class AbstractBaseDiscovery<T extends
ResourceComponent<?>> impl
if (hostXml==null)
throw new IllegalArgumentException("hostXml is null. You need to call
'readStandaloneOrHostXml' first.");
- return hostXml.getDocumentElement().getAttribute("name");
+ String hostName = hostXml.getDocumentElement().getAttribute("name");
+ return hostName;
}
/**
diff --git
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 3f37e34..1b5a855 100644
---
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -74,7 +74,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery
implements Resou
String psName = psr.getProcessScan().getName();
String description = discoveryContext.getResourceType().getDescription();
String homeDir = getHomeDirFromCommandLine(commandLine);
- String version;
+ String version = null;
//retrieve specific boot log file. Override for Standalone as server.log is
more appropriate
String bootLogFile = getLogFileFromCommandLine(commandLine);
@@ -164,7 +164,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery
implements Resou
DiscoveredResourceDetails detail = new
DiscoveredResourceDetails(discoveryContext.getResourceType(), // ResourceType
serverNameFull, // key TODO distinguish per domain?
serverName, // Name
- version, // TODO get via API ?�
+ version, // TODO get via API ?
description, // Description
config, psr.getProcessInfo());
commit 51462a41002f335bbfe7cc80af8d3fa74766af78
Merge: 3132cba 566527b
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 29 09:21:26 2011 -0400
merge master to code-smell
diff --cc modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
index 9ac9ead,60ae7cb..2389268
--- a/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
@@@ -186,4 -181,23 +191,23 @@@ public class PropertiesFileUpdate
return props;
}
+
+ private String trimString(String str, boolean trimStart, boolean trimEnd) {
+ int start = 0;
+ int end = str.length();
+
+ if (trimStart) {
+ while ((start < end) && (str.charAt(start) == ' ')) {
+ start++;
+ }
+ }
+
+ if (trimEnd) {
+ while ((start < end) && (str.charAt(end - 1) == ' ')) {
+ end--;
+ }
+ }
+
+ return ((start > 0) || (end < str.length())) ? str.substring(start, end) :
str;
+ }
-}
+}
diff --cc
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 9d4c2f2,8e73205..3f37e34
---
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@@ -77,7 -73,8 +73,8 @@@ public class BaseProcessDiscovery exten
String serverName;
String psName = psr.getProcessScan().getName();
String description = discoveryContext.getResourceType().getDescription();
+ String homeDir = getHomeDirFromCommandLine(commandLine);
- String version = null;
+ String version;
//retrieve specific boot log file. Override for Standalone as server.log is
more appropriate
String bootLogFile = getLogFileFromCommandLine(commandLine);
commit 566527b927703def46ed89b2b93c8025d3e0859a
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 28 23:18:09 2011 -0400
remove an unused param; misc cosmetic tweaks
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
index af2d800..9511e63 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/CriteriaQueryGenerator.java
@@ -262,7 +262,7 @@ public final class CriteriaQueryGenerator {
}
private String getParameterReplacedValue(Object value) {
- String returnValue = null;
+ String returnValue;
if (value instanceof String) {
returnValue = "'" + prepareStringBindValue((String) value) +
"'";
} else if (value instanceof Enum<?>) {
@@ -401,7 +401,7 @@ public final class CriteriaQueryGenerator {
String expressionLeaf = sortFragment.substring(lastDelimiterIndex + 1);
int expressionRootIndex =
orderingFieldRequiredJoins.indexOf(expressionRoot);
- String joinAlias = null;
+ String joinAlias;
if (expressionRootIndex == -1) {
// new join
joinAlias = "orderingField" +
orderingFieldRequiredJoins.size();
@@ -443,7 +443,7 @@ public final class CriteriaQueryGenerator {
}
String fieldName = filterField.getKey();
String override = criteria.getJPQLFilterOverride(fieldName);
- String fragment = null;
+ String fragment;
if (override != null) {
fragment = fixFilterOverride(override, fieldName);
} else {
@@ -476,7 +476,7 @@ public final class CriteriaQueryGenerator {
// always want AND for security, regardless of conjunctiveFragment
results.append(NL).append(" AND ");
}
- results.append(this.authorizationPermsFragment + " ");
+ results.append(this.authorizationPermsFragment).append(" ");
}
if (authorizationCustomConditionFragment != null) {
@@ -544,7 +544,7 @@ public final class CriteriaQueryGenerator {
public List<String> getFetchFields(Criteria criteria) {
List<String> results = new ArrayList<String>();
for (Field fetchField : getFields(criteria, Criteria.Type.FETCH)) {
- Object fetchFieldValue = null;
+ Object fetchFieldValue;
try {
fetchField.setAccessible(true);
fetchFieldValue = fetchField.get(criteria);
@@ -591,7 +591,7 @@ public final class CriteriaQueryGenerator {
public Map<String, Object> getFilterFields(Criteria criteria) {
Map<String, Object> results = new HashMap<String, Object>();
for (Field filterField : getFields(criteria, Criteria.Type.FILTER)) {
- Object filterFieldValue = null;
+ Object filterFieldValue;
try {
filterFieldValue = filterField.get(criteria);
} catch (IllegalAccessException iae) {
@@ -741,7 +741,7 @@ public final class CriteriaQueryGenerator {
public Query getQuery(EntityManager em) {
String queryString = getQueryString(false);
Query query = em.createQuery(queryString);
- setBindValues(query, false);
+ setBindValues(query);
PersistenceUtility.setDataPage(query, getPageControl(criteria));
return query;
}
@@ -749,11 +749,11 @@ public final class CriteriaQueryGenerator {
public Query getCountQuery(EntityManager em) {
String countQueryString = getQueryString(true);
Query query = em.createQuery(countQueryString);
- setBindValues(query, false);
+ setBindValues(query);
return query;
}
- private void setBindValues(Query query, boolean countQuery) {
+ private void setBindValues(Query query) {
for (Map.Entry<String, Object> critField :
getFilterFields(criteria).entrySet()) {
Object value = critField.getValue();
@@ -886,7 +886,7 @@ public final class CriteriaQueryGenerator {
}
public static PageControl getPageControl(Criteria criteria) {
- PageControl pc = null;
+ PageControl pc;
if (criteria.getPageControlOverrides() != null) {
pc = criteria.getPageControlOverrides();
@@ -901,7 +901,7 @@ public final class CriteriaQueryGenerator {
if (sortField.getName().equals(fieldName) == false) {
continue;
}
- Object sortFieldValue = null;
+ Object sortFieldValue;
try {
sortFieldValue = sortField.get(criteria);
} catch (IllegalAccessException iae) {
@@ -916,4 +916,5 @@ public final class CriteriaQueryGenerator {
}
return pc;
}
-}
\ No newline at end of file
+
+}
commit 78a15b47a94e4d8f4b5d6eff7f8fb030bf1b4ad3
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 28 22:55:34 2011 -0400
fix javadoc generation
diff --git a/modules/common/jboss-as/pom.xml b/modules/common/jboss-as/pom.xml
index 184c5ad..52befb3 100644
--- a/modules/common/jboss-as/pom.xml
+++ b/modules/common/jboss-as/pom.xml
@@ -71,7 +71,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
@@ -187,4 +186,5 @@
</build>
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
+
diff --git a/modules/core/domain/pom.xml b/modules/core/domain/pom.xml
index 42d28e1..d87ce09 100644
--- a/modules/core/domain/pom.xml
+++ b/modules/core/domain/pom.xml
@@ -408,23 +408,19 @@
<executions>
<execution>
- <id>javadoc-domain-api</id>
+ <id>domain-api</id>
<phase>compile</phase>
<goals>
<goal>javadoc</goal>
</goals>
<configuration>
- <doctitle>RHQ ${project.version} -
Domain</doctitle>
+ <doctitle>RHQ ${project.version} Domain
API</doctitle>
+ <windowtitle>RHQ ${project.version} Domain
API</windowtitle>
<reportOutputDirectory>${javadoc.outputDirectory}</reportOutputDirectory>
<destDir>domain</destDir>
- <aggregate>true</aggregate>
- <encoding>UTF-8</encoding>
- <charset>UTF-8</charset>
- <docencoding>UTF-8</docencoding>
<author>false</author>
<breakiterator>true</breakiterator>
<links>
-
<
link>http://java.sun.com/j2se/1.5.0/docs/api/</link>
<
link>http://java.sun.com/javaee/5/docs/api/</link>
</links>
</configuration>
@@ -434,6 +430,7 @@
</plugins>
</build>
</profile>
+
<profile>
<id>cobertura</id>
<activation>
diff --git a/modules/core/native-system/pom.xml b/modules/core/native-system/pom.xml
index 7d83f3d..4a24392 100644
--- a/modules/core/native-system/pom.xml
+++ b/modules/core/native-system/pom.xml
@@ -104,9 +104,67 @@
</configuration>
</plugin>
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+
+ <executions>
+ <execution>
+ <id>system-api</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>javadoc</goal>
+ </goals>
+ <configuration>
+ <doctitle>RHQ ${project.version} System API</doctitle>
+
<reportOutputDirectory>${javadoc.outputDirectory}</reportOutputDirectory>
+ <author>false</author>
+ <breakiterator>true</breakiterator>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
</plugins>
</build>
+
<profiles>
+
+ <profile>
+ <id>javadoc</id>
+ <activation>
+ <property>
+ <name>javadoc.outputDirectory</name>
+ </property>
+ </activation>
+
+ <build>
+ <plugins>
+
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+
+ <executions>
+ <execution>
+ <id>system-api</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>javadoc</goal>
+ </goals>
+ <configuration>
+ <doctitle>RHQ ${project.version} System
API</doctitle>
+ <windowtitle>RHQ ${project.version} System
API</windowtitle>
+
<reportOutputDirectory>${javadoc.outputDirectory}</reportOutputDirectory>
+ <destDir>system</destDir>
+ <author>false</author>
+ <breakiterator>true</breakiterator>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
<profile>
<id>cobertura</id>
<activation>
diff --git a/modules/core/plugin-api/pom.xml b/modules/core/plugin-api/pom.xml
index fc78701..6b633bb 100644
--- a/modules/core/plugin-api/pom.xml
+++ b/modules/core/plugin-api/pom.xml
@@ -75,6 +75,47 @@
</dependencies>
<profiles>
+
+ <profile>
+ <id>javadoc</id>
+ <activation>
+ <property>
+ <name>javadoc.outputDirectory</name>
+ </property>
+ </activation>
+
+ <build>
+ <plugins>
+
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+
+ <executions>
+ <execution>
+ <id>agent-plugin-api</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>javadoc</goal>
+ </goals>
+ <configuration>
+ <doctitle>RHQ ${project.version} Agent Plugin
API</doctitle>
+ <windowtitle>RHQ ${project.version} Agent Plugin
API</windowtitle>
+
<reportOutputDirectory>${javadoc.outputDirectory}</reportOutputDirectory>
+ <destDir>plugin-api</destDir>
+ <author>false</author>
+ <breakiterator>true</breakiterator>
+ <links>
+ <link>../domain/</link>
+ <link>../system/</link>
+ </links>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
<profile>
<id>cobertura</id>
<activation>
diff --git a/modules/enterprise/binding/pom.xml b/modules/enterprise/binding/pom.xml
index d96cf83..41d9c7c 100644
--- a/modules/enterprise/binding/pom.xml
+++ b/modules/enterprise/binding/pom.xml
@@ -272,6 +272,55 @@
</build>
</profile>
+ <profile>
+ <id>javadoc</id>
+ <activation>
+ <property>
+ <name>javadoc.outputDirectory</name>
+ </property>
+ </activation>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+
+ <execution>
+ <id>bindings-api</id>
+ <phase>compile</phase>
+ <configuration>
+ <tasks>
+ <property name="javadoc.outputDirectory"
value="${javadoc.outputDirectory}" />
+ <property name="project.dir"
value="./src/main/java/org/rhq/bindings" />
+ <property name="maven.compile.classpath"
refid="maven.compile.classpath" />
+
+ <mkdir
dir="${javadoc.outputDirectory}/bindings" />
+ <javadoc
destdir="${javadoc.outputDirectory}/bindings" author="false"
version="true" windowtitle="RHQ ${project.version} Binding API"
noindex="false">
+ <classpath>
+ <pathelement
path="${maven.compile.classpath}" />
+ </classpath>
+ <fileset dir="${project.dir}"
defaultexcludes="yes">
+ <include name="**/RhqManagers.java"
/>
+ </fileset>
+ <link href="../remote-api/" />
+ <link
href="http://download.oracle.com/javase/6/docs/api/" />
+ <bottom><![CDATA[Copyright © 2005-2011
<a
href="http://redhat.com/">Red Hat, Inc.</a>. All Rights
Reserved.]]></bottom>
+ </javadoc>
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ </profile>
+
<profile>
<id>cobertura-plugins</id>
<activation>
@@ -363,4 +412,4 @@
</build>
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/enterprise/remoting/client-api/pom.xml
b/modules/enterprise/remoting/client-api/pom.xml
index 1a1c88c..bacb64b 100644
--- a/modules/enterprise/remoting/client-api/pom.xml
+++ b/modules/enterprise/remoting/client-api/pom.xml
@@ -146,18 +146,15 @@
<phase>compile</phase>
<configuration>
- <doctitle>RHQ ${project.version} - Client
API</doctitle>
+ <doctitle>RHQ ${project.version} Client
API</doctitle>
+ <windowtitle>RHQ ${project.version} Client
API</windowtitle>
<reportOutputDirectory>${javadoc.outputDirectory}</reportOutputDirectory>
<destDir>client-api</destDir>
- <aggregate>true</aggregate>
- <encoding>UTF-8</encoding>
- <charset>UTF-8</charset>
- <docencoding>UTF-8</docencoding>
<author>false</author>
<breakiterator>true</breakiterator>
- <links>
-
<
link>http://java.sun.com/j2se/1.5.0/docs/api/</link>
- <link>../remote-api</link>
+ <links>
+ <link>../remote-api/</link>
+ <link>../bindings/</link>
</links>
</configuration>
<goals>
diff --git a/modules/enterprise/server/jar/pom.xml
b/modules/enterprise/server/jar/pom.xml
index f49af4e..2c63486 100644
--- a/modules/enterprise/server/jar/pom.xml
+++ b/modules/enterprise/server/jar/pom.xml
@@ -768,30 +768,28 @@ Build-OS-Version=${os.version}
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
- <id>javadoc-remote-api</id>
+ <id>remote-api</id>
<phase>compile</phase>
<configuration>
<tasks>
<property name="javadoc.outputDirectory"
value="${javadoc.outputDirectory}" />
<property name="project.dir"
value="./src/main/java/org/rhq/enterprise/server" />
<property name="maven.compile.classpath"
refid="maven.compile.classpath" />
-
- <javadoc
destdir="${javadoc.outputDirectory}/remote-api" author="true"
version="true" windowtitle="Remote API" noindex="false">
+
+ <mkdir
dir="${javadoc.outputDirectory}/remote-api" />
+ <javadoc
destdir="${javadoc.outputDirectory}/remote-api" author="false"
version="true" windowtitle="RHQ ${project.version} Remote API"
noindex="false">
<classpath>
<pathelement
path="${maven.compile.classpath}" />
</classpath>
<fileset dir="${project.dir}"
defaultexcludes="yes">
<include name="**/*Remote.java" />
- <exclude name="**/*Test*.java" />
</fileset>
- <link href="../domain" />
- <link href="../plugin-api" />
- <link
href="http://java.sun.com/j2se/1.5.0/docs/api/" />
- <bottom><![CDATA[Copyright © 2008-2010
<a
href="http://rhq-project.org/">Red Hat, Inc.</a>. All Rights
Reserved.]]></bottom>
+ <link href="../domain/" />
+ <link
href="http://download.oracle.com/javase/6/docs/api/" />
+ <bottom><![CDATA[Copyright © 2005-2011
<a
href="http://redhat.com/">Red Hat, Inc.</a>. All Rights
Reserved.]]></bottom>
</javadoc>
</tasks>
</configuration>
@@ -806,6 +804,7 @@ Build-OS-Version=${os.version}
</build>
</profile>
+
<profile>
<id>cobertura</id>
<build>
diff --git a/modules/enterprise/server/plugins/alert-irc/pom.xml
b/modules/enterprise/server/plugins/alert-irc/pom.xml
index 1b609e1..c38aff4 100644
--- a/modules/enterprise/server/plugins/alert-irc/pom.xml
+++ b/modules/enterprise/server/plugins/alert-irc/pom.xml
@@ -65,7 +65,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -124,7 +123,6 @@
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-pircbot-jar</id>
@@ -160,7 +158,6 @@
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-pircbot-jar</id>
diff --git a/modules/enterprise/server/plugins/alert-microblog/pom.xml
b/modules/enterprise/server/plugins/alert-microblog/pom.xml
index ab68d6b..8574c9f 100644
--- a/modules/enterprise/server/plugins/alert-microblog/pom.xml
+++ b/modules/enterprise/server/plugins/alert-microblog/pom.xml
@@ -11,7 +11,6 @@
<artifactId>alert-microblog</artifactId>
<version>4.1.0-SNAPSHOT</version>
-
<name>RHQ Enterprise Server Microblog Alert Plugin</name>
<scm>
@@ -65,7 +64,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -124,7 +122,6 @@
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-twitter4j-jar</id>
@@ -159,7 +156,6 @@
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-twitter4j-jar</id>
@@ -270,4 +266,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/enterprise/server/plugins/alert-scriptlang/pom.xml
b/modules/enterprise/server/plugins/alert-scriptlang/pom.xml
index 5eb7f65..a9816b4 100644
--- a/modules/enterprise/server/plugins/alert-scriptlang/pom.xml
+++ b/modules/enterprise/server/plugins/alert-scriptlang/pom.xml
@@ -47,8 +47,7 @@
<build>
<plugins>
<plugin>
- <artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
+ <artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jruby-jar</id>
@@ -88,7 +87,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/enterprise/server/plugins/alert-sms/pom.xml
b/modules/enterprise/server/plugins/alert-sms/pom.xml
index 097de47..5b7a1c5 100644
--- a/modules/enterprise/server/plugins/alert-sms/pom.xml
+++ b/modules/enterprise/server/plugins/alert-sms/pom.xml
@@ -93,8 +93,7 @@
<plugins>
<plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
+ <artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
@@ -154,7 +153,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-resteasy-jars</id>
diff --git a/modules/enterprise/server/plugins/alert-snmp/pom.xml
b/modules/enterprise/server/plugins/alert-snmp/pom.xml
index 3763c54..bdee60f 100644
--- a/modules/enterprise/server/plugins/alert-snmp/pom.xml
+++ b/modules/enterprise/server/plugins/alert-snmp/pom.xml
@@ -64,7 +64,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -124,7 +123,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-snmp4j-jar</id>
diff --git a/modules/enterprise/server/plugins/ant-bundle/pom.xml
b/modules/enterprise/server/plugins/ant-bundle/pom.xml
index c4e59b2..26f4409 100644
--- a/modules/enterprise/server/plugins/ant-bundle/pom.xml
+++ b/modules/enterprise/server/plugins/ant-bundle/pom.xml
@@ -84,7 +84,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -158,7 +157,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -304,4 +302,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/enterprise/server/plugins/cloud/pom.xml
b/modules/enterprise/server/plugins/cloud/pom.xml
index d7d4b82..fcb145f 100644
--- a/modules/enterprise/server/plugins/cloud/pom.xml
+++ b/modules/enterprise/server/plugins/cloud/pom.xml
@@ -33,7 +33,6 @@
<!--
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-libs</id>
@@ -79,8 +78,7 @@
<plugins>
<plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
+ <artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
diff --git a/modules/enterprise/server/plugins/cobbler/pom.xml
b/modules/enterprise/server/plugins/cobbler/pom.xml
index 381f64c..bdfe647 100644
--- a/modules/enterprise/server/plugins/cobbler/pom.xml
+++ b/modules/enterprise/server/plugins/cobbler/pom.xml
@@ -46,7 +46,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-libs</id>
@@ -104,7 +103,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index b5eefb7..0330114 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -94,7 +94,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-libs</id>
@@ -148,7 +147,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -209,6 +207,7 @@
</plugins>
</build>
</profile>
+
<profile>
<id>cobertura-plugins</id>
<activation>
diff --git a/modules/enterprise/server/plugins/filetemplate-bundle/pom.xml
b/modules/enterprise/server/plugins/filetemplate-bundle/pom.xml
index ad1c570..8cae6d5 100644
--- a/modules/enterprise/server/plugins/filetemplate-bundle/pom.xml
+++ b/modules/enterprise/server/plugins/filetemplate-bundle/pom.xml
@@ -84,7 +84,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -133,7 +132,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -280,4 +278,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/enterprise/server/plugins/groovy-script/pom.xml
b/modules/enterprise/server/plugins/groovy-script/pom.xml
index 0d2bf4b..83bb64a 100644
--- a/modules/enterprise/server/plugins/groovy-script/pom.xml
+++ b/modules/enterprise/server/plugins/groovy-script/pom.xml
@@ -66,7 +66,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-libs</id>
diff --git a/modules/integration-tests/jboss-as-7-plugin-test/pom.xml
b/modules/integration-tests/jboss-as-7-plugin-test/pom.xml
index cc68acd..95c697b 100644
--- a/modules/integration-tests/jboss-as-7-plugin-test/pom.xml
+++ b/modules/integration-tests/jboss-as-7-plugin-test/pom.xml
@@ -32,7 +32,6 @@
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-postgres-driver</id>
@@ -82,3 +81,4 @@
</dependencies>
</project>
+
diff --git a/modules/jopr/dist/server/pom.xml b/modules/jopr/dist/server/pom.xml
index 5265fae..39a1f34 100644
--- a/modules/jopr/dist/server/pom.xml
+++ b/modules/jopr/dist/server/pom.xml
@@ -93,7 +93,6 @@
<!-- Package the Jopr plugins with the RHQ plugins -->
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-plugins</id>
@@ -160,7 +159,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -219,4 +217,4 @@
</build>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/JBossOSGi/pom.xml b/modules/plugins/JBossOSGi/pom.xml
index 1bcbfe6..9566be8 100644
--- a/modules/plugins/JBossOSGi/pom.xml
+++ b/modules/plugins/JBossOSGi/pom.xml
@@ -52,7 +52,6 @@
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
@@ -90,7 +89,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/ant-bundle/pom.xml b/modules/plugins/ant-bundle/pom.xml
index ff8c753..c62f40e 100644
--- a/modules/plugins/ant-bundle/pom.xml
+++ b/modules/plugins/ant-bundle/pom.xml
@@ -39,7 +39,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -211,7 +210,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/apache/pom.xml b/modules/plugins/apache/pom.xml
index e68547f..caf7f20 100644
--- a/modules/plugins/apache/pom.xml
+++ b/modules/plugins/apache/pom.xml
@@ -13,7 +13,7 @@
<packaging>jar</packaging>
<name>RHQ Apache Plugin</name>
- <description>a plugin for managing Apache web servers (1.3 or
2.0)</description>
+ <description>a plugin for managing Apache web servers (1.3 and
later)</description>
<scm>
<
connection>scm:git:ssh://git.fedorahosted.org/git/rhq.git/modules/plug...
@@ -80,7 +80,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -265,7 +264,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/byteman/pom.xml b/modules/plugins/byteman/pom.xml
index 46bcb55..5037c78 100644
--- a/modules/plugins/byteman/pom.xml
+++ b/modules/plugins/byteman/pom.xml
@@ -41,7 +41,6 @@
<!--
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -180,7 +179,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/cobbler/pom.xml b/modules/plugins/cobbler/pom.xml
index 78156f3..cb99a8c 100644
--- a/modules/plugins/cobbler/pom.xml
+++ b/modules/plugins/cobbler/pom.xml
@@ -209,7 +209,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -266,7 +265,6 @@
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-commons-io-jar</id>
@@ -376,3 +374,4 @@
</profiles>
</project>
+
diff --git a/modules/plugins/filetemplate-bundle/pom.xml
b/modules/plugins/filetemplate-bundle/pom.xml
index c1e0a3d..700e775 100644
--- a/modules/plugins/filetemplate-bundle/pom.xml
+++ b/modules/plugins/filetemplate-bundle/pom.xml
@@ -44,7 +44,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -187,7 +186,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/hibernate/pom.xml b/modules/plugins/hibernate/pom.xml
index e482d30..d40a69a 100644
--- a/modules/plugins/hibernate/pom.xml
+++ b/modules/plugins/hibernate/pom.xml
@@ -42,7 +42,6 @@
<!-- Used to add dependencies to the plugin lib
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-postgres-jar</id>
@@ -180,7 +179,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -324,4 +322,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/irc/pom.xml b/modules/plugins/irc/pom.xml
index edf12ea..3632ceb 100644
--- a/modules/plugins/irc/pom.xml
+++ b/modules/plugins/irc/pom.xml
@@ -27,7 +27,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependency-jars</id>
@@ -68,7 +67,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -249,3 +247,4 @@
</dependencies>
</project>
+
diff --git a/modules/plugins/jboss-as-5/pom.xml b/modules/plugins/jboss-as-5/pom.xml
index 6ec0096..ecea0e5 100644
--- a/modules/plugins/jboss-as-5/pom.xml
+++ b/modules/plugins/jboss-as-5/pom.xml
@@ -726,3 +726,4 @@
</reporting>
</project>
+
diff --git a/modules/plugins/jboss-as-5/testsuite/pom.xml
b/modules/plugins/jboss-as-5/testsuite/pom.xml
index 26e436f..6976c39 100644
--- a/modules/plugins/jboss-as-5/testsuite/pom.xml
+++ b/modules/plugins/jboss-as-5/testsuite/pom.xml
@@ -114,7 +114,6 @@
<artifactId>cactus</artifactId>
<version>13-1.7.1</version>
-
<exclusions>
<!-- Xerces causes AS5 Beta1 to blow up when it's included in the
JAR. That is, every context fails
to load. Cactus will still run without this JAR. jdobies, Feb 16, 2007. -->
@@ -167,7 +166,6 @@ available when compiling dependent classes; it is fixed in JDK 6.
-->
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dist-plugins</id>
@@ -228,3 +226,4 @@ available when compiling dependent classes; it is fixed in JDK 6.
-->
</build>
</project>
+
diff --git a/modules/plugins/jboss-cache-v3/pom.xml
b/modules/plugins/jboss-cache-v3/pom.xml
index 1a3a1df..56efc5b 100644
--- a/modules/plugins/jboss-cache-v3/pom.xml
+++ b/modules/plugins/jboss-cache-v3/pom.xml
@@ -287,7 +287,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
@@ -495,7 +494,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/jdbctrace/pom.xml b/modules/plugins/jdbctrace/pom.xml
index 6e2f30f..69d9ac3 100644
--- a/modules/plugins/jdbctrace/pom.xml
+++ b/modules/plugins/jdbctrace/pom.xml
@@ -70,7 +70,6 @@
<!--
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -209,7 +208,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/jira/pom.xml b/modules/plugins/jira/pom.xml
index 2b7494a..c2123dc 100644
--- a/modules/plugins/jira/pom.xml
+++ b/modules/plugins/jira/pom.xml
@@ -104,7 +104,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
@@ -120,7 +119,7 @@
</execution>
</executions>
</plugin>
-</plugins>
+ </plugins>
</build>
<profiles>
@@ -254,8 +253,7 @@
<plugins>
<plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
+ <artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
diff --git a/modules/plugins/jmx/pom.xml b/modules/plugins/jmx/pom.xml
index 1daf86d..0d35df2 100644
--- a/modules/plugins/jmx/pom.xml
+++ b/modules/plugins/jmx/pom.xml
@@ -39,7 +39,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-ems-jar</id>
@@ -195,7 +194,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -339,4 +337,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/lsof/pom.xml b/modules/plugins/lsof/pom.xml
index e5f457e..1c691f4 100644
--- a/modules/plugins/lsof/pom.xml
+++ b/modules/plugins/lsof/pom.xml
@@ -41,7 +41,6 @@
<!--
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-rhq-plugins</id>
@@ -180,7 +179,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/mysql/pom.xml b/modules/plugins/mysql/pom.xml
index d8ebb5d..835c57b 100644
--- a/modules/plugins/mysql/pom.xml
+++ b/modules/plugins/mysql/pom.xml
@@ -47,7 +47,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependency-jar</id>
@@ -182,7 +181,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -326,4 +324,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/netservices/pom.xml b/modules/plugins/netservices/pom.xml
index f1675e4..970f3ed 100644
--- a/modules/plugins/netservices/pom.xml
+++ b/modules/plugins/netservices/pom.xml
@@ -39,7 +39,6 @@
<version>${commons-codec.version}</version>
</dependency>
-
</dependencies>
<build>
@@ -48,7 +47,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependency-jars</id>
@@ -80,7 +78,6 @@
</build>
-
<profiles>
<profile>
<id>integration-tests</id>
@@ -189,7 +186,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -333,4 +329,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/onewire/pom.xml b/modules/plugins/onewire/pom.xml
index 07bec15..57b0ed0 100644
--- a/modules/plugins/onewire/pom.xml
+++ b/modules/plugins/onewire/pom.xml
@@ -36,7 +36,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-onewireapi-jar</id>
@@ -250,3 +249,4 @@
</dependencies>
</project>
+
diff --git a/modules/plugins/oracle/pom.xml b/modules/plugins/oracle/pom.xml
index 8a3b3c0..ea74b9f 100644
--- a/modules/plugins/oracle/pom.xml
+++ b/modules/plugins/oracle/pom.xml
@@ -51,7 +51,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-oracle-jar</id>
@@ -187,7 +186,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -332,4 +330,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/postgres/pom.xml b/modules/plugins/postgres/pom.xml
index 365f6c4..0bba426 100644
--- a/modules/plugins/postgres/pom.xml
+++ b/modules/plugins/postgres/pom.xml
@@ -46,7 +46,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-postgres-jar</id>
@@ -181,7 +180,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -325,4 +323,4 @@
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
diff --git a/modules/plugins/raw-config-test/pom.xml
b/modules/plugins/raw-config-test/pom.xml
index b3a6078..666329c 100644
--- a/modules/plugins/raw-config-test/pom.xml
+++ b/modules/plugins/raw-config-test/pom.xml
@@ -64,7 +64,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-deps</id>
@@ -144,7 +143,6 @@
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
<id>deploy</id>
diff --git a/modules/plugins/rhq-server/pom.xml b/modules/plugins/rhq-server/pom.xml
index e88b97f..b1c3d22 100644
--- a/modules/plugins/rhq-server/pom.xml
+++ b/modules/plugins/rhq-server/pom.xml
@@ -44,7 +44,6 @@
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-deps</id>
@@ -179,7 +178,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -322,4 +320,5 @@
</build>
</profile>
</profiles>
-</project>
\ No newline at end of file
+</project>
+
diff --git a/modules/plugins/script2/pom.xml b/modules/plugins/script2/pom.xml
index 2cf689c..e218ca8 100644
--- a/modules/plugins/script2/pom.xml
+++ b/modules/plugins/script2/pom.xml
@@ -37,7 +37,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-Script2-jar</id>
@@ -109,7 +108,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/snmptrapd/pom.xml b/modules/plugins/snmptrapd/pom.xml
index 05ed401..a52a978 100644
--- a/modules/plugins/snmptrapd/pom.xml
+++ b/modules/plugins/snmptrapd/pom.xml
@@ -33,7 +33,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-snmp4j-jar</id>
@@ -74,7 +73,6 @@
</executions>
</plugin>
-
</plugins>
</build>
@@ -93,7 +91,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/modules/plugins/twitter/pom.xml b/modules/plugins/twitter/pom.xml
index 50ff9b6..a13f91c 100644
--- a/modules/plugins/twitter/pom.xml
+++ b/modules/plugins/twitter/pom.xml
@@ -46,7 +46,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
@@ -105,7 +104,6 @@
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-twitter4j-jar</id>
diff --git a/modules/plugins/virt/pom.xml b/modules/plugins/virt/pom.xml
index 8700a19..e2fb957 100644
--- a/modules/plugins/virt/pom.xml
+++ b/modules/plugins/virt/pom.xml
@@ -52,7 +52,6 @@
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
@@ -220,7 +219,6 @@
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
- <version>1.1</version>
<executions>
<execution>
diff --git a/pom.xml b/pom.xml
index d4a2fd3..74ec29a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -539,7 +539,7 @@
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
- <version>2.1</version>
+ <version>2.3</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
@@ -571,7 +571,7 @@
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
- <version>2.7</version>
+ <version>2.8</version>
</plugin>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
@@ -595,7 +595,7 @@
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
- <version>2.2</version>
+ <version>3.0</version>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
@@ -661,7 +661,6 @@
</executions>
</plugin>
-
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
@@ -898,6 +897,29 @@
</plugin>
-->
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+
+ <execution>
+ <id>javadoc-dist</id>
+ <phase>site</phase>
+ <inherited>false</inherited>
+ <configuration>
+ <tasks>
+ <property name="apidocs.dir"
value="target/apidocs" />
+
+ <copy dir="modules/core/domain/target/site/apidocs"
todir="${apidocs.dir}/domain"/>
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+
+ </executions>
+ </plugin>
+
</plugins>
</build>
@@ -966,6 +988,7 @@
<profiles>
+
<profile>
<id>ojdbc-driver</id>
<activation>
@@ -1290,14 +1313,58 @@
<reporting>
<plugins>
+<!--
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+
+ <configuration>
+ <author>false</author>
+ <breakiterator>true</breakiterator>
+ <verbose>true</verbose>
+ </configuration>
+
+ <reportSets>
+ <reportSet>
+ <id>agent-plugin</id>
+ <configuration>
+ <doctitle>RHQ ${project.version} Agent Plugin
API</doctitle>
+ <destDir>agentPlugin-apidocs</destDir>
+
<subpackages>org.rhq.core.domain:org.rhq.core.util:org.rhq.core.system:org.rhq.core.pluginapi</subpackages>
+ </configuration>
+ <reports>
+ <report>aggregate</report>
+ </reports>
+ </reportSet>
+
+ <reportSet>
+ <id>remote</id>
+ <configuration>
+ <doctitle>RHQ ${project.version} Remote API</doctitle>
+ <windowtitle>RHQ ${project.version} Remote
API</windowtitle>
+ <destDir>remote-apidocs</destDir>
+
<subpackages>org.rhq.core.domain:org.rhq.enterprise.server:org.rhq.enterprise.client</subpackages>
+ <links>
+ <
link>http://java.sun.com/javaee/5/docs/api/</link>
+ </links>
+ </configuration>
+ <reports>
+ <report>aggregate</report>
+ </reports>
+ </reportSet>
+
+ </reportSets>
+ </plugin>
+-->
+<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
- <version>2.2</version>
+ <version>2.3</version>
<inherited>true</inherited>
</plugin>
-
+-->
+<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
@@ -1309,28 +1376,21 @@
</configuration>
<inherited>true</inherited>
</plugin>
-
+-->
+<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
<version>2.0-beta-2</version>
</plugin>
-<!--
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.7</version>
- <configuration>
- <aggregate>true</aggregate>
- <additionalJOption>-J-Xmx768m</additionalJOption>
- </configuration>
- </plugin>
-->
+<!--
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
- <version>2.6</version>
+ <version>2.9</version>
</plugin>
+-->
<!--
<plugin>
<groupId>org.codehaus.mojo</groupId>
@@ -1339,12 +1399,14 @@
<inherited>true</inherited>
</plugin>
-->
+<!--
<plugin>
- <!-- must be last plugin in the list -->
+ <!- - must be last plugin in the list - ->
<groupId>org.codehaus.mojo</groupId>
<artifactId>dashboard-maven-plugin</artifactId>
<version>1.0.0-beta-1</version>
</plugin>
+-->
</plugins>
</reporting>
commit 664793c8f8564784083e5886213548aa7a3c6507
Merge: e105c0e 786eb9d
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Sep 28 18:38:00 2011 -0400
merged master to feature/performance
commit e105c0ea9218bc4fb17d5a5d9321434d1193fc98
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Sep 28 17:45:05 2011 -0400
[BZ 734599] Change notification of schedule updates to agents so it uses quartz; use
unique quartz job and trigger names to avoid conflicts.
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 8ae6040..c2a5226 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -645,12 +645,15 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
final String DEFAULT_AGENT_GROUP = "AGENT NOTIFICATION GROUP";
final String DEFAULT_AGENT_TRIGGER = "AGENT NOTIFICATION TRIGGER";
+ final String randomSuffix = UUID.randomUUID().toString();
+
+ final String jobName = DEFAULT_AGENT_JOB + " - " + randomSuffix;
JobDetail jobDetail = new JobDetail(
- DEFAULT_AGENT_JOB,
+ jobName,
DEFAULT_AGENT_GROUP,
NotifyAgentsOfScheduleUpdatesJob.class);
- final String triggerName = UUID.randomUUID().toString();
+ final String triggerName = DEFAULT_AGENT_TRIGGER + " - " +
randomSuffix;
SimpleTrigger simpleTrigger = new SimpleTrigger(
triggerName,
DEFAULT_AGENT_GROUP,
commit 8dc174fc7d93c89e7840856d56798ae9c61fde1e
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Sep 27 14:37:41 2011 -0400
[BZ 734599] Change notification of schedule updates to agents so it uses quartz,
reducing the time to update a metric schedule on a compat group with 1,000 members from
14s to 1.5s.
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 3d537f4..8ae6040 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -29,6 +29,14 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Date;
+import java.util.UUID;
+
+import org.quartz.Trigger;
+import org.quartz.Scheduler;
+import org.quartz.JobDetail;
+import org.quartz.JobDataMap;
+import org.quartz.SimpleTrigger;
+import org.quartz.SchedulerException;
import javax.ejb.EJB;
import javax.ejb.Stateless;
@@ -620,6 +628,8 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
return affectedRows;
}
+ public static final String TRIGGER_NAME = "TriggerName";
+ public static final String TRIGGER_GROUP_NAME = "TriggerGroupName";
public static final String SCHEDULE_SUBQUERY = "ScheduleSubQuery";
public static final String ENTITYCONTEXT_RESOURCEID =
"EntityContext.resourceId";
public static final String ENTITYCONTEXT_GROUPID =
"EntityContext.groupId";
@@ -640,12 +650,15 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
DEFAULT_AGENT_GROUP,
NotifyAgentsOfScheduleUpdatesJob.class);
+ final String triggerName = UUID.randomUUID().toString();
SimpleTrigger simpleTrigger = new SimpleTrigger(
- DEFAULT_AGENT_TRIGGER,
+ triggerName,
DEFAULT_AGENT_GROUP,
new Date());
JobDataMap jobDataMap = simpleTrigger.getJobDataMap();
+ jobDataMap.put(TRIGGER_NAME, triggerName);
+ jobDataMap.put(TRIGGER_GROUP_NAME, DEFAULT_AGENT_GROUP);
jobDataMap.put(SCHEDULE_SUBQUERY, scheduleSubQuery);
jobDataMap.put(ENTITYCONTEXT_RESOURCEID,
Integer.toString(entityContext.getResourceId()));
jobDataMap.put(ENTITYCONTEXT_GROUPID,
Integer.toString(entityContext.getGroupId()));
@@ -655,11 +668,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
if (isJobScheduled(scheduler, DEFAULT_AGENT_JOB, DEFAULT_AGENT_GROUP)) {
simpleTrigger.setJobName(DEFAULT_AGENT_JOB);
simpleTrigger.setJobGroup(DEFAULT_AGENT_GROUP);
- if (isTriggerScheduled(scheduler, DEFAULT_AGENT_TRIGGER,
DEFAULT_AGENT_GROUP)) {
- scheduler.rescheduleJob(DEFAULT_AGENT_TRIGGER, DEFAULT_AGENT_GROUP,
simpleTrigger);
- } else {
- scheduler.scheduleJob(simpleTrigger);
- }
+ scheduler.scheduleJob(simpleTrigger);
} else {
scheduler.scheduleJob(jobDetail, simpleTrigger);
}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
index 86b3f7e..f560699 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
@@ -1,21 +1,38 @@
package org.rhq.enterprise.server.measurement;
import org.quartz.JobDataMap;
+import org.quartz.SchedulerException;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
+import org.rhq.enterprise.server.scheduler.SchedulerBean;
import org.rhq.enterprise.server.scheduler.jobs.AbstractStatefulJob;
import org.rhq.enterprise.server.util.LookupUtil;
import org.rhq.core.domain.common.EntityContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* Job that asynchronously notifies agents of schedule updates.
*/
public class NotifyAgentsOfScheduleUpdatesJob extends AbstractStatefulJob {
+
+ private final Log log = LogFactory.getLog(MeasurementScheduleManagerBean.class);
+
@Override
public void executeJobCode(JobExecutionContext context) throws JobExecutionException
{
MeasurementScheduleManagerLocal scheduleManager =
LookupUtil.getMeasurementScheduleManager();
JobDataMap jobDataMap = context.getMergedJobDataMap();
+
+ final String triggerName = (String)
jobDataMap.get(MeasurementScheduleManagerBean.TRIGGER_NAME);
+ final String triggerGroupName = (String)
jobDataMap.get(MeasurementScheduleManagerBean.TRIGGER_GROUP_NAME);
+ try {
+ context.getScheduler().unscheduleJob(triggerName, triggerGroupName);
+ } catch (SchedulerException e) {
+ log.error("Failed unscheduling Quartz trigger: " + triggerName,
e);
+ }
+
String scheduleSubQuery = (String)
jobDataMap.get(MeasurementScheduleManagerBean.SCHEDULE_SUBQUERY);
EntityContext entityContext = new EntityContext(
Integer.parseInt((String)
jobDataMap.get(MeasurementScheduleManagerBean.ENTITYCONTEXT_RESOURCEID)),
commit 1c2c9b4d16e1abcd939cdefe14ea2421f1c63850
Author: Robert Buck <rbuck(a)redhat.com>
Date: Mon Sep 26 19:42:06 2011 -0400
[bz 734599] fix schedule update changes per code review; added doc and renamed method
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 4e77320..3d537f4 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -46,7 +46,6 @@ import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.IgnoreDependency;
-import org.quartz.*;
import org.rhq.core.db.DatabaseType;
import org.rhq.core.db.DatabaseTypeFactory;
import org.rhq.core.db.H2DatabaseType;
@@ -582,7 +581,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
query.setParameter("interval", collectionInterval);
int affectedRows = query.executeUpdate();
- dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
+ scheduleJobToPushScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
@@ -599,7 +598,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
Query query = entityManager.createQuery(updateQuery);
int affectedRows = query.executeUpdate();
- dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
+ scheduleJobToPushScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
@@ -616,7 +615,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
Query query = entityManager.createQuery(updateQuery);
int affectedRows = query.executeUpdate();
- dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
+ scheduleJobToPushScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
@@ -627,7 +626,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
public static final String ENTITYCONTEXT_PARENT_RESOURCEID =
"EntityContext.parentResourceId";
public static final String ENTITYCONTEXT_RESOURCETYPEID =
"EntityContext.resourceTypeId";
- private void dispatchScheduleUpdatesToAgents(EntityContext entityContext, String
scheduleSubQuery) {
+ private void scheduleJobToPushScheduleUpdatesToAgents(EntityContext entityContext,
String scheduleSubQuery) {
Scheduler scheduler;
try {
scheduler = LookupUtil.getSchedulerBean();
@@ -667,6 +666,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
} catch (RuntimeException e) {
// lookup wrapper throws runtime exceptions, no distinction between
// types, so fallback and do the best we can.
+ log.error("Failed to schedule agents update notification.", e);
notifyAgentsOfScheduleUpdates(entityContext, scheduleSubQuery);
} catch (SchedulerException e) {
// should never happen, but fallback gracefully...
@@ -753,7 +753,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
(Long) nextScheduleDataSet[3], // interval,
(Boolean) nextScheduleDataSet[4], // enabled,
(DataType) nextScheduleDataSet[5], // dataType,
- (NumericType) nextScheduleDataSet[6]); // awNumericType
+ (NumericType) nextScheduleDataSet[6]); // rawNumericType
resourceRequest.addMeasurementScheduleRequest(requestData);
}
@@ -784,6 +784,13 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
}
}
+ /**
+ * The mtime on the Resources will tell the Agent it needs to pull down the
+ * latest schedules next time it performs an Agent-Server sync.
+ *
+ * @param context the entity context
+ * @param agentId the agent id
+ */
private void markResources(EntityContext context, int agentId) {
ResourceCriteria criteria = new ResourceCriteria();
if (context.type == EntityContext.Type.Resource) {
commit 3156a8fb2bb30e3b4f9ac0e7152c6bfdfc9cad1e
Author: Robert Buck <rbuck(a)redhat.com>
Date: Mon Sep 26 19:08:27 2011 -0400
[bz 734599] fix schedule update changes per code review
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 77f82e9..4e77320 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -22,7 +22,13 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
@@ -615,6 +621,12 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
return affectedRows;
}
+ public static final String SCHEDULE_SUBQUERY = "ScheduleSubQuery";
+ public static final String ENTITYCONTEXT_RESOURCEID =
"EntityContext.resourceId";
+ public static final String ENTITYCONTEXT_GROUPID =
"EntityContext.groupId";
+ public static final String ENTITYCONTEXT_PARENT_RESOURCEID =
"EntityContext.parentResourceId";
+ public static final String ENTITYCONTEXT_RESOURCETYPEID =
"EntityContext.resourceTypeId";
+
private void dispatchScheduleUpdatesToAgents(EntityContext entityContext, String
scheduleSubQuery) {
Scheduler scheduler;
try {
@@ -635,11 +647,11 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
new Date());
JobDataMap jobDataMap = simpleTrigger.getJobDataMap();
- jobDataMap.put("ScheduleSubQuery", scheduleSubQuery);
- jobDataMap.put("EntityContext.resourceId",
Integer.toString(entityContext.getResourceId()));
- jobDataMap.put("EntityContext.groupId",
Integer.toString(entityContext.getGroupId()));
- jobDataMap.put("EntityContext.parentResourceId",
Integer.toString(entityContext.getParentResourceId()));
- jobDataMap.put("EntityContext.resourceTypeId",
Integer.toString(entityContext.getResourceTypeId()));
+ jobDataMap.put(SCHEDULE_SUBQUERY, scheduleSubQuery);
+ jobDataMap.put(ENTITYCONTEXT_RESOURCEID,
Integer.toString(entityContext.getResourceId()));
+ jobDataMap.put(ENTITYCONTEXT_GROUPID,
Integer.toString(entityContext.getGroupId()));
+ jobDataMap.put(ENTITYCONTEXT_PARENT_RESOURCEID,
Integer.toString(entityContext.getParentResourceId()));
+ jobDataMap.put(ENTITYCONTEXT_RESOURCETYPEID,
Integer.toString(entityContext.getResourceTypeId()));
if (isJobScheduled(scheduler, DEFAULT_AGENT_JOB, DEFAULT_AGENT_GROUP)) {
simpleTrigger.setJobName(DEFAULT_AGENT_JOB);
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
index d61717a..86b3f7e 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
@@ -16,12 +16,12 @@ public class NotifyAgentsOfScheduleUpdatesJob extends
AbstractStatefulJob {
MeasurementScheduleManagerLocal scheduleManager =
LookupUtil.getMeasurementScheduleManager();
JobDataMap jobDataMap = context.getMergedJobDataMap();
- String scheduleSubQuery = (String) jobDataMap.get("ScheduleSubQuery");
+ String scheduleSubQuery = (String)
jobDataMap.get(MeasurementScheduleManagerBean.SCHEDULE_SUBQUERY);
EntityContext entityContext = new EntityContext(
- Integer.parseInt((String)
jobDataMap.get("EntityContext.resourceId")),
- Integer.parseInt((String)
jobDataMap.get("EntityContext.groupId")),
- Integer.parseInt((String)
jobDataMap.get("EntityContext.parentResourceId")),
- Integer.parseInt((String)
jobDataMap.get("EntityContext.resourceTypeId"))
+ Integer.parseInt((String)
jobDataMap.get(MeasurementScheduleManagerBean.ENTITYCONTEXT_RESOURCEID)),
+ Integer.parseInt((String)
jobDataMap.get(MeasurementScheduleManagerBean.ENTITYCONTEXT_GROUPID)),
+ Integer.parseInt((String)
jobDataMap.get(MeasurementScheduleManagerBean.ENTITYCONTEXT_PARENT_RESOURCEID)),
+ Integer.parseInt((String)
jobDataMap.get(MeasurementScheduleManagerBean.ENTITYCONTEXT_RESOURCETYPEID))
);
scheduleManager.notifyAgentsOfScheduleUpdates(entityContext, scheduleSubQuery);
commit fece00f1862612104aef1439fb02c4f7a35d797e
Author: Robert Buck <rbuck(a)redhat.com>
Date: Mon Sep 26 08:54:05 2011 -0400
oracle em cites lots of open cursor issues; fix open cursor leaks by closing result
sets and prepared statements in finally blocks.
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentManagerBean.java
index 9915959..121ea7e 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentManagerBean.java
@@ -1901,7 +1901,7 @@ public class ContentManagerBean implements ContentManagerLocal,
ContentManagerRe
ps = conn.prepareStatement("SELECT BITS FROM " +
PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE");
ps.setInt(1, bits.getId());
ResultSet rs = ps.executeQuery();
- if (rs != null) {
+ try {
while (rs.next()) {
//We can not create a blob directly because BlobImpl from Hibernate
is not acceptable
@@ -1924,6 +1924,8 @@ public class ContentManagerBean implements ContentManagerLocal,
ContentManagerRe
}
ps2.close();
}
+ } finally {
+ rs.close();
}
ps.close();
conn.close();
@@ -2048,15 +2050,22 @@ public class ContentManagerBean implements ContentManagerLocal,
ContentManagerRe
Connection conn = dataSource.getConnection();
//prepared statement for retrieval of Blob.bits
- PreparedStatement ps = conn
- .prepareStatement("SELECT BITS FROM " + PackageBits.TABLE_NAME
+ " WHERE ID = ?");
- ps.setInt(1, bits.getId());
- ResultSet results = ps.executeQuery();
- if (results.next()) {
- //retrieve the Blob
- Blob blob = results.getBlob(1);
- //now copy the contents to the stream passed in
- StreamUtil.copy(blob.getBinaryStream(), stream, closeStreams);
+ PreparedStatement ps = conn.prepareStatement("SELECT BITS FROM " +
PackageBits.TABLE_NAME + " WHERE ID = ?");
+ try {
+ ps.setInt(1, bits.getId());
+ ResultSet results = ps.executeQuery();
+ try {
+ if (results.next()) {
+ //retrieve the Blob
+ Blob blob = results.getBlob(1);
+ //now copy the contents to the stream passed in
+ StreamUtil.copy(blob.getBinaryStream(), stream, closeStreams);
+ }
+ } finally {
+ results.close();
+ }
+ } finally {
+ ps.close();
}
} catch (Exception ex) {
log.error("An error occurred while writing Blob contents out to stream
:" + ex.getMessage());
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentSourceManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentSourceManagerBean.java
index 764f542..5f65afb 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentSourceManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/content/ContentSourceManagerBean.java
@@ -853,7 +853,7 @@ public class ContentSourceManagerBean implements
ContentSourceManagerLocal {
+ " WHERE ID = ? FOR UPDATE");
ps.setInt(1, packageBits.getId());
ResultSet rs = ps.executeQuery();
- if (rs != null) {
+ try {
while (rs.next()) {
//We can not create a blob directly because BlobImpl from
Hibernate is not acceptable
//for oracle and Connection.createBlob is not working on
postgres.
@@ -870,6 +870,8 @@ public class ContentSourceManagerBean implements
ContentSourceManagerLocal {
}
ps2.close();
}
+ } finally {
+ rs.close();
}
ps.close();
conn.close();
@@ -1088,7 +1090,7 @@ public class ContentSourceManagerBean implements
ContentSourceManagerLocal {
+ " WHERE ID = ? FOR UPDATE");
ps.setInt(1, packageBits.getId());
ResultSet rs = ps.executeQuery();
- if (rs != null) {
+ try {
while (rs.next()) {
//We can not create a blob directly because BlobImpl from
Hibernate is not acceptable
@@ -1107,6 +1109,8 @@ public class ContentSourceManagerBean implements
ContentSourceManagerLocal {
}
ps2.close();
}
+ } finally {
+ rs.close();
}
ps.close();
conn.close();
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index abfae0c..77f82e9 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -1081,28 +1081,32 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
Map<Integer, ResourceMeasurementScheduleRequest> scheduleRequestMap =
new HashMap<Integer, ResourceMeasurementScheduleRequest>();
ResultSet results = resultsStatement.executeQuery();
- while (results.next()) {
- Integer resourceId = (Integer) results.getInt(1);
- Integer scheduleId = (Integer) results.getInt(2);
- String definitionName = (String) results.getString(3);
- Long interval = (Long) results.getLong(4);
- Boolean enabled = (Boolean) results.getBoolean(5);
- DataType dataType = DataType.values()[results.getInt(6)];
- NumericType rawNumericType = NumericType.values()[results.getInt(7)];
- if (results.wasNull()) {
- rawNumericType = null;
- }
+ try {
+ while (results.next()) {
+ Integer resourceId = (Integer) results.getInt(1);
+ Integer scheduleId = (Integer) results.getInt(2);
+ String definitionName = (String) results.getString(3);
+ Long interval = (Long) results.getLong(4);
+ Boolean enabled = (Boolean) results.getBoolean(5);
+ DataType dataType = DataType.values()[results.getInt(6)];
+ NumericType rawNumericType =
NumericType.values()[results.getInt(7)];
+ if (results.wasNull()) {
+ rawNumericType = null;
+ }
- ResourceMeasurementScheduleRequest scheduleRequest =
scheduleRequestMap.get(resourceId);
- if (scheduleRequest == null) {
- scheduleRequest = new
ResourceMeasurementScheduleRequest(resourceId);
- scheduleRequestMap.put(resourceId, scheduleRequest);
- allSchedules.add(scheduleRequest);
- }
+ ResourceMeasurementScheduleRequest scheduleRequest =
scheduleRequestMap.get(resourceId);
+ if (scheduleRequest == null) {
+ scheduleRequest = new
ResourceMeasurementScheduleRequest(resourceId);
+ scheduleRequestMap.put(resourceId, scheduleRequest);
+ allSchedules.add(scheduleRequest);
+ }
- MeasurementScheduleRequest requestData = new
MeasurementScheduleRequest(scheduleId, definitionName,
- interval, enabled, dataType, rawNumericType);
- scheduleRequest.addMeasurementScheduleRequest(requestData);
+ MeasurementScheduleRequest requestData = new
MeasurementScheduleRequest(scheduleId, definitionName,
+ interval, enabled, dataType, rawNumericType);
+ scheduleRequest.addMeasurementScheduleRequest(requestData);
+ }
+ } finally {
+ results.close();
}
} finally {
if (resultsStatement != null) {
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataInserter.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataInserter.java
index 1aabf92..ac26ed5 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataInserter.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataInserter.java
@@ -46,15 +46,20 @@ public class DataInserter {
try {
List<Integer> scheduleIds = new ArrayList<Integer>();
Statement s = c.createStatement();
- ResultSet rs = s.executeQuery("SELECT id FROM
RHQ_MEASUREMENT_SCHED");
-
- while (rs.next() && (numSchedules > 0)) {
- scheduleIds.add(rs.getInt(1));
- numSchedules--;
+ try {
+ ResultSet rs = s.executeQuery("SELECT id FROM
RHQ_MEASUREMENT_SCHED");
+ try {
+ while (rs.next() && (numSchedules > 0)) {
+ scheduleIds.add(rs.getInt(1));
+ numSchedules--;
+ }
+ } finally {
+ rs.close();
+ }
+ } finally {
+ s.close();
}
- JDBCUtil.safeClose(s, rs);
-
System.out.println("INSERTING for " + scheduleIds.size() + "
schedules starting at " + new Date(time));
for (long i = 0; i < HOUR; i += INTERVAL) {
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataReader.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataReader.java
index 7e0ca13..ddf6215 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataReader.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/util/DataReader.java
@@ -61,9 +61,25 @@ public class DataReader {
StringBuilder fullSql = new StringBuilder(sql);
PreparedStatement ps = c.prepareStatement(sql);
+ try {
+ int i = 1;
+ for (String table : tables) {
+ ps.setLong(i++, beginTime); // 1) begin
+ fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(beginTime));
+
+ ps.setLong(i++, interval); // 2) interval
+ fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(interval));
+
+ ps.setLong(i++, numberOfDataPoints); // 3) points
+ fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(numberOfDataPoints));
+
+ ps.setLong(i++, interval); // 4) interval
+ fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(interval));
+
+ ps.setInt(i++, 0); // schedule_id
+ fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(0));
+ }
- int i = 1;
- for (String table : tables) {
ps.setLong(i++, beginTime); // 1) begin
fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(beginTime));
@@ -73,45 +89,35 @@ public class DataReader {
ps.setLong(i++, numberOfDataPoints); // 3) points
fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(numberOfDataPoints));
- ps.setLong(i++, interval); // 4) interval
- fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(interval));
-
- ps.setInt(i++, 0); // schedule_id
- fullSql.replace(fullSql.indexOf("?"),
fullSql.indexOf("?") + 1, String.valueOf(0));
- }
-
- ps.setLong(i++, beginTime); // 1) begin
- fullSql.replace(fullSql.indexOf("?"), fullSql.indexOf("?") +
1, String.valueOf(beginTime));
-
- ps.setLong(i++, interval); // 2) interval
- fullSql.replace(fullSql.indexOf("?"), fullSql.indexOf("?") +
1, String.valueOf(interval));
-
- ps.setLong(i++, numberOfDataPoints); // 3) points
- fullSql.replace(fullSql.indexOf("?"), fullSql.indexOf("?") +
1, String.valueOf(numberOfDataPoints));
-
- System.out.println("-------------------------------------");
- System.out.println("\n\n\nFinal sql was:\n" + fullSql.toString());
- System.out.println("-------------------------------------");
-
- long timingStart = System.currentTimeMillis();
- ResultSet rs = ps.executeQuery();
- System.out.println("Executed query in: " + (System.currentTimeMillis()
- timingStart) + "ms");
-
- int count = 0;
- long lastStart = 0;
- while (rs.next()) {
- count++;
- if (lastStart != 0) {
- System.out.println(Arrays.deepToString(MeasurementDataManagerUtility
- .getTables(lastStart, rs.getLong(1))));
+ System.out.println("-------------------------------------");
+ System.out.println("\n\n\nFinal sql was:\n" + fullSql.toString());
+ System.out.println("-------------------------------------");
+
+ long timingStart = System.currentTimeMillis();
+ ResultSet rs = ps.executeQuery();
+ try {
+ System.out.println("Executed query in: " +
(System.currentTimeMillis() - timingStart) + "ms");
+
+ int count = 0;
+ long lastStart = 0;
+ while (rs.next()) {
+ count++;
+ if (lastStart != 0) {
+
System.out.println(Arrays.deepToString(MeasurementDataManagerUtility
+ .getTables(lastStart, rs.getLong(1))));
+ }
+
+ lastStart = rs.getLong(1);
+ System.out.println(new Date(rs.getLong(1)) + " - avg: " +
rs.getDouble(2) + " - max: " + rs.getDouble(3)
+ + " - min: " + rs.getDouble(4));
+ }
+ System.out.println("Count: " + count);
+ } finally {
+ rs.close();
}
-
- lastStart = rs.getLong(1);
- System.out.println(new Date(rs.getLong(1)) + " - avg: " +
rs.getDouble(2) + " - max: " + rs.getDouble(3)
- + " - min: " + rs.getDouble(4));
+ } finally {
+ ps.close();
}
-
- System.out.println("Count: " + count);
}
public static String getTableString(String table) {
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java
index b88f9ae..cce96d4 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java
@@ -1150,14 +1150,18 @@ public class ResourceGroupManagerBean implements
ResourceGroupManagerLocal, Reso
}
ResultSet rs = stmt.executeQuery();
- while (rs.next()) {
- long explicitCount = rs.getLong(1);
- double explicitAvail = rs.getDouble(2);
- long implicitCount = rs.getLong(3);
- double implicitAvail = rs.getDouble(4);
- int groupKey = rs.getInt(5);
- Object[] next = new Object[] { explicitCount, explicitAvail,
implicitCount, implicitAvail, groupKey };
- rawResults.add(next);
+ try {
+ while (rs.next()) {
+ long explicitCount = rs.getLong(1);
+ double explicitAvail = rs.getDouble(2);
+ long implicitCount = rs.getLong(3);
+ double implicitAvail = rs.getDouble(4);
+ int groupKey = rs.getInt(5);
+ Object[] next = new Object[]{explicitCount, explicitAvail,
implicitCount, implicitAvail, groupKey};
+ rawResults.add(next);
+ }
+ } finally {
+ rs.close();
}
} catch (Throwable t) {
log.error("Could not execute groups query [ " + query + " ]:
", t);
diff --git
a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/dbunit/EntityRelationshipFilter.java
b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/dbunit/EntityRelationshipFilter.java
index 0d6bf9a..c35d8c6 100644
---
a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/dbunit/EntityRelationshipFilter.java
+++
b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/dbunit/EntityRelationshipFilter.java
@@ -422,33 +422,33 @@ public class EntityRelationshipFilter extends DatabaseSequenceFilter
{
sql.replace(sql.length() - 4, sql.length(), "");
- PreparedStatement st = null;
+ PreparedStatement st =
connection.getConnection().prepareStatement(sql.toString());
try {
- st = connection.getConnection().prepareStatement(sql.toString());
int idx = 1;
for (ColumnValues.Column c : cols) {
st.setObject(idx++, c.getValue());
}
ResultSet rs = st.executeQuery();
+ try {
+ ResultSetMetaData rsmd = rs.getMetaData();
- ResultSetMetaData rsmd = rs.getMetaData();
+ while (rs.next()) {
+ ColumnValues vals = new ColumnValues();
- while (rs.next()) {
- ColumnValues vals = new ColumnValues();
+ for (int i = 1; i <= rsmd.getColumnCount(); ++i) {
+ String columnName = rsmd.getColumnName(i);
+ Object value = rs.getObject(i);
+ vals.add(columnName, value);
+ }
- for (int i = 1; i <= rsmd.getColumnCount(); ++i) {
- String columnName = rsmd.getColumnName(i);
- Object value = rs.getObject(i);
- vals.add(columnName, value);
+ ret.add(vals);
}
-
- ret.add(vals);
+ } finally {
+ rs.close();
}
} finally {
- if (st != null) {
- st.close();
- }
+ st.close();
}
}
diff --git
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseComponent.java
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseComponent.java
index d6380b7..f235f93 100644
---
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseComponent.java
+++
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseComponent.java
@@ -113,15 +113,18 @@ public class PostgresDatabaseComponent implements
DatabaseComponent<PostgresServ
statement.setString(1,
this.resourceContext.getPluginConfiguration().getSimple("databaseName")
.getStringValue());
ResultSet results = statement.executeQuery();
+ try {
+ if (!results.next()) {
+ throw new RuntimeException("Couldn't get the data"); //
TODO Error handling system
+ }
- if (!results.next()) {
- throw new RuntimeException("Couldn't get the data"); //
TODO Error handling system
- }
-
- for (MeasurementScheduleRequest request : metrics) {
- // Only size expected
- double val = results.getDouble(request.getName());
- report.addData(new MeasurementDataNumeric(request, val));
+ for (MeasurementScheduleRequest request : metrics) {
+ // Only size expected
+ double val = results.getDouble(request.getName());
+ report.addData(new MeasurementDataNumeric(request, val));
+ }
+ } finally {
+ results.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
diff --git
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseDiscoveryComponent.java
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseDiscoveryComponent.java
index f7f6f56..cfc60b2 100644
---
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseDiscoveryComponent.java
+++
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresDatabaseDiscoveryComponent.java
@@ -51,7 +51,7 @@ public class PostgresDatabaseDiscoveryComponent implements
ResourceDiscoveryComp
databases.add(database);
}
} finally {
- JDBCUtil.safeClose(statement);
+ JDBCUtil.safeClose(statement, resultSet);
}
return databases;
diff --git
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresServerComponent.java
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresServerComponent.java
index f80f288..52f2e91 100644
---
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresServerComponent.java
+++
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresServerComponent.java
@@ -273,16 +273,25 @@ public class PostgresServerComponent<T extends
ResourceComponent<?>> implements
try {
if (property.endsWith("startTime")) {
// db start time
- ResultSet rs =
getConnection().createStatement().executeQuery("SELECT
pg_postmaster_start_time()");
- if (rs.next())
- report.addData(new MeasurementDataTrait(request,
rs.getTimestamp(1).toString()));
-
+ ResultSet rs =
getConnection().createStatement().executeQuery("SELECT
pg_postmaster_start_time()");
+ try {
+ if (rs.next()) {
+ report.addData(new MeasurementDataTrait(request,
rs.getTimestamp(1).toString()));
+ }
+ } finally {
+ rs.close();
+ }
}
else if (property.endsWith("backends")) {
- // number of connected backends
- ResultSet rs =
getConnection().createStatement().executeQuery("select count(*) from
pg_stat_activity");
- if (rs.next())
- report.addData(new MeasurementDataNumeric(request,
(double)rs.getLong(1)));
+ // number of connected backends
+ ResultSet rs =
getConnection().createStatement().executeQuery("select count(*) from
pg_stat_activity");
+ try {
+ if (rs.next()) {
+ report.addData(new MeasurementDataNumeric(request, (double)
rs.getLong(1)));
+ }
+ } finally {
+ rs.close();
+ }
}
}
diff --git
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableComponent.java
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableComponent.java
index 6fb651a..9dc07bd 100644
---
a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableComponent.java
+++
b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableComponent.java
@@ -121,24 +121,27 @@ public class PostgresTableComponent implements
DatabaseComponent<PostgresDatabas
DatabaseMetaData dmd = connection.getMetaData();
ResultSet rs = dmd.getColumns("", "", getTableName(),
"");
+ try {
+ PropertyList columnList = new PropertyList("columns");
- PropertyList columnList = new PropertyList("columns");
+ while (rs.next()) {
+ PropertyMap col = new PropertyMap("columnDefinition");
- while (rs.next()) {
- PropertyMap col = new PropertyMap("columnDefinition");
+ col.put(new PropertySimple("columnName",
rs.getString("COLUMN_NAME")));
+ col.put(new PropertySimple("columnType",
rs.getString("TYPE_NAME")));
+ col.put(new PropertySimple("columnLength",
rs.getInt("COLUMN_SIZE")));
+ col.put(new PropertySimple("columnPrecision",
rs.getInt("DECIMAL_DIGITS")));
+ col.put(new PropertySimple("columnDefault",
rs.getString("COLUMN_DEF")));
+ col.put(new PropertySimple("columnNullable",
rs.getBoolean("IS_NULLABLE")));
- col.put(new PropertySimple("columnName",
rs.getString("COLUMN_NAME")));
- col.put(new PropertySimple("columnType",
rs.getString("TYPE_NAME")));
- col.put(new PropertySimple("columnLength",
rs.getInt("COLUMN_SIZE")));
- col.put(new PropertySimple("columnPrecision",
rs.getInt("DECIMAL_DIGITS")));
- col.put(new PropertySimple("columnDefault",
rs.getString("COLUMN_DEF")));
- col.put(new PropertySimple("columnNullable",
rs.getBoolean("IS_NULLABLE")));
+ columnList.add(col);
+ }
- columnList.add(col);
+ config.put(columnList);
+ } finally {
+ rs.close();
}
- config.put(columnList);
-
return config;
}
@@ -151,11 +154,14 @@ public class PostgresTableComponent implements
DatabaseComponent<PostgresDatabas
DatabaseMetaData dmd = connection.getMetaData();
ResultSet rs = dmd.getColumns("", "", getTableName(),
"");
-
Map<String, ColumnDefinition> existingDefs = new HashMap<String,
ColumnDefinition>();
- while (rs.next()) {
- ColumnDefinition def = new ColumnDefinition(rs);
- existingDefs.put(def.columnName, def);
+ try {
+ while (rs.next()) {
+ ColumnDefinition def = new ColumnDefinition(rs);
+ existingDefs.put(def.columnName, def);
+ }
+ } finally {
+ rs.close();
}
for (Property newColumnDefinition : updatedColumns.getList()) {
commit f93ffa9d47045e3026f3297b63ca2473bad36d73
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 15 11:03:34 2011 -0400
[BZ 734599] Change notification of schedule updates to agents so it uses quartz,
reducing the time to update a metric schedule on a compat group with 1,000 members from
14s to 1.5s.
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 0b1c394..abfae0c 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -22,12 +22,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import javax.ejb.EJB;
import javax.ejb.Stateless;
@@ -45,6 +40,7 @@ import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.IgnoreDependency;
+import org.quartz.*;
import org.rhq.core.db.DatabaseType;
import org.rhq.core.db.DatabaseTypeFactory;
import org.rhq.core.db.H2DatabaseType;
@@ -580,7 +576,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
query.setParameter("interval", collectionInterval);
int affectedRows = query.executeUpdate();
- notifyAgentsOfScheduleUpdates(context, measurementScheduleSubQuery);
+ dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
@@ -597,7 +593,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
Query query = entityManager.createQuery(updateQuery);
int affectedRows = query.executeUpdate();
- notifyAgentsOfScheduleUpdates(context, measurementScheduleSubQuery);
+ dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
@@ -614,20 +610,93 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
Query query = entityManager.createQuery(updateQuery);
int affectedRows = query.executeUpdate();
- notifyAgentsOfScheduleUpdates(context, measurementScheduleSubQuery);
+ dispatchScheduleUpdatesToAgents(context, measurementScheduleSubQuery);
return affectedRows;
}
- @SuppressWarnings("unchecked")
- private void notifyAgentsOfScheduleUpdates(EntityContext context, String
measurementScheduleSubQuery) {
+ private void dispatchScheduleUpdatesToAgents(EntityContext entityContext, String
scheduleSubQuery) {
+ Scheduler scheduler;
+ try {
+ scheduler = LookupUtil.getSchedulerBean();
+
+ final String DEFAULT_AGENT_JOB = "AGENT NOTIFICATION JOB";
+ final String DEFAULT_AGENT_GROUP = "AGENT NOTIFICATION GROUP";
+ final String DEFAULT_AGENT_TRIGGER = "AGENT NOTIFICATION TRIGGER";
+
+ JobDetail jobDetail = new JobDetail(
+ DEFAULT_AGENT_JOB,
+ DEFAULT_AGENT_GROUP,
+ NotifyAgentsOfScheduleUpdatesJob.class);
+
+ SimpleTrigger simpleTrigger = new SimpleTrigger(
+ DEFAULT_AGENT_TRIGGER,
+ DEFAULT_AGENT_GROUP,
+ new Date());
+
+ JobDataMap jobDataMap = simpleTrigger.getJobDataMap();
+ jobDataMap.put("ScheduleSubQuery", scheduleSubQuery);
+ jobDataMap.put("EntityContext.resourceId",
Integer.toString(entityContext.getResourceId()));
+ jobDataMap.put("EntityContext.groupId",
Integer.toString(entityContext.getGroupId()));
+ jobDataMap.put("EntityContext.parentResourceId",
Integer.toString(entityContext.getParentResourceId()));
+ jobDataMap.put("EntityContext.resourceTypeId",
Integer.toString(entityContext.getResourceTypeId()));
+
+ if (isJobScheduled(scheduler, DEFAULT_AGENT_JOB, DEFAULT_AGENT_GROUP)) {
+ simpleTrigger.setJobName(DEFAULT_AGENT_JOB);
+ simpleTrigger.setJobGroup(DEFAULT_AGENT_GROUP);
+ if (isTriggerScheduled(scheduler, DEFAULT_AGENT_TRIGGER,
DEFAULT_AGENT_GROUP)) {
+ scheduler.rescheduleJob(DEFAULT_AGENT_TRIGGER, DEFAULT_AGENT_GROUP,
simpleTrigger);
+ } else {
+ scheduler.scheduleJob(simpleTrigger);
+ }
+ } else {
+ scheduler.scheduleJob(jobDetail, simpleTrigger);
+ }
+ } catch (RuntimeException e) {
+ // lookup wrapper throws runtime exceptions, no distinction between
+ // types, so fallback and do the best we can.
+ notifyAgentsOfScheduleUpdates(entityContext, scheduleSubQuery);
+ } catch (SchedulerException e) {
+ // should never happen, but fallback gracefully...
+ log.error("Failed to schedule agents update notification.", e);
+ notifyAgentsOfScheduleUpdates(entityContext, scheduleSubQuery);
+ }
+ }
+
+ private boolean isTriggerScheduled(Scheduler scheduler, String name, String group) {
+ boolean isScheduled = false;
+ try {
+ Trigger trigger = scheduler.getTrigger(name, group);
+ if (trigger != null) {
+ isScheduled = true;
+ }
+ } catch (SchedulerException se) {
+ log.error("Error getting trigger", se);
+ }
+ return isScheduled;
+ }
+
+ private boolean isJobScheduled(Scheduler scheduler, String name, String group) {
+ boolean isScheduled = false;
+ try {
+ JobDetail jobDetail = scheduler.getJobDetail(name, group);
+ if (jobDetail != null) {
+ isScheduled = true;
+ }
+ } catch (SchedulerException se) {
+ log.error("Error getting job detail", se);
+ }
+ return isScheduled;
+ }
+ @SuppressWarnings("unchecked")
+ public void notifyAgentsOfScheduleUpdates(EntityContext entityContext, String
scheduleSubQuery) {
List<Integer> agentIds = new ArrayList<Integer>();
try {
String agentsQueryString = "" //
+ "SELECT DISTINCT ms.resource.agent.id " //
+ " FROM MeasurementSchedule ms " //
- + " WHERE ms.id IN ( " + measurementScheduleSubQuery + " )
";
+ + " WHERE ms.id IN ( " + scheduleSubQuery + " ) ";
if (log.isDebugEnabled()) {
log.debug("agentsQueryString: " + agentsQueryString);
}
@@ -647,7 +716,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
+ " ms.definition.dataType, " //
+ " ms.definition.rawNumericType " //
+ " FROM MeasurementSchedule ms " //
- + " WHERE ms.id IN ( " + measurementScheduleSubQuery + " )
" //
+ + " WHERE ms.id IN ( " + scheduleSubQuery + " ) " //
+ " AND ms.resource.agent.id = :agentId";
if (log.isDebugEnabled()) {
log.debug("scheduleRequestQueryString: " +
scheduleRequestQueryString);
@@ -669,9 +738,9 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
MeasurementScheduleRequest requestData = new MeasurementScheduleRequest(
//
(Integer) nextScheduleDataSet[1], // scheduleId
(String) nextScheduleDataSet[2], // definitionName,
- (Long) nextScheduleDataSet[3], // interval,
- (Boolean) nextScheduleDataSet[4], // enabled,
- (DataType) nextScheduleDataSet[5], // dataType,
+ (Long) nextScheduleDataSet[3], // interval,
+ (Boolean) nextScheduleDataSet[4], // enabled,
+ (DataType) nextScheduleDataSet[5], // dataType,
(NumericType) nextScheduleDataSet[6]); // awNumericType
resourceRequest.addMeasurementScheduleRequest(requestData);
}
@@ -698,7 +767,7 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
}
if (markResources) {
- markResources(context, nextAgentId);
+ markResources(entityContext, nextAgentId);
}
}
}
@@ -1417,4 +1486,5 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
// }
// }
-}
\ No newline at end of file
+}
+
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java
index 9edf221..77ee167 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java
@@ -373,4 +373,10 @@ public interface MeasurementScheduleManagerLocal {
*/
PageList<MeasurementSchedule> findSchedulesByCriteria(Subject subject,
MeasurementScheduleCriteria criteria);
+ /**
+ * Notifies all agents of measurement schedule changes.
+ * @param entityContext the context.
+ * @param scheduleSubQuery the subquery indicating which schedules changed
+ */
+ void notifyAgentsOfScheduleUpdates(EntityContext entityContext, String
scheduleSubQuery);
}
\ No newline at end of file
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
new file mode 100644
index 0000000..d61717a
--- /dev/null
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/NotifyAgentsOfScheduleUpdatesJob.java
@@ -0,0 +1,29 @@
+package org.rhq.enterprise.server.measurement;
+
+import org.quartz.JobDataMap;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.rhq.enterprise.server.scheduler.jobs.AbstractStatefulJob;
+import org.rhq.enterprise.server.util.LookupUtil;
+import org.rhq.core.domain.common.EntityContext;
+
+/**
+ * Job that asynchronously notifies agents of schedule updates.
+ */
+public class NotifyAgentsOfScheduleUpdatesJob extends AbstractStatefulJob {
+ @Override
+ public void executeJobCode(JobExecutionContext context) throws JobExecutionException
{
+ MeasurementScheduleManagerLocal scheduleManager =
LookupUtil.getMeasurementScheduleManager();
+
+ JobDataMap jobDataMap = context.getMergedJobDataMap();
+ String scheduleSubQuery = (String) jobDataMap.get("ScheduleSubQuery");
+ EntityContext entityContext = new EntityContext(
+ Integer.parseInt((String)
jobDataMap.get("EntityContext.resourceId")),
+ Integer.parseInt((String)
jobDataMap.get("EntityContext.groupId")),
+ Integer.parseInt((String)
jobDataMap.get("EntityContext.parentResourceId")),
+ Integer.parseInt((String)
jobDataMap.get("EntityContext.resourceTypeId"))
+ );
+
+ scheduleManager.notifyAgentsOfScheduleUpdates(entityContext, scheduleSubQuery);
+ }
+}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/EnhancedScheduler.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/EnhancedScheduler.java
index 1fc2c71..b10f627 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/EnhancedScheduler.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/EnhancedScheduler.java
@@ -24,7 +24,7 @@ import org.quartz.Scheduler;
import org.quartz.SchedulerException;
/**
- * An enhanced scheduler interface that provides the normal scheduler API with some
additional convienence methods.
+ * An enhanced scheduler interface that provides the normal scheduler API with some
additional convenience methods.
*
* @author John Mazzitelli
*/
commit 038df495706986f3d0ba03a0eaaf97ddbb2c885d
Merge: 3793ec4 457e6d1
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Sep 15 10:11:31 2011 -0400
Merge branch 'master' into feature/performance
* master:
don't show the refresh button in the alert details view - they don't do
anything and when you click it, they get disabled and never enabled again.
[BZ 698600] do some null checks, because i am paranoid
[BZ 698600] fix UI so users can enter units and see units in alert condition UI
trivial - clean up imports, add TODO to mark a possible duplicate class
More wildcard updates propagated upwards from the agent api.
commit 3793ec453fd090b543e91c79a3e77d8485f33281
Merge: 48e5750 57e2de0
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 14 17:41:40 2011 -0400
Merge branch 'master' into feature/performance
commit 48e57501f897f39287fd5317452256bb474c4b62
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 14 17:37:39 2011 -0400
disable footer controls on metric schedules list view after Set
(collection interval) button is clicked
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
index 933aa01..60e52ee 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java
@@ -530,7 +530,7 @@ public class Table<DS extends RPCDataSource> extends
LocatableHLayout implements
refreshTableInfo();
}
- private void disableAllFooterControls() {
+ public void disableAllFooterControls() {
for (TableActionInfo tableAction : tableActions) {
tableAction.actionCanvas.disable();
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java
index 76378f0..493160a 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/UpdateCollectionIntervalWidget.java
@@ -122,9 +122,11 @@ public class UpdateCollectionIntervalWidget extends LocatableHLayout
implements
this.setButton.setDisabled(true);
this.setButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
- form.validate();
-
UpdateCollectionIntervalWidget.this.schedulesView.getDataSource().updateSchedules(
- UpdateCollectionIntervalWidget.this.schedulesView, getInterval());
+ if (form.validate()) {
+
UpdateCollectionIntervalWidget.this.schedulesView.disableAllFooterControls();
+
UpdateCollectionIntervalWidget.this.schedulesView.getDataSource().updateSchedules(
+ UpdateCollectionIntervalWidget.this.schedulesView,
getInterval());
+ }
}
});
this.setButton.setOverflow(Overflow.VISIBLE);
commit 67b35af6de08717bfed3c5e4c0d2a08d9dd7ae47
Merge: 43d0562 63a0592
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 14 11:03:28 2011 -0400
Merge branch 'master' into feature/performance
commit 43d0562c62abd1f45f926d4d51c4438489f84061
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Sep 14 11:01:02 2011 -0400
fix minor bug where as/as5 server discovery failed to parse the --properties
command-line option if the cwd was unknown, even if the arg to the option was
a relative path
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstanceInfo.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstanceInfo.java
index 991c68c..24083840 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstanceInfo.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstanceInfo.java
@@ -150,14 +150,15 @@ public class JBossInstanceInfo {
case 'P': // 'P' (--properties)
{
- // cwd can be null if native support is not able to determine CWD.
- if (null == currentWorkingDir) {
- log.error("Could not determine CWD. Failed to parse argument to
--properties option: "
+ String arg = options.getOptarg();
+
+ // cwd can be null if native support (i.e. SIGAR) is not able to
determine it.
+ if (!new File(arg).isAbsolute() && currentWorkingDir == null) {
+ log.error("Could not determine current working directory. Failed
to parse relative path argument to --properties option: "
+ options.getOptarg());
break;
}
- String arg = options.getOptarg();
URL url;
try {
File workingDir = new File(currentWorkingDir);
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JBossConfigurationUtility.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JBossConfigurationUtility.java
index 5554414..553d890 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JBossConfigurationUtility.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JBossConfigurationUtility.java
@@ -58,7 +58,7 @@ public class JBossConfigurationUtility
if (url.getProtocol().equals("file"))
{
File file = (new File(url.getFile())).getCanonicalFile();
- url = file.toURL();
+ url = file.toURI().toURL();
}
}
catch (Exception e)
diff --git
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstanceInfo.java
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstanceInfo.java
index 3ae813e..9dadd39 100644
---
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstanceInfo.java
+++
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstanceInfo.java
@@ -150,14 +150,15 @@ public class JBossInstanceInfo {
case 'P': // 'P' (--properties)
{
- // cwd can be null if native support is not able to determine CWD.
- if (null == currentWorkingDir) {
- log.error("Could not determine CWD. Failed to parse argument to
--properties option: "
+ String arg = options.getOptarg();
+
+ // cwd can be null if native support (i.e. SIGAR) is not able to
determine it.
+ if (!new File(arg).isAbsolute() && currentWorkingDir == null) {
+ log.error("Could not determine current working directory. Failed
to parse relative path argument to --properties option: "
+ options.getOptarg());
break;
}
- String arg = options.getOptarg();
URL url;
try {
File workingDir = new File(currentWorkingDir);
diff --git
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JBossConfigurationUtility.java
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JBossConfigurationUtility.java
index dff5b82..8b94c6e 100644
---
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JBossConfigurationUtility.java
+++
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JBossConfigurationUtility.java
@@ -53,7 +53,7 @@ public class JBossConfigurationUtility {
url = new URL(urlSpec);
if (url.getProtocol().equals("file")) {
File file = (new File(url.getFile())).getCanonicalFile();
- url = file.toURL();
+ url = file.toURI().toURL();
}
}
catch (Exception e) {
commit 8592dbb0c2765720a463b885b8b93ca6d5276c9f
Merge: 2bd932a 80561b8
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Sep 13 15:52:09 2011 -0400
Merge branch 'master' into feature/performance
commit 2bd932a8a276f1c7ed4e422c656f2500dee2d46f
Merge: 3558c8a 8bb8c6d
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Sep 13 14:51:51 2011 -0400
Merge branch 'master' into feature/performance
* master: (44 commits)
[BZ 738031] upgrade EMS from 1.2.15.1 to 1.2.16 to fix failure of as5 plugin to
initialize the EMS connection to an AS 6.0 instance
(
https://bugzilla.redhat.com/show_bug.cgi?id=738031) (cherry picked from commit
a49952619b9f61fc67631583a2e679e580f97b0c)
[BZ 738050] prior to invoking plugin API methods on discovery components, make sure
the context classloader is set correctly; specifically, it must be set to the parent
resource component's classloader, except for platform discovery, where it must be set
to the platform-plugin classloader) (
https://bugzilla.redhat.com/show_bug.cgi?id=738050)
(cherry picked from commit 3cd497771b43e14d9ceb945b72301816a0e40657)
BZ 737996 - Working around the property names inconsistency in the clustered web app
contexts.
BZ 737565 - do not allow user to pick multiple conditions using the same metric if
using ALL conjunction
BZ:733019: changed i)plugin display name to be more consistent with AS4 and AS5
ii)renamed HostController to better show relevance to AS7 inleft navigation
tree.
inserting missing profile. Make sure release number gets included in artifacts in
brew builds.
Fix test failure
Detect deleted drift configs during inventory sync
Adding support for syncing drift configs when agent starts with --cleanconfig
[BZ 735262] to support range alert definitions, we now have a "RANGE"
conditional. you can specify a range of values (low and high) and you can alert if a
metric value is either outside or inside that range. This will now allow you to avoid
having to have two conditions on the same metric with the ALL conjunection. You still
can't have that - two conditions using the same metric with ALL conjunction still
exhibits that typically-undesired effects as before. But now we support a range condition
that allows you to do a range check.
[BZ 736848] add new method to LinkManager that can return the appropriate form of
group URL given an EntityContext; update several spots in the code to start using this new
method to ensure the correct form of URL is used for the different types of compat groups
(
https://bugzilla.redhat.com/show_bug.cgi?id=736848) (cherry picked from commit
34cb25f075a22714af01ea08cd0de453b638a139)
refactor to make some of the helper methods more generic
add test that shows bug BZ-736685
make test better
[BZ 736685 - cannot uninventory resource that has condition log not associated with
an alert] Now deletes condition logs via the alert def, not alerts, because not every
condition log may not yet be associated with an alert. Also, avoids joining with the
potentially large alert table.
Som boilerplate for group level drift tab
create the server entity with a custom name so it doesn't clash with a possibly
already existing default one
start alert unit tests. this commit causes one test failure. need to fix 736685 to
get the test to pass.
Update the resource container when a drift config is deleted
Reflect in the GUI when a changeset contains planned changes. It is in the display
name of the changeset tree node and also in the changeset section of the drift details.
...
commit 3558c8a5f3d7dea4e633f534e6a41ecf9287f24f
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Sep 13 14:28:16 2011 -0400
add traits and operations to the server-a/service-a resource types used by
configurable-1 scenario, and add metric and trait generators to that scenario; make
SimpleNumericMeasurementFactory and SimpleTraitFactory return more realistic metric and
trait values
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
index 1bf4b8a..c93c7a4 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
@@ -71,7 +71,7 @@ public class PerfTestComponent implements ResourceComponent,
MeasurementFacet, C
// Attributes --------------------------------------------
private Log log = LogFactory.getLog(PerfTestComponent.class);
- public static final Random RANDOM = new Random();
+ private static final Random RANDOM = new Random();
private ResourceContext resourceContext;
private EventPoller eventPoller;
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/measurement/SimpleNumericMeasurementFactory.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/measurement/SimpleNumericMeasurementFactory.java
index e5ce82d..42b6d8f 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/measurement/SimpleNumericMeasurementFactory.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/measurement/SimpleNumericMeasurementFactory.java
@@ -22,18 +22,22 @@ import org.rhq.core.domain.measurement.MeasurementData;
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import java.util.Random;
+
/**
- * The simplest algorithm for generating measurement values
+ * Create mock numeric data.
*
- * @author Jason Dobies
+ * @author Ian Springer
*/
public class SimpleNumericMeasurementFactory implements MeasurementFactory {
- // MeasurementFactory Implementation --------------------------------------------
+
+ private static final Random RANDOM = new Random();
public MeasurementData nextValue(MeasurementScheduleRequest request) {
- double value = request.getScheduleId();
+ // generate a random value between 95,000 and 105,000
+ double value = 100000 + (RANDOM.nextInt(10000) - 5000);
- MeasurementDataNumeric data = new MeasurementDataNumeric(request, value);
- return data;
+ return new MeasurementDataNumeric(request, value);
}
+
}
\ No newline at end of file
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/trait/SimpleTraitFactory.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/trait/SimpleTraitFactory.java
index 566ecde..f420a23 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/trait/SimpleTraitFactory.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/trait/SimpleTraitFactory.java
@@ -18,28 +18,24 @@
*/
package org.rhq.plugins.perftest.trait;
-import org.rhq.core.domain.measurement.MeasurementData;
import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.plugins.perftest.trait.TraitFactory;
-import java.util.Date;
+import java.util.Random;
/**
- * Create trait data
+ * Create mock trait data.
*
- * @author Heiko W. Rupp
+ * @author Ian Springer
*/
public class SimpleTraitFactory implements TraitFactory {
- public MeasurementDataTrait nextValue(MeasurementScheduleRequest request) {
-
- String name = request.getName();
- Date date = new Date();
+ private static final Random RANDOM = new Random();
- MeasurementDataTrait data = new MeasurementDataTrait(request,name + ",
" + date);
-
- return data;
+ public MeasurementDataTrait nextValue(MeasurementScheduleRequest request) {
+ // generate "red" roughly 10% of the time, and "green" the
rest of the time
+ String value = (RANDOM.nextInt(10) % 9) == 0 ? "red" :
"green";
+ return new MeasurementDataTrait(request, value);
}
}
diff --git a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
index 05c3e98..568998e 100644
--- a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
@@ -146,6 +146,12 @@
<metric property="metric8" defaultOn="true"
displayType="summary"/>
<metric property="metric9" defaultOn="true"
displayType="summary"/>
+ <metric property="trait000" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="trait001" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="trait002" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="trait003" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="trait004" defaultOn="true"
dataType="trait" displayType="summary"/>
+
<event name="PerfTestEventType" description="a test event
type"/>
<content name="artifact0" displayName="Artifact 0"
category="configuration"/>
@@ -163,6 +169,8 @@
<c:simple-property name="childProperty2"
default="blue"/>
</plugin-configuration>
+ <operation name="childOperation0"/>
+
<metric property="childMetric0" defaultOn="true"
displayType="summary"/>
<metric property="childMetric1" defaultOn="true"
displayType="summary"/>
<metric property="childMetric2" defaultOn="true"
displayType="summary"/>
@@ -174,6 +182,12 @@
<metric property="childMetric8" defaultOn="true"
displayType="summary"/>
<metric property="childMetric9" defaultOn="true"
displayType="summary"/>
+ <metric property="childTrait000" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="childTrait001" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="childTrait002" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="childTrait003" defaultOn="true"
dataType="trait" displayType="summary"/>
+ <metric property="childTrait004" defaultOn="true"
dataType="trait" displayType="summary"/>
+
<content name="childArtifact0" displayName="Child Artifact
0" category="configuration"/>
<resource-configuration>
diff --git a/modules/plugins/perftest/src/main/resources/configurable-1.xml
b/modules/plugins/perftest/src/main/resources/configurable-1.xml
index 55f88b7..d6f6ccf 100644
--- a/modules/plugins/perftest/src/main/resources/configurable-1.xml
+++ b/modules/plugins/perftest/src/main/resources/configurable-1.xml
@@ -13,10 +13,14 @@
<resource type="server-a">
<simpleResourceGenerator property="rhq.perftest.server-a-count"/>
+ <simpleNumericMeasurementGenerator/>
+ <simpleTraitMeasurementGenerator/>
</resource>
<resource type="service-a">
<simpleResourceGenerator property="rhq.perftest.service-a-count"/>
+ <simpleNumericMeasurementGenerator/>
+ <simpleTraitMeasurementGenerator/>
</resource>
</scenario>
commit 3cd497771b43e14d9ceb945b72301816a0e40657
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Sep 13 14:22:06 2011 -0400
[BZ 738050] prior to invoking plugin API methods on discovery components, make sure
the context classloader is set correctly; specifically, it must be set to the parent
resource component's classloader, except for platform discovery, where it must be set
to the platform-plugin classloader) (
https://bugzilla.redhat.com/show_bug.cgi?id=738050)
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index dc58717..da56a9a 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -78,7 +78,6 @@ import org.rhq.core.domain.resource.ResourceUpgradeReport;
import org.rhq.core.pc.ContainerService;
import org.rhq.core.pc.PluginContainer;
import org.rhq.core.pc.PluginContainerConfiguration;
-import org.rhq.core.pc.RebootRequestListener;
import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.agent.AgentRegistrar;
import org.rhq.core.pc.agent.AgentService;
@@ -87,8 +86,6 @@ import org.rhq.core.pc.content.ContentContextImpl;
import org.rhq.core.pc.event.EventContextImpl;
import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState;
import org.rhq.core.pc.operation.OperationContextImpl;
-import org.rhq.core.pc.operation.OperationManager;
-import org.rhq.core.pc.operation.OperationServicesAdapter;
import org.rhq.core.pc.plugin.BlacklistedException;
import org.rhq.core.pc.plugin.CanonicalResourceKey;
import org.rhq.core.pc.plugin.PluginComponentFactory;
@@ -100,7 +97,6 @@ import org.rhq.core.pc.util.FacetLockType;
import org.rhq.core.pc.util.LoggingThreadFactory;
import org.rhq.core.pluginapi.availability.AvailabilityFacet;
import org.rhq.core.pluginapi.content.ContentContext;
-import org.rhq.core.pluginapi.content.ContentServices;
import org.rhq.core.pluginapi.event.EventContext;
import org.rhq.core.pluginapi.inventory.ClassLoaderFacet;
import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
@@ -112,7 +108,6 @@ import org.rhq.core.pluginapi.inventory.ResourceContext;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
import org.rhq.core.pluginapi.operation.OperationContext;
-import org.rhq.core.pluginapi.operation.OperationServices;
import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext;
import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
import org.rhq.core.system.SystemInfo;
@@ -312,7 +307,7 @@ public class InventoryManager extends AgentService implements
ContainerService,
try {
ResourceDiscoveryComponent proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
- .getResourceType(), component, timeout);
+ .getResourceType(), component, timeout, parentResourceContainer);
Set<DiscoveredResourceDetails> results =
proxy.discoverResources(context);
return results;
} catch (TimeoutException te) {
@@ -332,20 +327,23 @@ public class InventoryManager extends AgentService implements
ContainerService,
* an empty set if nothing is discovered. This may return
<code>null</code> if for some reason
* we could not invoke the discovery component.
*
+ *
* @param component the discovery component that will actually go out and discover
resources
* @param pluginConfig the plugin configuration to be used to connect to the resource
to be discovered
* @param context the context for use by the discovery component
+ * @param parentResourceContainer
* @return the details of all discovered resources, may be empty or
<code>null</code>
*
* @throws Exception if the discovery component threw an exception
*/
private DiscoveredResourceDetails discoverResource(ResourceDiscoveryComponent
component,
- Configuration pluginConfig, ResourceDiscoveryContext context) throws Exception {
+ Configuration pluginConfig,
ResourceDiscoveryContext context,
+ ResourceContainer
parentResourceContainer) throws Exception {
long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try {
ManualAddFacet proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context
- .getResourceType(), component, timeout, ManualAddFacet.class);
+ .getResourceType(), component, timeout, ManualAddFacet.class,
parentResourceContainer);
DiscoveredResourceDetails result = proxy.discoverResource(pluginConfig,
context);
return result;
} catch (TimeoutException te) {
@@ -381,7 +379,7 @@ public class InventoryManager extends AgentService implements
ContainerService,
long timeout = getDiscoveryComponentTimeout(resourceType);
ClassLoaderFacet proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(resourceType,
- component, timeout, ClassLoaderFacet.class);
+ component, timeout, ClassLoaderFacet.class, parentContainer);
ResourceDiscoveryContext discoveryContext = new
ResourceDiscoveryContext(resourceType, parentComponent,
parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null,
this.configuration
@@ -401,14 +399,14 @@ public class InventoryManager extends AgentService implements
ContainerService,
}
public <T extends ResourceComponent> ResourceUpgradeReport
invokeDiscoveryComponentResourceUpgradeFacet(
- ResourceType resourceType, ResourceDiscoveryComponent<T> component,
- ResourceUpgradeContext<T> inventoriedResource) throws Throwable {
+ ResourceType resourceType, ResourceDiscoveryComponent<T> component,
+ ResourceUpgradeContext<T> inventoriedResource, ResourceContainer
parentResourceContainer) throws Throwable {
long timeout = getDiscoveryComponentTimeout(resourceType);
try {
@SuppressWarnings("unchecked")
ResourceUpgradeFacet<T> proxy =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(
- resourceType, component, timeout, ResourceUpgradeFacet.class);
+ resourceType, component, timeout, ResourceUpgradeFacet.class,
parentResourceContainer);
return proxy.upgrade(inventoriedResource);
} catch (BlacklistedException e) {
@@ -678,7 +676,8 @@ public class InventoryManager extends AgentService implements
ContainerService,
// Ask the plugin's discovery component to find the new resource,
throwing exceptions if it cannot be
// found at all.
- discoveredResourceDetails = discoverResource(discoveryComponent,
pluginConfiguration, discoveryContext);
+ discoveredResourceDetails = discoverResource(discoveryComponent,
pluginConfiguration, discoveryContext,
+ parentResourceContainer);
if (discoveredResourceDetails == null) {
log.info("Plugin Error: During manual add, discovery component
method ["
+ discoveryComponent.getClass().getName() +
".discoverResource()] returned null "
@@ -1508,7 +1507,7 @@ public class InventoryManager extends AgentService implements
ContainerService,
// wrap the discovery component in a proxy to allow us to timeout discovery
invocations
try {
discoveryComponent =
this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(type,
- discoveryComponent, getDiscoveryComponentTimeout(type));
+ discoveryComponent, getDiscoveryComponentTimeout(type),
parentResourceContainer);
} catch (Exception e) {
discoveryComponent = null;
log.warn("Cannot give activated resource its discovery component.
Cause: " + e);
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java
index 10aae22..c0a0fae 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java
@@ -89,6 +89,20 @@ public class PluginComponentFactory implements ContainerService {
log.debug("Creating discovery component [" + className + "]
for resource type [" + typeName + ']');
}
+ ClassLoader classLoader =
getDiscoveryComponentClassLoader(parentResourceContainer, pluginName);
+
+ ResourceDiscoveryComponent discoveryComponent = (ResourceDiscoveryComponent)
instantiateClass(classLoader,
+ className);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Created discovery component [" + className + "] for
resource type [" + typeName + ']');
+ }
+
+ return discoveryComponent;
+ }
+
+ public ClassLoader getDiscoveryComponentClassLoader(ResourceContainer
parentResourceContainer, String pluginName)
+ throws PluginContainerException {
// Determine what classloader to use to load the discovery component class. If
the parent resource for newly
// discovered resources is the root platform (or if the discovered resource is
going TO BE the root platform),
// we can just use the plugin classloader. If discovered resources will be
children of a top level server or
@@ -109,15 +123,7 @@ public class PluginComponentFactory implements ContainerService {
classLoader = classLoaderMgr.obtainDiscoveryClassLoader(pluginName,
parentClassLoader);
}
}
-
- ResourceDiscoveryComponent discoveryComponent = (ResourceDiscoveryComponent)
instantiateClass(classLoader,
- className);
-
- if (log.isDebugEnabled()) {
- log.debug("Created discovery component [" + className + "] for
resource type [" + typeName + ']');
- }
-
- return discoveryComponent;
+ return classLoader;
}
/**
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java
index c659b8e..6dff613 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java
@@ -274,7 +274,7 @@ public class ResourceUpgradeDelegate {
ResourceUpgradeReport upgradeReport = null;
try {
upgradeReport =
inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resource.getResourceType(),
- discoveryComponent, upgradeContext);
+ discoveryComponent, upgradeContext, parentResourceContainer);
} catch (Throwable t) {
log.error("ResourceUpgradeFacet threw an exception while upgrading
resource [" + resource + "]", t);
request.setErrorProperties(t);
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java
index bcbd31d..b72f019 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java
@@ -41,8 +41,11 @@ import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.agent.PluginContainerException;
import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.inventory.TimeoutException;
import org.rhq.core.pc.plugin.BlacklistedException;
+import org.rhq.core.pc.plugin.PluginComponentFactory;
import org.rhq.core.pluginapi.inventory.ClassLoaderFacet;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
@@ -65,20 +68,24 @@ public class DiscoveryComponentProxyFactory {
private final Set<ResourceType> blacklist = new HashSet<ResourceType>();
/**
- * Same as {@link #getDiscoveryComponentProxy(ResourceType,
ResourceDiscoveryComponent, long)} except
+ * Same as {@link
#getDiscoveryComponentProxy(org.rhq.core.domain.resource.ResourceType,
org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent, long,
org.rhq.core.pc.inventory.ResourceContainer)} except
* this lets you provide the interface of the discovery component you want to talk
to. For example,
* use this to talk to the {@link ClassLoaderFacet} of a discovery component.
*/
@SuppressWarnings("unchecked")
public <T> T getDiscoveryComponentProxy(ResourceType type,
ResourceDiscoveryComponent component, long timeout,
- Class<T> componentInterface) throws PluginContainerException,
BlacklistedException {
+ Class<T> componentInterface,
ResourceContainer parentResourceContainer)
+ throws PluginContainerException, BlacklistedException {
if (isResourceTypeBlacklisted(type)) {
throw new BlacklistedException("Discovery component for resource type
[" + type + "] has been blacklisted");
}
try {
- ClassLoader pluginClassLoader = component.getClass().getClassLoader();
+ PluginComponentFactory pluginComponentFactory =
PluginContainer.getInstance().getPluginComponentFactory();
+
+ ClassLoader pluginClassLoader =
+
pluginComponentFactory.getDiscoveryComponentClassLoader(parentResourceContainer,
type.getPlugin());
// This is the handler that will actually invoke the method calls.
ResourceDiscoveryComponentInvocationHandler handler = new
ResourceDiscoveryComponentInvocationHandler(type,
@@ -99,10 +106,12 @@ public class DiscoveryComponentProxyFactory {
* to make calls into the plugin discovery component and not deadlock if that plugin
misbehaves and never returns
* (or takes too long to return).
*
+ *
* @param type the resource type that is to be discovered by the given discovery
component
* @param component the discovery component to be wrapped in a timer proxy
* @param timeout the time, in milliseconds, that invocations can take to invoke
discovery component methods
- *
+ *
+ * @param parentResourceContainer
* @return the discovery component wrapped in a proxy that should be used to make
calls to the component
*
* @throws PluginContainerException if this method failed to create the proxy
@@ -111,9 +120,11 @@ public class DiscoveryComponentProxyFactory {
*/
@SuppressWarnings("unchecked")
public ResourceDiscoveryComponent getDiscoveryComponentProxy(ResourceType type,
- ResourceDiscoveryComponent component, long timeout) throws
PluginContainerException, BlacklistedException {
-
- return getDiscoveryComponentProxy(type, component, timeout,
ResourceDiscoveryComponent.class);
+
ResourceDiscoveryComponent component, long timeout,
+ ResourceContainer
parentResourceContainer)
+ throws PluginContainerException, BlacklistedException {
+ return getDiscoveryComponentProxy(type, component, timeout,
ResourceDiscoveryComponent.class,
+ parentResourceContainer);
}
public void initialize() {
commit a49952619b9f61fc67631583a2e679e580f97b0c
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Sep 13 13:44:15 2011 -0400
[BZ 738031] upgrade EMS from 1.2.15.1 to 1.2.16 to fix failure of as5 plugin to
initialize the EMS connection to an AS 6.0 instance
(
https://bugzilla.redhat.com/show_bug.cgi?id=738031)
diff --git a/pom.xml b/pom.xml
index ab342f5..d917682 100644
--- a/pom.xml
+++ b/pom.xml
@@ -85,7 +85,7 @@
<jsf-api.version>1.2_14</jsf-api.version>
<jsf-impl.version>1.2_14</jsf-impl.version>
<ojdbc5.version>11.2.0.2.0</ojdbc5.version>
- <ems.version>1.2.15.1</ems.version>
+ <ems.version>1.2.16</ems.version>
<postgresql.version>9.0-801.jdbc4</postgresql.version>
<h2.version>1.2.139</h2.version>
<jtds.version>1.2.2</jtds.version>
commit 34cb25f075a22714af01ea08cd0de453b638a139
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Sep 8 17:07:44 2011 -0400
[BZ 736848] add new method to LinkManager that can return the appropriate form of
group URL given an EntityContext; update several spots in the code to start using this new
method to ensure the correct form of URL is used for the different types of compat groups
(
https://bugzilla.redhat.com/show_bug.cgi?id=736848)
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
index 63535a8..fa9fa06 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2010 Red Hat, Inc.
+ * Copyright (C) 2005-2011 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -101,8 +101,39 @@ public class LinkManager {
return link;
}
- public static String getResourcePluginConfigurationUpdateHistoryLink(int groupId) {
- return getResourceLink(groupId) +
"/Inventory/ConnectionSettingsHistory";
+ public static String getEntityTabLink(EntityContext entityContext, String tabName,
String subTabName) {
+ String link;
+ switch (entityContext.getType()) {
+ case Resource:
+ link = getResourceTabLink(entityContext.getResourceId(), tabName,
subTabName);
+ break;
+ case ResourceGroup:
+ if (entityContext.isAutoGroup()) {
+ link = getAutoGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ } else if (entityContext.isAutoCluster()) {
+ link = getAutoClusterTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ } else {
+ link = getResourceGroupTabLink(entityContext.getGroupId(), tabName,
subTabName);
+ }
+ break;
+ case SubsystemView:
+ if (tabName.equals("Alerts") &&
subTabName.equals("Definitions")) {
+ link = "#Reports/Subsystems/AlertDefinitions";
+ } else if (tabName.equals("Alerts") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/RecentAlerts";
+ } else if (tabName.equals("Operations") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/RecentOperations";
+ } else if (tabName.equals("Configuration") &&
subTabName.equals("History")) {
+ link = "#Reports/Subsystems/ConfigurationHistoryView";
+ } else {
+ throw new IllegalArgumentException("Subsystem link not supported
for tab " + tabName + ">"
+ + subTabName + ".");
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported entity context type:
" + entityContext.getType());
+ }
+ return link;
}
public static String getGroupPluginConfigurationUpdateHistoryLink(int groupId,
Integer groupUpdateHistoryId) {
@@ -200,18 +231,7 @@ public class LinkManager {
public static String getAlertDetailLink(EntityContext entityContext, int alertId) {
String link;
if (GWT) {
- String baseLink = getResourceLink(entityContext.getResourceId());
- switch (entityContext.getType()) {
- case Resource:
- baseLink = getResourceTabLink(entityContext.getResourceId(),
"Alerts", "History");
- break;
- case ResourceGroup:
- baseLink = getResourceGroupTabLink(entityContext.getGroupId(),
"Alerts", "History");
- break;
- case SubsystemView:
- baseLink = "#Reports/Subsystems/RecentAlerts";
- break;
- }
+ String baseLink = getEntityTabLink(entityContext, "Alerts",
"History");
link = baseLink + "/" + alertId;
} else {
link = null; // TODO
@@ -273,7 +293,7 @@ public class LinkManager {
public static String getHubServerssLink() {
if (GWT) {
- return "#Inventory/Serers";
+ return "#Inventory/Servers";
} else {
return "/rhq/inventory/browseResources.xhtml?subtab=server";
}
@@ -321,7 +341,7 @@ public class LinkManager {
public static String getAdminUsersLink() {
if (GWT) {
- return "#Administration/Security/Manage Users";
+ return "#Administration/Security/Users";
} else {
return "/admin/user/UserAdmin.do?mode=list";
}
@@ -329,7 +349,7 @@ public class LinkManager {
public static String getAdminRolesLink() {
if (GWT) {
- return "#Administration/Security/Manage Roles";
+ return "#Administration/Security/Roles";
} else {
return "/admin/role/RoleAdmin.do?mode=list";
}
@@ -474,4 +494,5 @@ public class LinkManager {
public static String getDriftConfigurationLink(int resourceId, int driftConfigId) {
return "#Resource/" + resourceId + "/Drift/Configuration/" +
driftConfigId;
}
+
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java
index 6f552c8..3d973d5 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java
@@ -184,16 +184,7 @@ public class ResourceGroupContextMenu extends LocatableMenu {
if (pluginConfigEnabled) {
pluginConfiguration.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
- if (isAutoGroup) {
- CoreGUI.goToView(LinkManager.getAutoGroupTabLink(group.getId(),
"Inventory",
- "ConnectionSettings"));
- } else if (isAutoCluster) {
- CoreGUI.goToView(LinkManager.getAutoClusterTabLink(group.getId(),
"Inventory",
- "ConnectionSettings"));
- } else {
-
CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group.getId(),
"Inventory",
- "ConnectionSettings"));
- }
+ CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group,
"Inventory", "ConnectionSettings"));
}
});
}
@@ -207,14 +198,7 @@ public class ResourceGroupContextMenu extends LocatableMenu {
if (resourceConfigEnabled) {
resourceConfiguration.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
- if (isAutoGroup) {
- CoreGUI.goToView(LinkManager.getAutoGroupTabLink(group.getId(),
"Configuration", "Current"));
- } else if (isAutoCluster) {
- CoreGUI.goToView(LinkManager.getAutoClusterTabLink(group.getId(),
"Configuration", "Current"));
- } else {
- CoreGUI
- .goToView(LinkManager.getResourceGroupTabLink(group.getId(),
"Configuration", "Current"));
- }
+ CoreGUI.goToView(LinkManager.getResourceGroupTabLink(group,
"Configuration", "Current"));
}
});
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java
index efddea7..0be3378 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java
@@ -211,7 +211,7 @@ public class GroupResourceConfigurationEditView extends
LocatableVLayout impleme
}
public void onSuccess(Void result) {
- String configHistoryUrl =
LinkManager.getResourceGroupTabLink(group.getId(),
+ String configHistoryUrl = LinkManager.getResourceGroupTabLink(group,
ResourceDetailView.Tab.CONFIGURATION,
ResourceDetailView.ConfigurationSubTab.HISTORY);
String configHistoryView = configHistoryUrl.substring(1); // chop off
the leading '#'
Message message = new
Message(MSG.view_group_resConfig_edit_saveInitiated_concise(), MSG
commit ab72fd88c401ad070ca716a0996cf36a9edd1720
Merge: 91849bd be4d0cd
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Sep 8 11:10:48 2011 -0400
Merge branch 'master' into feature/performance
commit 91849bd6dd4e0f4a51e535da4f21f19b0b2e2937
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Sep 8 10:35:21 2011 -0400
make various improvements to the server-a resourceType used by the configurable-1
scenario, including setting up resource subCategories; add generic support to
PerfTestComponent for simulating operation execution; make minor Javadoc improvement in
PerfTestEventPoller
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
index fdfb98e..1bf4b8a 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
@@ -57,6 +57,7 @@ import org.rhq.plugins.perftest.trait.TraitFactory;
import java.io.InputStream;
import java.util.List;
+import java.util.Random;
import java.util.Set;
import java.util.Arrays;
@@ -70,10 +71,13 @@ public class PerfTestComponent implements ResourceComponent,
MeasurementFacet, C
// Attributes --------------------------------------------
private Log log = LogFactory.getLog(PerfTestComponent.class);
+ public static final Random RANDOM = new Random();
+
private ResourceContext resourceContext;
private EventPoller eventPoller;
private Configuration resourceConfiguration;
+
// ResourceComponent Implementation --------------------------------------------
public void start(ResourceContext context) throws
InvalidPluginConfigurationException, Exception {
@@ -186,9 +190,17 @@ public class PerfTestComponent implements ResourceComponent,
MeasurementFacet, C
if (name.equals("createEvents")) {
return createEvents(parameters);
+ } else {
+ // Sleep for a bit to simulate actually doing something.
+ Thread.sleep(500);
+ // Make roughly 1 out of 10 invocations fail.
+ if ((RANDOM.nextInt(10) % 9) == 0) {
+ throw new Exception("Operation failed!");
+ } else {
+ // Assume the operation returns an empty result config.
+ return new OperationResult();
+ }
}
-
- return null;
}
private OperationResult createEvents(Configuration params) {
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/event/PerfTestEventPoller.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/event/PerfTestEventPoller.java
index 10af135..8ad107d 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/event/PerfTestEventPoller.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/event/PerfTestEventPoller.java
@@ -11,9 +11,9 @@ import org.rhq.core.pluginapi.inventory.ResourceContext;
/**
* Emits events when polled. Set the following system properties to define behavior:
*
+ * rhq.perftest.events.polling-interval (in seconds; if this is not set, this poller
object will never be created)
* rhq.perftest.events.count (default is "1")
* rhq.perftest.events.severity (default is "INFO")
- * rhq.perftest.events.polling-interval (in seconds; if this is not set, this poller
object will never be created)
*/
public class PerfTestEventPoller implements EventPoller {
diff --git a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
index 6642315..05c3e98 100644
--- a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
@@ -119,6 +119,12 @@
<!-- try to make server-a and its children representative of "average"
resources -->
<server name="server-a" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Test Server
A">
+ <subcategories>
+ <subcategory name="subcategory0">
+ <subcategory name="childSubcategory0"/>
+ </subcategory>
+ </subcategories>
+
<plugin-configuration>
<c:simple-property name="property0"/>
<c:simple-property name="property1"/>
@@ -127,16 +133,18 @@
<c:simple-property name="property4"/>
</plugin-configuration>
- <metric displayName="Metric 0" property="metric0"
defaultOn="false"/>
- <metric displayName="Metric 1" property="metric1"
defaultOn="false"/>
- <metric displayName="Metric 2" property="metric2"
defaultOn="false"/>
- <metric displayName="Metric 3" property="metric3"
defaultOn="false"/>
- <metric displayName="Metric 4" property="metric4"
defaultOn="true" displayType="detail"/>
- <metric displayName="Metric 5" property="metric5"
defaultOn="true" displayType="detail"/>
- <metric displayName="Metric 6" property="metric6"
defaultOn="true" displayType="detail"/>
- <metric displayName="Metric 7" property="metric7"
defaultOn="true" displayType="summary"/>
- <metric displayName="Metric 8" property="metric8"
defaultOn="true" displayType="summary"/>
- <metric displayName="Metric 9" property="metric9"
defaultOn="true" displayType="summary"/>
+ <operation name="operation0"/>
+
+ <metric property="metric0" defaultOn="true"
displayType="summary"/>
+ <metric property="metric1" defaultOn="true"
displayType="summary"/>
+ <metric property="metric2" defaultOn="true"
displayType="summary"/>
+ <metric property="metric3" defaultOn="true"
displayType="summary"/>
+ <metric property="metric4" defaultOn="true"
displayType="summary"/>
+ <metric property="metric5" defaultOn="true"
displayType="summary"/>
+ <metric property="metric6" defaultOn="true"
displayType="summary"/>
+ <metric property="metric7" defaultOn="true"
displayType="summary"/>
+ <metric property="metric8" defaultOn="true"
displayType="summary"/>
+ <metric property="metric9" defaultOn="true"
displayType="summary"/>
<event name="PerfTestEventType" description="a test event
type"/>
@@ -146,17 +154,25 @@
<content name="artifact3" displayName="Artifact 3"
category="configuration"/>
<content name="artifact4" displayName="Artifact 4"
category="configuration"/>
- <service name="service-a" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Nested Service
A">
+ <service name="service-a" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent"
+ description="Nested Service A"
subCategory="childSubcategory0">
<plugin-configuration>
- <c:simple-property name="childProperty0"/>
- <c:simple-property name="childProperty1"/>
- <c:simple-property name="childProperty2"/>
+ <c:simple-property name="childProperty0"
default="red"/>
+ <c:simple-property name="childProperty1"
default="green"/>
+ <c:simple-property name="childProperty2"
default="blue"/>
</plugin-configuration>
- <metric property="childMetric0" defaultOn="false"/>
- <metric property="childMetric1" defaultOn="true"
displayType="detail"/>
+ <metric property="childMetric0" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric1" defaultOn="true"
displayType="summary"/>
<metric property="childMetric2" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric3" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric4" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric5" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric6" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric7" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric8" defaultOn="true"
displayType="summary"/>
+ <metric property="childMetric9" defaultOn="true"
displayType="summary"/>
<content name="childArtifact0" displayName="Child Artifact
0" category="configuration"/>
@@ -164,85 +180,80 @@
<!-- This group contains a sampling of all of the various types of
properties. -->
<c:group name="group1" displayName="Group 1">
- <c:simple-property name="string"
type="string"/>
- <c:simple-property name="longString"
type="longString"/>
- <c:simple-property name="password"
type="password"/>
- <c:simple-property name="boolean"
type="boolean"/>
- <c:simple-property name="integer"
type="integer"/>
- <c:simple-property name="long" type="long"/>
- <c:simple-property name="float"
type="float"/>
- <c:simple-property name="double"
type="double"/>
- <c:simple-property name="file" type="file"/>
- <c:simple-property name="directory"
type="directory"/>
-
- <c:simple-property name="enum"
default="Blue">
+ <c:simple-property name="string" type="string"
default="blah"/>
+ <c:simple-property name="longString"
type="longString" default="blah blah blah"/>
+ <c:simple-property name="password"
type="password" default="secret"/>
+ <c:simple-property name="boolean" type="boolean"
default="true"/>
+ <c:simple-property name="integer" type="integer"
default="42"/>
+ <c:simple-property name="long" type="long"
default="1000000000000"/>
+ <c:simple-property name="float" type="float"
default="3.14"/>
+ <c:simple-property name="double" type="double"
default="0.123456789"/>
+ <c:simple-property name="file" type="file"
default="/etc/passwd"/>
+ <c:simple-property name="directory"
type="directory" default="/tmp"/>
+
+ <c:simple-property name="enum"
default="blue">
<c:property-options>
<c:option value="red" name="Red"/>
- <c:option value="blue" name="Blue"/>
<c:option value="green"
name="Green"/>
+ <c:option value="blue" name="Blue"/>
</c:property-options>
</c:simple-property>
- <c:simple-property name="optional"
required="false"/>
- <c:simple-property name="readOnly"
readOnly="true"/>
+ <c:simple-property name="optional"
required="false" default="boo"/>
+ <c:simple-property name="readOnly"
readOnly="true" default="fixed"/>
<c:map-property name="openMap"/>
<c:map-property name="map">
- <c:simple-property name="mapMember1"/>
- <c:simple-property name="mapMember2"/>
- <c:simple-property name="mapMember3"/>
+ <c:simple-property name="mapMember1"
default="value1"/>
+ <c:simple-property name="mapMember2"
default="value2"/>
+ <c:simple-property name="mapMember3"
default="value3"/>
</c:map-property>
<c:list-property name="listOfMaps">
<c:map-property name="listMember">
- <c:simple-property name="mapInListMember1"/>
- <c:simple-property name="mapInListMember2"/>
- <c:simple-property name="mapInListMember3"/>
+ <c:simple-property name="mapInListMember1"
default="value1"/>
+ <c:simple-property name="mapInListMember2"
default="value2"/>
+ <c:simple-property name="mapInListMember3"
default="value3"/>
</c:map-property>
</c:list-property>
</c:group>
<!-- This group just contains a whole bunch of props to give this config
some bulk. -->
<c:group name="group2" displayName="Group 2">
- <c:simple-property name="string1"/>
- <c:simple-property name="string2"/>
- <c:simple-property name="string3"/>
- <c:simple-property name="string4"/>
- <c:simple-property name="string5"/>
- <c:simple-property name="string6"/>
- <c:simple-property name="string7"/>
- <c:simple-property name="string8"/>
- <c:simple-property name="string9"/>
- <c:simple-property name="string10"/>
- <c:simple-property name="string11"/>
- <c:simple-property name="string12"/>
- <c:simple-property name="string13"/>
- <c:simple-property name="string14"/>
- <c:simple-property name="string15"/>
- <c:simple-property name="string16"/>
- <c:simple-property name="string17"/>
- <c:simple-property name="string18"/>
- <c:simple-property name="string19"/>
- <c:simple-property name="string20"/>
+ <c:simple-property name="string1"
default="foo"/>
+ <c:simple-property name="string2"
default="foo"/>
+ <c:simple-property name="string3"
default="foo"/>
+ <c:simple-property name="string4"
default="foo"/>
+ <c:simple-property name="string5"
default="foo"/>
+ <c:simple-property name="string6"
default="foo"/>
+ <c:simple-property name="string7"
default="foo"/>
+ <c:simple-property name="string8"
default="foo"/>
+ <c:simple-property name="string9"
default="foo"/>
+ <c:simple-property name="string10"
default="foo"/>
+ <c:simple-property name="string11"
default="foo"/>
+ <c:simple-property name="string12"
default="foo"/>
+ <c:simple-property name="string13"
default="foo"/>
+ <c:simple-property name="string14"
default="foo"/>
+ <c:simple-property name="string15"
default="foo"/>
+ <c:simple-property name="string16"
default="foo"/>
+ <c:simple-property name="string17"
default="foo"/>
+ <c:simple-property name="string18"
default="foo"/>
+ <c:simple-property name="string19"
default="foo"/>
+ <c:simple-property name="string20"
default="foo"/>
</c:group>
- <!-- Throw in a couple templates too. -->
+ <!-- Throw in a template for good measure. -->
<c:template name="template1" description="Template
1">
<c:simple-property name="string"
default="template1Value"/>
</c:template>
- <c:template name="template2" description="Template
2">
- <c:simple-property name="string"
default="template2Value"/>
- </c:template>
-
</resource-configuration>
<service name="service-ab" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Nested Service
A-B">
<plugin-configuration>
<c:simple-property name="grandchildProperty0"/>
</plugin-configuration>
- <metric property="grandchildMetric0" defaultOn="true"
displayType="detail"/>
</service>
</service>
commit cd4e29698030b5766a02602b527f52a7cc468a07
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Sep 8 10:32:23 2011 -0400
document what the default collection interval will default to if the defaultInterval
attribute is not specified for a metric in an Agent plugin descriptor
diff --git a/modules/core/client-api/src/main/resources/rhq-plugin.xsd
b/modules/core/client-api/src/main/resources/rhq-plugin.xsd
index e02013a..1d95be7 100644
--- a/modules/core/client-api/src/main/resources/rhq-plugin.xsd
+++ b/modules/core/client-api/src/main/resources/rhq-plugin.xsd
@@ -202,8 +202,16 @@
<xs:annotation>
<xs:documentation>
The default collection interval, in milliseconds. The metric is not
necessarily
- enabled - see the defaultOn attribute for that. The minimum allowed
value is
- 30000 (30 seconds).
+ enabled by default - see the defaultOn attribute for that. The minimum
allowed
+ value is 30000 (30 seconds). If unspecified, the default collection
interval is
+ set according to the Resource category, metric data type, and metric
display
+ type, as follows:
+
+ platform numeric metrics: summary - 1m, detail - 2m
+ server numeric metrics: summary - 5m, detail - 10m
+ service numeric metrics: summary - 10m, detail - 20m
+ traits: summary - 10m, detail - 30m
+ call-time metrics: 1m
</xs:documentation>
</xs:annotation>
<xs:simpleType>
commit ca3b7bfa051e1f1038f157fb28fac257cdca8245
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Sep 8 10:30:20 2011 -0400
include exception in logged error when adding a ResourceError fails
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java
index 4e739aa..04e15d4 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java
@@ -166,7 +166,7 @@ public class DiscoveryServerServiceImpl implements
DiscoveryServerService {
ResourceManagerLocal resourceManager = LookupUtil.getResourceManager();
resourceManager.addResourceError(resourceError);
} catch (RuntimeException re) {
- log.error("Failed to persist resource error: " + resourceError);
+ log.error("Failed to persist Resource error [" + resourceError +
"].", re);
throw re;
}
}
commit b0a02240c70a4de3c48f4c1d8d4d5751695d3c47
Merge: 81b1e5c 4646e23
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Sep 6 16:23:08 2011 -0400
merged
commit 3132cbae82742a6e32adc598c81eaa574c45462b
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Aug 11 12:30:07 2011 -0400
[BZ 726435][coverity 13064, 13106, 13115, 13231, 13232, 13283, 13346] Fix Coverity
identified RESOURCE_LEAK; close some IO streams.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
index 323a15c..88e7705 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
@@ -49,7 +49,6 @@ import javax.persistence.Id;
import org.rhq.core.domain.resource.Agent;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.core.server.ExternalizableStrategy;
import org.rhq.core.server.ExternalizableStrategy.Subsystem;
/**
@@ -99,8 +98,7 @@ public class EntitySerializer {
Collections.sort(serializableFields, fieldComparator);
- Field[] results = serializableFields.toArray(new
Field[serializableFields.size()]);
- return results;
+ return serializableFields.toArray(new Field[serializableFields.size()]);
}
private static List<Field> getNonEntityFieldList(Object object) {
@@ -252,25 +250,29 @@ public class EntitySerializer {
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir, "entitySerializerTest.txt");
- ObjectOutput output = null;
+ FileOutputStream fos = new FileOutputStream(tempFile);
try {
- output = new ObjectOutputStream(new FileOutputStream(tempFile));
- writeExternalRemote(writeResource, output);
- } finally {
- if (output != null) {
+ ObjectOutput output = new ObjectOutputStream(fos);
+ try {
+ writeExternalRemote(writeResource, output);
+ } finally {
output.close();
}
+ } finally {
+ fos.close();
}
Resource readResource = new Resource();
- ObjectInput input = null;
+ FileInputStream fis = new FileInputStream(tempFile);
try {
- input = new ObjectInputStream(new FileInputStream(tempFile));
- readExternalRemote(readResource, input);
- } finally {
- if (input != null) {
- input.close();
+ ObjectInput ois = new ObjectInputStream(fis);
+ try {
+ readExternalRemote(readResource, ois);
+ } finally {
+ ois.close();
}
+ } finally {
+ fis.close();
}
// quick verification
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java
index fe4ee1c..10b1b1b 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java
@@ -18,11 +18,7 @@
*/
package org.rhq.core.pc;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStreamReader;
+import java.io.*;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
@@ -93,18 +89,26 @@ public class StandaloneContainer {
if (argv.length == 0) {
br = new BufferedReader(new InputStreamReader(System.in));
isStdin = true;
+ sc.run(br);
}
else {
try {
br = new BufferedReader(new InputStreamReader(new
FileInputStream(argv[0])));
- isStdin=false;
+ try {
+ isStdin=false;
+ sc.run(br);
+ } finally {
+ try {
+ br.close();
+ } catch (IOException e) {
+ System.err.println("IOException happened: " + e +
"\n");
+ }
+ }
} catch (FileNotFoundException fnfe) {
System.err.println("File " + argv[0] + " not
found");
System.exit(1);
}
}
-
- sc.run(br);
}
/**
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryFile.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryFile.java
index ea5e7fd..023a93e 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryFile.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryFile.java
@@ -205,22 +205,19 @@ public class InventoryFile {
*/
public void storeInventory(Resource platformResource, Map<String,
ResourceContainer> containers) throws IOException {
FileOutputStream fos = new FileOutputStream(inventoryFile);
-
try {
ObjectOutputStream oos = new ObjectOutputStream(fos);
-
- oos.writeObject(platformResource);
- oos.writeObject(containers);
-
- this.platform = platformResource;
- this.resourceContainers = containers;
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (Exception e) {
- }
+ try {
+ oos.writeObject(platformResource);
+ oos.writeObject(containers);
+
+ this.platform = platformResource;
+ this.resourceContainers = containers;
+ } finally {
+ oos.close();
}
+ } finally {
+ fos.close();
}
}
}
\ No newline at end of file
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginClassLoader.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginClassLoader.java
index a9b07f2..dd72117 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginClassLoader.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginClassLoader.java
@@ -215,24 +215,26 @@ public class PluginClassLoader extends URLClassLoader {
}
throw ex;
}
-
- BufferedOutputStream outputStream = new
BufferedOutputStream(fileOutputStream);
try {
- file.deleteOnExit();
-
- // do NOT close this inputStream since it is buffering the
ZipInputStream
- // and we are going to still process that input stream later.
We close
- // this ZipInputStream down below in the outer most
try-finally block.
- BufferedInputStream inputStream = new
BufferedInputStream(zis);
-
- int count;
- byte[] b = new byte[8192];
- while ((count = inputStream.read(b)) > -1) {
- outputStream.write(b, 0, count);
+ BufferedOutputStream outputStream = new
BufferedOutputStream(fileOutputStream);
+ try {
+ file.deleteOnExit();
+
+ // do NOT close this inputStream since it is buffering
the ZipInputStream
+ // and we are going to still process that input stream
later. We close
+ // this ZipInputStream down below in the outer most
try-finally block.
+ BufferedInputStream inputStream = new
BufferedInputStream(zis);
+
+ int count;
+ byte[] b = new byte[8192];
+ while ((count = inputStream.read(b)) > -1) {
+ outputStream.write(b, 0, count);
+ }
+ } finally {
+ outputStream.close(); // this also closes the
fileOutputStream
}
} finally {
- outputStream.flush();
- outputStream.close(); // this also closes the
fileOutputStream
+ fileOutputStream.close();
}
} catch (IOException ioe) {
if (file != null) {
diff --git
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/standaloneContainer/History.java
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/standaloneContainer/History.java
index 37b5bf1..bef499b 100644
---
a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/standaloneContainer/History.java
+++
b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/standaloneContainer/History.java
@@ -102,17 +102,20 @@ public class History {
}
File file = new File(tokens[1]);
try {
- file.createNewFile();
- if (file.canWrite()) {
- Writer writer = new FileWriter(file);
- for (String item : history) {
- writer.write(item);
- writer.write("\n");
+ if (file.createNewFile()) {
+ if (file.canWrite()) {
+ Writer writer = new FileWriter(file);
+ try {
+ for (String item : history) {
+ writer.write(item);
+ writer.write("\n");
+ }
+ } finally {
+ writer.close();
+ }
+ } else {
+ System.err.println("Can not write to file " + file);
}
- writer.flush();
- writer.close();
- } else {
- System.err.println("Can not write to file " + file);
}
} catch (IOException ioe) {
System.err.println("Saving the history to file " + file +
" failed: " + ioe.getMessage());
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/ZipUtil.java
b/modules/core/util/src/main/java/org/rhq/core/util/ZipUtil.java
index 8affe98..7c7ccfb 100644
--- a/modules/core/util/src/main/java/org/rhq/core/util/ZipUtil.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/ZipUtil.java
@@ -144,11 +144,16 @@ public abstract class ZipUtil {
File parentDirectoryFile = new File(parentDirectory);
parentDirectoryFile.mkdirs();
- BufferedOutputStream outputStream = new BufferedOutputStream(new
FileOutputStream(entryFile));
+ FileOutputStream fos = new FileOutputStream(entryFile);
try {
- StreamUtil.copy(zis, outputStream, false);
+ BufferedOutputStream outputStream = new
BufferedOutputStream(fos);
+ try {
+ StreamUtil.copy(zis, outputStream, false);
+ } finally {
+ outputStream.close();
+ }
} finally {
- outputStream.close();
+ fos.close();
}
}
}
@@ -167,18 +172,24 @@ public abstract class ZipUtil {
* @throws Exception if any errors occur during the reading or visiting
*/
public static void walkZipFile(File zipFile, ZipEntryVisitor visitor) throws
Exception {
- InputStream zipContent = new BufferedInputStream(new FileInputStream(zipFile));
+ FileInputStream fis = new FileInputStream(zipFile);
try {
- ZipInputStream zis = new ZipInputStream(zipContent);
- ZipEntry e;
- while ((e = zis.getNextEntry()) != null) {
- boolean keepGoing = visitor.visit(e, zis);
- if (!keepGoing) {
- break; // visitor told us to stop
+ InputStream zipContent = new BufferedInputStream(fis);
+ try {
+ ZipInputStream zis = new ZipInputStream(zipContent);
+
+ ZipEntry e;
+ while ((e = zis.getNextEntry()) != null) {
+ boolean keepGoing = visitor.visit(e, zis);
+ if (!keepGoing) {
+ break; // visitor told us to stop
+ }
}
+ } finally {
+ zipContent.close();
}
} finally {
- zipContent.close();
+ fis.close();
}
}
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 e20bf6b..ff94188 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
@@ -480,24 +480,28 @@ public class AgentManagerBean implements AgentManagerLocal {
// second, get the agent version info (by peeking into the agent update
binary jar)
JarFile binaryJarFile = new JarFile(binaryFile);
- JarEntry binaryJarFileEntry =
binaryJarFile.getJarEntry("rhq-agent-update-version.properties");
- InputStream binaryJarFileEntryStream =
binaryJarFile.getInputStream(binaryJarFileEntry);
-
- // now write the server and agent version info in our internal version file
our servlet will use
- FileOutputStream versionFileOutputStream = new
FileOutputStream(versionFile);
try {
- versionFileOutputStream.write(serverVersionInfo.toString().getBytes());
- versionFileOutputStream.write(md5Property.getBytes());
- StreamUtil.copy(binaryJarFileEntryStream, versionFileOutputStream,
false);
- } finally {
- try {
- versionFileOutputStream.close();
- } catch (Exception e) {
- }
+ JarEntry binaryJarFileEntry =
binaryJarFile.getJarEntry("rhq-agent-update-version.properties");
+ InputStream binaryJarFileEntryStream =
binaryJarFile.getInputStream(binaryJarFileEntry);
+
+ // now write the server and agent version info in our internal version
file our servlet will use
+ FileOutputStream versionFileOutputStream = new
FileOutputStream(versionFile);
try {
- binaryJarFileEntryStream.close();
- } catch (Exception e) {
+
versionFileOutputStream.write(serverVersionInfo.toString().getBytes());
+ versionFileOutputStream.write(md5Property.getBytes());
+ StreamUtil.copy(binaryJarFileEntryStream, versionFileOutputStream,
false);
+ } finally {
+ try {
+ versionFileOutputStream.close();
+ } catch (Exception e) {
+ }
+ try {
+ binaryJarFileEntryStream.close();
+ } catch (Exception e) {
+ }
}
+ } finally {
+ binaryJarFile.close();
}
}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/ServerPluginsBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/ServerPluginsBean.java
index a4103c4..4091720 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/ServerPluginsBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/ServerPluginsBean.java
@@ -646,24 +646,24 @@ public class ServerPluginsBean implements ServerPluginsLocal {
ResultSet rs = null;
FileInputStream fis = new FileInputStream(file);
-
try {
conn = this.dataSource.getConnection();
ps = conn.prepareStatement("UPDATE " + ServerPlugin.TABLE_NAME +
" SET CONTENT = ? WHERE ID = ?");
- ps.setBinaryStream(1, new BufferedInputStream(fis), (int) file.length());
- ps.setInt(2, id);
- int updateResults = ps.executeUpdate();
- if (updateResults != 1) {
- throw new Exception("Failed to update content for plugin [" +
id + "] from [" + file + "]");
+ BufferedInputStream bis = new BufferedInputStream(fis);
+ try {
+ ps.setBinaryStream(1, bis, (int) file.length());
+ ps.setInt(2, id);
+ int updateResults = ps.executeUpdate();
+ if (updateResults != 1) {
+ throw new Exception("Failed to update content for plugin ["
+ id + "] from [" + file + "]");
+ }
+ } finally {
+ bis.close();
}
} finally {
JDBCUtil.safeClose(conn, ps, rs);
-
- try {
- fis.close();
- } catch (Throwable t) {
- }
+ fis.close();
}
return;
}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginClassLoader.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginClassLoader.java
index 90e2117..00b0141 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginClassLoader.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/ServerPluginClassLoader.java
@@ -144,23 +144,26 @@ public class ServerPluginClassLoader extends URLClassLoader {
throw ex;
}
- BufferedOutputStream outputStream = new
BufferedOutputStream(fileOutputStream);
try {
- file.deleteOnExit();
-
- // do NOT close this inputStream since it is buffering the
ZipInputStream
- // and we are going to still process that input stream later.
We close
- // this ZipInputStream down below in the outer most
try-finally block.
- BufferedInputStream inputStream = new
BufferedInputStream(zis);
-
- int count;
- byte[] b = new byte[8192];
- while ((count = inputStream.read(b)) > -1) {
- outputStream.write(b, 0, count);
+ BufferedOutputStream outputStream = new
BufferedOutputStream(fileOutputStream);
+ try {
+ file.deleteOnExit();
+
+ // do NOT close this inputStream since it is buffering
the ZipInputStream
+ // and we are going to still process that input stream
later. We close
+ // this ZipInputStream down below in the outer most
try-finally block.
+ BufferedInputStream inputStream = new
BufferedInputStream(zis);
+
+ int count;
+ byte[] b = new byte[8192];
+ while ((count = inputStream.read(b)) > -1) {
+ outputStream.write(b, 0, count);
+ }
+ } finally {
+ outputStream.close(); // this also closes the
fileOutputStream
}
} finally {
- outputStream.flush();
- outputStream.close(); // this also closes the
fileOutputStream
+ fileOutputStream.close();
}
} catch (IOException ioe) {
if (file != null) {
@@ -171,10 +174,7 @@ public class ServerPluginClassLoader extends URLClassLoader {
}
}
} finally {
- try {
- zis.close();
- } catch (Exception e) {
- }
+ zis.close();
}
return extractionDirectory;
commit 421022285376d56a807a62e45fb0637c76131602
Author: Robert Buck <rbuck(a)redhat.com>
Date: Thu Aug 11 09:06:56 2011 -0400
[BZ 726435][coverity] Fix Coverity identified RESOURCE_LEAK; close some IO streams.
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
b/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
index fd8dac1..9ac9ead 100644
--- a/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
@@ -78,17 +78,22 @@ public class PropertiesFileUpdate {
// if the given property is new (doesn't exist in the file yet) just append
it and return
// if the property exists, update the value in place (ignore if the value
isn't really changing)
if (!existingProps.containsKey(key)) {
- PrintStream ps = new PrintStream(new FileOutputStream(file, true), true,
"8859_1");
- ps.println(key + "=" + value);
- ps.flush();
- ps.close();
+ FileOutputStream fos = new FileOutputStream(file, true);
+ try {
+ PrintStream ps = new PrintStream(fos, true, "8859_1");
+ try {
+ ps.println(key + "=" + value);
+ } finally {
+ ps.close();
+ }
+ } finally {
+ fos.close();
+ }
} else if (!value.equals(existingProps.getProperty(key))) {
Properties newProp = new Properties();
newProp.setProperty(key, value);
update(newProp);
}
-
- return;
}
/**
@@ -158,8 +163,6 @@ public class PropertiesFileUpdate {
fos.write(baos.toByteArray());
fos.flush();
fos.close();
-
- return;
}
/**
@@ -174,10 +177,13 @@ public class PropertiesFileUpdate {
if (file.exists()) {
FileInputStream is = new FileInputStream(file);
- props.load(is);
- is.close();
+ try {
+ props.load(is);
+ } finally {
+ is.close();
+ }
}
return props;
}
-}
\ No newline at end of file
+}
diff --git
a/modules/core/util/src/main/java/org/rhq/core/util/maven/MavenArtifactProperties.java
b/modules/core/util/src/main/java/org/rhq/core/util/maven/MavenArtifactProperties.java
index 4e749b5..5d82adc 100644
---
a/modules/core/util/src/main/java/org/rhq/core/util/maven/MavenArtifactProperties.java
+++
b/modules/core/util/src/main/java/org/rhq/core/util/maven/MavenArtifactProperties.java
@@ -133,7 +133,11 @@ public class MavenArtifactProperties {
}
Properties props = new Properties();
try {
- props.load(inputStream);
+ try {
+ props.load(inputStream);
+ } finally {
+ inputStream.close();
+ }
} catch (IOException e) {
LOG.error("Failed to load resource " + resourcePath + " into
Properties object.", e);
return null;
diff --git
a/modules/enterprise/agentupdate/src/main/java/org/rhq/enterprise/agent/update/AgentUpdate.java
b/modules/enterprise/agentupdate/src/main/java/org/rhq/enterprise/agent/update/AgentUpdate.java
index 704b48d..aaca166 100644
---
a/modules/enterprise/agentupdate/src/main/java/org/rhq/enterprise/agent/update/AgentUpdate.java
+++
b/modules/enterprise/agentupdate/src/main/java/org/rhq/enterprise/agent/update/AgentUpdate.java
@@ -200,8 +200,11 @@ public class AgentUpdate {
System.out.println(msg);
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(logFile, true));
+ try {
pw.println(msg);
- pw.close();
+ } finally {
+ pw.close();
+ }
} catch (Throwable t) {
}
}
@@ -216,8 +219,11 @@ public class AgentUpdate {
t.printStackTrace(System.out);
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(logFile, true));
- t.printStackTrace(pw);
- pw.close();
+ try {
+ t.printStackTrace(pw);
+ } finally {
+ pw.close();
+ }
} catch (Throwable t1) {
}
}
@@ -232,8 +238,11 @@ public class AgentUpdate {
System.out.println(msg);
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(logFileArgument,
true));
- pw.println(msg);
- pw.close();
+ try {
+ pw.println(msg);
+ } finally {
+ pw.close();
+ }
} catch (Throwable t) {
}
}
@@ -266,7 +275,11 @@ public class AgentUpdate {
byte[] bytes = getJarFileContent(RHQ_AGENT_UPDATE_VERSION_PROPERTIES);
InputStream propertiesStream = new ByteArrayInputStream(bytes);
Properties versionProps = new Properties();
- versionProps.load(propertiesStream);
+ try {
+ versionProps.load(propertiesStream);
+ } finally {
+ propertiesStream.close();
+ }
return versionProps;
}
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 b850605..928468b 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
@@ -564,9 +564,11 @@ public class ResourceClientProxy {
remoteClient.getSubject(), resourceClientProxy.resourceId,
installedPackage.getId());
FileOutputStream fos = new FileOutputStream(file);
- fos.write(data);
- fos.close();
-
+ try {
+ fos.write(data);
+ } finally {
+ fos.close();
+ }
}
//
------------------------------------------------------------------------------------------------------
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java
index 2d766aa..decf99e 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/CoreServer.java
@@ -133,30 +133,35 @@ public class CoreServer extends ServiceMBeanSupport implements
CoreServerMBean {
public ProductInfo getProductInfo() {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream =
classLoader.getResourceAsStream(PRODUCT_INFO_PROPERTIES_RESOURCE_PATH);
- if (inputStream == null) {
+ if (inputStream != null) {
+ Properties props = new Properties();
+ try {
+ try {
+ props.load(inputStream);
+ } finally {
+ inputStream.close();
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to load product info
properties from class loader resource ["
+ + PRODUCT_INFO_PROPERTIES_RESOURCE_PATH + "].");
+ }
+ ProductInfo productInfo = new ProductInfo();
+ // TODO: Using reflection below might be nicer.
+ productInfo.setBuildNumber(props.getProperty("buildNumber"));
+ productInfo.setFullName(props.getProperty("fullName"));
+ productInfo.setHelpDocRoot(props.getProperty("helpDocRoot"));
+ productInfo.setName(props.getProperty("name"));
+ productInfo.setSalesEmail(props.getProperty("salesEmail"));
+ productInfo.setShortName(props.getProperty("shortName"));
+ productInfo.setSupportEmail(props.getProperty("supportEmail"));
+ productInfo.setUrlDomain(props.getProperty("urlDomain"));
+ productInfo.setUrl(props.getProperty("url"));
+ productInfo.setVersion(props.getProperty("version"));
+ return productInfo;
+ } else {
throw new IllegalStateException("Failed to find class loader resource
["
+ PRODUCT_INFO_PROPERTIES_RESOURCE_PATH + "].");
}
- Properties props = new Properties();
- try {
- props.load(inputStream);
- } catch (IOException e) {
- throw new IllegalStateException("Failed to load product info properties
from class loader resource ["
- + PRODUCT_INFO_PROPERTIES_RESOURCE_PATH + "].");
- }
- ProductInfo productInfo = new ProductInfo();
- // TODO: Using reflection below might be nicer.
- productInfo.setBuildNumber(props.getProperty("buildNumber"));
- productInfo.setFullName(props.getProperty("fullName"));
- productInfo.setHelpDocRoot(props.getProperty("helpDocRoot"));
- productInfo.setName(props.getProperty("name"));
- productInfo.setSalesEmail(props.getProperty("salesEmail"));
- productInfo.setShortName(props.getProperty("shortName"));
- productInfo.setSupportEmail(props.getProperty("supportEmail"));
- productInfo.setUrlDomain(props.getProperty("urlDomain"));
- productInfo.setUrl(props.getProperty("url"));
- productInfo.setVersion(props.getProperty("version"));
- return productInfo;
}
private MBeanServer getMBeanServer() {
@@ -168,8 +173,11 @@ public class CoreServer extends ServiceMBeanSupport implements
CoreServerMBean {
ClassLoader classLoader = this.getClass().getClassLoader();
try {
InputStream stream = classLoader.getResourceAsStream(VERSION_FILE);
- buildProps.load(stream);
- stream.close();
+ try {
+ buildProps.load(stream);
+ } finally {
+ stream.close();
+ }
} catch (Exception e) {
log.fatal("Failed to load [" + VERSION_FILE + "] via class
loader [" + classLoader + "]");
}
diff --git
a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/PrintTokens.java
b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/PrintTokens.java
index a51f2fb..e7bbcd9 100644
---
a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/PrintTokens.java
+++
b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/PrintTokens.java
@@ -49,11 +49,12 @@ public class PrintTokens {
out = new BufferedOutputStream(new FileOutputStream(file));
}
- String text = createTokenDescription();
-
- out.write(text.getBytes());
- out.flush();
- out.close();
+ try {
+ String text = createTokenDescription();
+ out.write(text.getBytes());
+ } finally {
+ out.close();
+ }
}
/**
diff --git
a/modules/enterprise/server/plugins/alert-snmp/src/main/java/org/rhq/enterprise/server/plugins/alertSnmp/SnmpTrapSender.java
b/modules/enterprise/server/plugins/alert-snmp/src/main/java/org/rhq/enterprise/server/plugins/alertSnmp/SnmpTrapSender.java
index 4389779..ba4bf84 100644
---
a/modules/enterprise/server/plugins/alert-snmp/src/main/java/org/rhq/enterprise/server/plugins/alertSnmp/SnmpTrapSender.java
+++
b/modules/enterprise/server/plugins/alert-snmp/src/main/java/org/rhq/enterprise/server/plugins/alertSnmp/SnmpTrapSender.java
@@ -197,35 +197,37 @@ public class SnmpTrapSender implements PDUFactory {
public PDU send() throws IOException {
Snmp snmp = createSnmpSession();
- this.target = createTarget();
- target.setVersion(version);
- target.setAddress(address);
- target.setRetries(retries);
- target.setTimeout(timeout);
- snmp.listen();
-
- PDU request = createPDU(target);
- if (request.getType() == PDU.GETBULK) {
- request.setMaxRepetitions(maxRepetitions);
- request.setNonRepeaters(nonRepeaters);
- }
+ try {
+ this.target = createTarget();
+ target.setVersion(version);
+ target.setAddress(address);
+ target.setRetries(retries);
+ target.setTimeout(timeout);
+ snmp.listen();
+
+ PDU request = createPDU(target);
+ if (request.getType() == PDU.GETBULK) {
+ request.setMaxRepetitions(maxRepetitions);
+ request.setNonRepeaters(nonRepeaters);
+ }
- for (Object vb : vbs) {
- request.add((VariableBinding) vb);
- }
+ for (Object vb : vbs) {
+ request.add((VariableBinding) vb);
+ }
- PDU response = null;
- ResponseEvent responseEvent;
- long startTime = System.currentTimeMillis();
- responseEvent = snmp.send(request, target);
- if (responseEvent != null) {
- response = responseEvent.getResponse();
- if (log.isDebugEnabled())
- log.debug("Received response after " +
(System.currentTimeMillis() - startTime) + " millis");
+ PDU response = null;
+ ResponseEvent responseEvent;
+ long startTime = System.currentTimeMillis();
+ responseEvent = snmp.send(request, target);
+ if (responseEvent != null) {
+ response = responseEvent.getResponse();
+ if (log.isDebugEnabled())
+ log.debug("Received response after " +
(System.currentTimeMillis() - startTime) + " millis");
+ }
+ return response;
+ } finally {
+ snmp.close();
}
-
- snmp.close();
- return response;
}
private void getVariableBindings(String args) {
diff --git
a/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/RHNHelper.java
b/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/RHNHelper.java
index ac02551..62e3afd 100644
---
a/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/RHNHelper.java
+++
b/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/RHNHelper.java
@@ -470,9 +470,11 @@ public class RHNHelper {
ByteArrayOutputStream zipped = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(zipped);
- gzip.write(input);
- gzip.flush();
- gzip.close();
+ try {
+ gzip.write(input);
+ } finally {
+ gzip.close();
+ }
return zipped.toByteArray();
}
diff --git
a/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/certificate/PublicKeyRing.java
b/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/certificate/PublicKeyRing.java
index a29f272..ba45aee 100644
---
a/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/certificate/PublicKeyRing.java
+++
b/modules/enterprise/server/plugins/rhnhosted/src/main/java/org/rhq/enterprise/server/plugins/rhnhosted/certificate/PublicKeyRing.java
@@ -89,7 +89,7 @@ public class PublicKeyRing {
throws SignatureException {
PGPSignature sig = decodeSignature(asciiSig);
PGPPublicKey key;
- boolean result = false;
+ boolean result;
try {
key = keyRing.getPublicKey(sig.getKeyID());
sig.initVerify(key, RhnSecurityProvider.NAME);
@@ -119,12 +119,20 @@ public class PublicKeyRing {
* @return the signature
*/
private static PGPSignature decodeSignature(String asciiSig) {
- PGPSignature result = null;
+ PGPSignature result;
ByteArrayInputStream bais = new ByteArrayInputStream(asciiSig.getBytes());
try {
- InputStream in = PGPUtil.getDecoderStream(new ArmoredInputStream(bais));
- result = ((PGPSignatureList) new PGPObjectFactory(in).nextObject()).get(0);
- in.close();
+ ArmoredInputStream ais = new ArmoredInputStream(bais);
+ try {
+ InputStream in = PGPUtil.getDecoderStream(ais);
+ try {
+ result = ((PGPSignatureList) new
PGPObjectFactory(in).nextObject()).get(0);
+ } finally {
+ in.close();
+ }
+ } finally {
+ ais.close();
+ }
}
catch (IOException e) {
// This is so unlikely that we convert it to a runtime exception
diff --git
a/modules/enterprise/server/plugins/yum/src/main/java/org/rhq/enterprise/server/plugins/yum/Repo.java
b/modules/enterprise/server/plugins/yum/src/main/java/org/rhq/enterprise/server/plugins/yum/Repo.java
index 318a031..616dad4 100644
---
a/modules/enterprise/server/plugins/yum/src/main/java/org/rhq/enterprise/server/plugins/yum/Repo.java
+++
b/modules/enterprise/server/plugins/yum/src/main/java/org/rhq/enterprise/server/plugins/yum/Repo.java
@@ -251,9 +251,11 @@ public class Repo {
XMLOutputter printer = new XMLOutputter();
ByteArrayOutputStream zipped = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(zipped);
- printer.output(p, gzip);
- gzip.flush();
- gzip.close();
+ try {
+ printer.output(p, gzip);
+ } finally {
+ gzip.close();
+ }
return zipped.toByteArray();
}
}
\ No newline at end of file
diff --git
a/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
b/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
index bdda353..6160643 100644
--- a/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
+++ b/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
@@ -156,11 +156,13 @@ public class BundleGen {
Template templ = config.getTemplate(template + ".ftl");
Writer out = new BufferedWriter(new FileWriter(new File(directory,
fileName)));
- Map<String, Props> root = new HashMap<String, Props>();
- root.put("props", props);
- templ.process(root, out);
- out.flush();
- out.close();
+ try {
+ Map<String, Props> root = new HashMap<String, Props>();
+ root.put("props", props);
+ templ.process(root, out);
+ } finally {
+ out.close();
+ }
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (TemplateException te) {
diff --git
a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
index 3b76d52..223a57f 100644
--- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
@@ -363,7 +363,6 @@ public class PluginGen {
templ.process(root, out);
}
finally {
- out.flush();
out.close();
}
} catch (IOException ioe) {
diff --git
a/modules/integration-tests/apache-plugin-test/src/test/java/org/rhq/plugins/apache/util/ApacheDeploymentUtil.java
b/modules/integration-tests/apache-plugin-test/src/test/java/org/rhq/plugins/apache/util/ApacheDeploymentUtil.java
index 6183694..bc80898 100644
---
a/modules/integration-tests/apache-plugin-test/src/test/java/org/rhq/plugins/apache/util/ApacheDeploymentUtil.java
+++
b/modules/integration-tests/apache-plugin-test/src/test/java/org/rhq/plugins/apache/util/ApacheDeploymentUtil.java
@@ -350,47 +350,30 @@ public class ApacheDeploymentUtil {
Map<String, String> replacements = config.getTokenReplacements();
for (File file : configFiles) {
- Reader rdr = null;
- FileWriter wrt = null;
-
try {
- rdr = new TokenReplacingReader(new FileReader(file), replacements);
-
File tmp = File.createTempFile("apache-deployment-util",
null);
- wrt = new FileWriter(tmp);
-
- int cnt = -1;
-
- while ((cnt = rdr.read(buffer)) != -1) {
- wrt.write(buffer, 0, cnt);
+ FileWriter wrt = new FileWriter(tmp);
+ try {
+ Reader rdr = new TokenReplacingReader(new FileReader(file),
replacements);
+ try {
+ int cnt = -1;
+ while ((cnt = rdr.read(buffer)) != -1) {
+ wrt.write(buffer, 0, cnt);
+ }
+ } finally {
+ rdr.close();
+ }
+ } finally {
+ wrt.close();
}
- rdr.close();
- wrt.close();
-
//now overwrite the contents of the original file with the new one.
//we don't just move the new file to the location of the original
one
//here to preserve the file permissions and file mode on the original.
FileUtil.copyFile(tmp, file);
} catch (IOException e) {
LOG.error("Error while replacing the tokens in file '" +
file + "'.", e);
-
- if (rdr != null) {
- try {
- rdr.close();
- } catch (IOException ioe) {
-
- }
- }
-
- if (wrt != null) {
- try {
- wrt.close();
- } catch (IOException ioe) {
-
- }
- }
}
}
}
diff --git
a/modules/jopr/tools/jbas5-plugin-descriptor-gen/src/main/java/org/jboss/jopr/tool/jbas5/PluginDescriptorGenerator.java
b/modules/jopr/tools/jbas5-plugin-descriptor-gen/src/main/java/org/jboss/jopr/tool/jbas5/PluginDescriptorGenerator.java
index 49e6089..5019fea 100644
---
a/modules/jopr/tools/jbas5-plugin-descriptor-gen/src/main/java/org/jboss/jopr/tool/jbas5/PluginDescriptorGenerator.java
+++
b/modules/jopr/tools/jbas5-plugin-descriptor-gen/src/main/java/org/jboss/jopr/tool/jbas5/PluginDescriptorGenerator.java
@@ -371,12 +371,15 @@ public class PluginDescriptorGenerator
{
LOG.info("Writing plugin descriptor to [" + file + "]...");
OutputStream outputStream = new BufferedOutputStream(new
FileOutputStream(file));
- JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);
- Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new
RhqNamespacePrefixMapper());
- marshaller.marshal(pluginDescriptor, outputStream);
- outputStream.close();
+ try {
+ JAXBContext jaxbContext =
JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);
+ Marshaller marshaller = jaxbContext.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+ marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
new RhqNamespacePrefixMapper());
+ marshaller.marshal(pluginDescriptor, outputStream);
+ } finally {
+ outputStream.close();
+ }
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
index 974f8ef..0b04d77 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
@@ -95,10 +95,13 @@ public class SNMPClient {
}
Properties props = new Properties();
try {
- props.load(stream);
+ try {
+ props.load(stream);
+ } finally {
+ stream.close();
+ }
} catch (Exception e) {
throw new IllegalStateException("Failed to parse oids.properties file
from plugin classloader.", e);
-
}
Enumeration<?> propNames = props.propertyNames();
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerContentFacetDelegate.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerContentFacetDelegate.java
index 6166076..05ca8e7 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerContentFacetDelegate.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerContentFacetDelegate.java
@@ -185,7 +185,6 @@ public class ApplicationServerContentFacetDelegate extends
AbstractJBossASConten
// Request the bits from the server
try {
contentServices.downloadPackageBits(contentContext, key, bufferedOutput,
true);
- bufferedOutput.close();
// Verify the file was created correctly
File downloadedFile = new File(destinationFileLocation);
diff --git
a/modules/plugins/script2/src/main/java/org/rhq/modules/plugins/script2/ScriptComponent.java
b/modules/plugins/script2/src/main/java/org/rhq/modules/plugins/script2/ScriptComponent.java
index 1df7f29..4a22007 100644
---
a/modules/plugins/script2/src/main/java/org/rhq/modules/plugins/script2/ScriptComponent.java
+++
b/modules/plugins/script2/src/main/java/org/rhq/modules/plugins/script2/ScriptComponent.java
@@ -97,17 +97,28 @@ public class ScriptComponent implements ResourceComponent,
MeasurementFacet, Ope
if (!scriptFile.exists())
throw new InvalidPluginConfigurationException("Script does not exist at
" + scriptFile.getAbsolutePath());
- Reader reader;
try {
- reader = new BufferedReader(new FileReader(scriptFile));
- StringWriter writer = new StringWriter();
- int tmp;
- while ((tmp=reader.read())!=-1)
- writer.write(tmp);
-
- reader.close();
- theScript = writer.toString();
- writer.close();
+ FileReader fr = new FileReader(scriptFile);
+ try {
+ Reader reader = new BufferedReader(fr);
+ try {
+ StringWriter writer = new StringWriter();
+ try {
+ int tmp;
+ while ((tmp=reader.read())!=-1) {
+ writer.write(tmp);
+ }
+ reader.close();
+ theScript = writer.toString();
+ } finally {
+ writer.close();
+ }
+ } finally {
+ reader.close();
+ }
+ } finally {
+ fr.close();
+ }
engine.eval(theScript);
}
commit b47ed240bbd1a0bce77649fc77007383f25ca35e
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Aug 10 10:07:08 2011 -0400
[BZ 726435] Fixed several bitwise-or uses on booleans, switching to logical-or.
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
index f372363..f7a510e 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
@@ -182,7 +182,7 @@ public class MappingToAugeasDirectivePerMapIndex extends
ConfigurationToAugeasAp
PropertyMap propMap = (PropertyMap)prop;
PropertySimple propSim =
((PropertySimple)propMap.get("_index"));
int value;
- if (propSim ==null | propSim.getIntegerValue() == null)
+ if (propSim ==null || propSim.getIntegerValue() == null)
value = 0;
else
value = propSim.getIntegerValue().intValue();
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
index 9da0cb0..f181481 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
@@ -133,7 +133,7 @@ public class MappingToAugeasParamPerMap extends
ConfigurationToAugeasApacheBase{
PropertyMap propMap = (PropertyMap)prop;
PropertySimple propSim =
((PropertySimple)propMap.get("_index"));
int value;
- if (propSim ==null | propSim.getIntegerValue() == null)
+ if (propSim ==null || propSim.getIntegerValue() == null)
value = 0;
else
value = propSim.getIntegerValue().intValue();
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
index fa7d196..404fb5d 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
@@ -183,7 +183,7 @@ public class ApacheDirectiveRegExpression {
return nodeParams;
}
- if (name.equals("Allow") | name.equals("Deny")){
+ if (name.equals("Allow") || name.equals("Deny")){
nodeParams.add("from");
}
//each regex is applied as long as it matches something
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
index 2c13f87..e600dce 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
@@ -55,7 +55,7 @@ public class SpecificParams {
if (name.equals("Listen")){
int i;
StringBuilder val = new StringBuilder(value);
- while (val.charAt(0) == ' ' | val.charAt(0) == '\t')
+ while (val.charAt(0) == ' ' || val.charAt(0) == '\t')
val.deleteCharAt(0);
String [] str = val.toString().split("[ \t]+");
diff --git
a/modules/plugins/augeas/src/main/java/org/rhq/rhqtransform/impl/ConfigurationToAugeasSimple.java
b/modules/plugins/augeas/src/main/java/org/rhq/rhqtransform/impl/ConfigurationToAugeasSimple.java
index 26a10a5..de43610 100644
---
a/modules/plugins/augeas/src/main/java/org/rhq/rhqtransform/impl/ConfigurationToAugeasSimple.java
+++
b/modules/plugins/augeas/src/main/java/org/rhq/rhqtransform/impl/ConfigurationToAugeasSimple.java
@@ -94,8 +94,8 @@ public class ConfigurationToAugeasSimple implements
ConfigurationToAugeas {
List<AugeasNode> nodes = tree.matchRelative(mapNode,
propDefMap.getName());
AugeasNode node;
- int i = 0;
- if (nodes.isEmpty() | nodes.size() < seq) {
+ int i;
+ if (nodes.isEmpty() || nodes.size() < seq) {
node = tree.createNode(mapNode, propDefMap.getName(), null, seq);
nodes.add(node);
i = ((seq == 0) ? 0 : seq - 1);
@@ -130,9 +130,9 @@ public class ConfigurationToAugeasSimple implements
ConfigurationToAugeas {
}
List<AugeasNode> nodes = tree.matchRelative(listNode, propDef.getName());
- AugeasNode node = null;
+ AugeasNode node;
- if (nodes.isEmpty() | nodes.size() < seq) {
+ if (nodes.isEmpty() || nodes.size() < seq) {
node = tree.createNode(listNode, propDef.getName(), null, seq);
nodes.add(node);
} else
@@ -150,7 +150,7 @@ public class ConfigurationToAugeasSimple implements
ConfigurationToAugeas {
throws AugeasRhqException {
PropertySimple simpleProp = null;
- AugeasNode node = null;
+ AugeasNode node;
if (prop instanceof PropertyList) {
PropertyList lst = (PropertyList) prop;
List<Property> props = lst.getList();
commit dc3c6f68af412eb7826e71ae62f43cc3c1d66a06
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Aug 10 09:58:31 2011 -0400
[BZ 726435][coverity 13546 12979 12996] Fix Coverity identified FORWARD_NULL. Also,
fixed several bitwise-and uses on booleans, switching to logical-and.
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
index 3e1364b..b17d67a 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
@@ -586,7 +586,6 @@ public class ConfigurationEditor extends LocatableVLayout {
property, odd, fields);
odd = !odd;
}
- return;
}
public void addItemsForPropertyRecursively(String locatorId, PropertyDefinition
propertyDefinition,
@@ -1064,13 +1063,18 @@ public class ConfigurationEditor extends LocatableVLayout {
}
private PropertyMapListGridRecord[] buildSummaryRecords(PropertyList propertyList,
List<PropertyDefinition> definitions) {
- PropertyMapListGridRecord[] records = new PropertyMapListGridRecord[propertyList
== null ? 0 : propertyList.getList().size()];
- List<Property> list = propertyList.getList();
- for (int index = 0, listSize = list.size(); index < listSize; index++) {
- Property row = list.get(index);
- PropertyMap rowMap = (PropertyMap) row;
- PropertyMapListGridRecord record = new PropertyMapListGridRecord(rowMap,
index, definitions);
- records[index] = record;
+ PropertyMapListGridRecord[] records;
+ if (propertyList == null) {
+ records = new PropertyMapListGridRecord[0];
+ } else {
+ records = new PropertyMapListGridRecord[propertyList.getList().size()];
+ List<Property> list = propertyList.getList();
+ for (int index = 0, listSize = list.size(); index < listSize; index++) {
+ Property row = list.get(index);
+ PropertyMap rowMap = (PropertyMap) row;
+ PropertyMapListGridRecord record = new PropertyMapListGridRecord(rowMap,
index, definitions);
+ records[index] = record;
+ }
}
return records;
}
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java
index 7b23c0a..0c14cb6 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java
@@ -298,7 +298,7 @@ public class PortletFactory {
public static PortletViewFactory getRegisteredPortletFactory(String key) {
PortletViewFactory portletFactory = null;
- if ((key != null) & (!key.trim().isEmpty())) {
+ if ((key != null) && (!key.trim().isEmpty())) {
portletFactory = registeredPortletFactoryMap.get(key);
}
return portletFactory;
@@ -306,7 +306,7 @@ public class PortletFactory {
public static PortletViewFactory getRegisteredGroupPortletFactory(String key) {
PortletViewFactory portletFactory = null;
- if ((key != null) & (!key.trim().isEmpty())) {
+ if ((key != null) && (!key.trim().isEmpty())) {
portletFactory = registeredGroupPortletFactoryMap.get(key);
}
return portletFactory;
@@ -314,7 +314,7 @@ public class PortletFactory {
public static PortletViewFactory getRegisteredResourcePortletFactory(String key) {
PortletViewFactory portletFactory = null;
- if ((key != null) & (!key.trim().isEmpty())) {
+ if ((key != null) && (!key.trim().isEmpty())) {
portletFactory = registeredResourcePortletFactoryMap.get(key);
}
return portletFactory;
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java
index 803df4c..0959d9b 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/GwtRelativeDurationConverter.java
@@ -37,10 +37,10 @@ public class GwtRelativeDurationConverter {
int dayOfYearEvent = Integer.parseInt(dayFormatter.format(new
Date(eventMillis)));
String result = null;
//add additional check to fix when dayOfYear and dayOfYearToday is same but month
apart.
- if ((dayOfYearEvent == dayOfYearToday) & ((now - eventMillis) <
MILLIS_IN_DAY)) {
+ if ((dayOfYearEvent == dayOfYearToday) && ((now - eventMillis) <
MILLIS_IN_DAY)) {
// <time>
result = formatter.format(new Date(eventMillis));
- } else if ((dayOfYearEvent == dayOfYearToday - 1) & ((now - eventMillis) <
MILLIS_IN_DAY * 28)) {
+ } else if ((dayOfYearEvent == dayOfYearToday - 1) && ((now - eventMillis)
< MILLIS_IN_DAY * 28)) {
// "yesterday" <time>
result = MSG.common_label_yesterday() + ", " + formatter.format(new
Date(eventMillis));
} else {
diff --git
a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/ClientMain.java
b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/ClientMain.java
index 1f6f007..b3968e6 100755
---
a/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/ClientMain.java
+++
b/modules/enterprise/remoting/cli/src/main/java/org/rhq/enterprise/client/ClientMain.java
@@ -219,7 +219,7 @@ public class ClientMain {
* @return flag indicating status of realtime check.
*/
public boolean loggedIn() {
- return subject != null && remoteClient != null &
remoteClient.isLoggedIn();
+ return subject != null && remoteClient != null &&
remoteClient.isLoggedIn();
}
/**
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
index b6a3b35..f372363 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectivePerMapIndex.java
@@ -191,7 +191,7 @@ public class MappingToAugeasDirectivePerMapIndex extends
ConfigurationToAugeasAp
map.add(propMap);
count = count + 1;
}
- if (value > min & value<next){
+ if (value > min && value<next){
next = value;
}
}
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
index a274099..9da0cb0 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
@@ -142,7 +142,7 @@ public class MappingToAugeasParamPerMap extends
ConfigurationToAugeasApacheBase{
tempList.add(propMap);
count = count + 1;
}
- if (value > min & value<next){
+ if (value > min && value<next){
next = value;
}
}
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
index 9d9dc33..2c13f87 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
@@ -27,7 +27,7 @@ public class SpecificParams {
Pattern pattern = Pattern.compile("[ \t]*(Add|Remove|Set)[
\t]*([a-zA-Z]+)");
int startIndex = 0;
boolean updated = true;
- while (updated & startIndex < value.length()){
+ while (updated && startIndex < value.length()){
updated = false;
Matcher m = pattern.matcher(value);
while (m.find(startIndex)) {
@@ -96,7 +96,7 @@ public class SpecificParams {
Pattern pattern = Pattern.compile("[ \t]*([+-]?)([a-zA-Z]+)");
int startIndex = 0;
boolean updated = true;
- while (updated & startIndex < value.length()){
+ while (updated && startIndex < value.length()){
updated = false;
Matcher m = pattern.matcher(value);
while (m.find(startIndex)) {
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
index ae2f025..d02e447 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
@@ -41,7 +41,7 @@ public class ApacheDirective implements Cloneable {
}else{
int startIndex = 0;
boolean updated = true;
- while (updated & startIndex < directive.length()){
+ while (updated && startIndex < directive.length()){
updated = false;
Matcher m = DIRECTIVE_PATTERN.matcher(directive);
while (m.find(startIndex)) {
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
index 6c3a362..077d263 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
@@ -44,7 +44,7 @@ public class AugeasNodeSearch {
boolean match = true;
int i =0;
- while (match & i<nodeParams.size() & tempNode!=parentNode){
+ while (match && i<nodeParams.size() &&
tempNode!=parentNode){
List<AugeasNode> childNodes =
tempNode.getChildByLabel("param");
if (childNodes.size()>0){
if (!nodeParams.get(i).equals(childNodes.get(0).getValue()))
@@ -135,7 +135,7 @@ public class AugeasNodeSearch {
public static String getNodeKey(AugeasNode node,AugeasNode parentNode){
AugeasNode pNode = node;
StringBuilder str = new StringBuilder();
- while (pNode!=null & !pNode.equals(parentNode))
+ while (pNode!=null && !pNode.equals(parentNode))
{
str.append(getNodeKeyFromParent(pNode));
pNode = pNode.getParentNode();
diff --git
a/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/AugeasNodeBuffer.java
b/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/AugeasNodeBuffer.java
index fd66390..9ba9e09 100644
--- a/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/AugeasNodeBuffer.java
+++ b/modules/plugins/augeas/src/main/java/org/rhq/augeas/tree/AugeasNodeBuffer.java
@@ -89,7 +89,7 @@ public class AugeasNodeBuffer {
for (String key : buffer.keySet()) {
int index = key.indexOf(parentNode.getFullPath());
- if ((index == 0) & (key.length() > parentNode.getFullPath().length()))
{
+ if ((index == 0) && (key.length() >
parentNode.getFullPath().length())) {
String localPath = key.substring(parentNode.getFullPath().length());
int endOfLabel = localPath.indexOf(File.separatorChar);
String label;
diff --git
a/modules/plugins/jboss-cache-v3/src/test/java/org/rhq/plugins/jbosscache3/test/TestHelper.java
b/modules/plugins/jboss-cache-v3/src/test/java/org/rhq/plugins/jbosscache3/test/TestHelper.java
index 7600a2e..16c453e 100644
---
a/modules/plugins/jboss-cache-v3/src/test/java/org/rhq/plugins/jbosscache3/test/TestHelper.java
+++
b/modules/plugins/jboss-cache-v3/src/test/java/org/rhq/plugins/jbosscache3/test/TestHelper.java
@@ -65,7 +65,7 @@ public class TestHelper {
public static boolean compareValues(String value, String type, Object obj) {
- if (value == null & obj == null)
+ if (value == null && obj == null)
return true;
if (type.equals("int")) {
commit f286cfe6f1b4f87516942545c6dc8d8031b12f9e
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Aug 10 08:23:20 2011 -0400
[BZ 726435][coverity 13171] Fix Coverity identified REVERSE_INULL. Fix unnecessary
boxing of '0' to Integer object returns.
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java
index c222819..ffd9607 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java
@@ -59,10 +59,10 @@ public class GroupForm extends BaseValidatorForm {
*/
public Integer getCompatibleCount() {
if ((platformTypes == null) || (serverTypes == null) || (serviceTypes == null))
{
- return new Integer(0);
+ return 0;
}
- return new Integer(platformTypes.size() + serverTypes.size() +
serviceTypes.size());
+ return platformTypes.size() + serverTypes.size() + serviceTypes.size();
}
/**
@@ -70,10 +70,10 @@ public class GroupForm extends BaseValidatorForm {
*/
public Integer getClusterCount() {
if (serviceTypes == null) {
- return new Integer(0);
+ return 0;
}
- return new Integer(serviceTypes.size());
+ return serviceTypes.size();
}
/**
@@ -92,10 +92,10 @@ public class GroupForm extends BaseValidatorForm {
*/
public Integer getPlatformTypeCount() {
if (platformTypes == null) {
- return new Integer(0);
+ return 0;
}
- return new Integer(platformTypes.size());
+ return platformTypes.size();
}
/**
@@ -114,10 +114,10 @@ public class GroupForm extends BaseValidatorForm {
*/
public Integer getServerTypeCount() {
if (serverTypes == null) {
- return new Integer(0);
+ return 0;
}
- return new Integer(serverTypes.size());
+ return serverTypes.size();
}
/**
@@ -136,10 +136,10 @@ public class GroupForm extends BaseValidatorForm {
*/
public Integer getServiceTypeCount() {
if (serviceTypes == null) {
- return new Integer(0);
+ return 0;
}
- return new Integer(serviceTypes.size());
+ return serviceTypes.size();
}
/**
@@ -170,17 +170,16 @@ public class GroupForm extends BaseValidatorForm {
}
private List<Map<String, Object>>
getOptionListItemsWithDashes(List<ResourceType> types) {
- Map<String, Integer> typeNameCounts = new HashMap<String,
Integer>();
- for (ResourceType type : types) {
- if (typeNameCounts.containsKey(type.getName()) == false) {
- typeNameCounts.put(type.getName(), 1);
- } else {
- typeNameCounts.put(type.getName(), typeNameCounts.get(type.getName()) +
1);
- }
- }
-
List<Map<String, Object>> items = new ArrayList<Map<String,
Object>>();
if (types != null) {
+ Map<String, Integer> typeNameCounts = new HashMap<String,
Integer>();
+ for (ResourceType type : types) {
+ if (!typeNameCounts.containsKey(type.getName())) {
+ typeNameCounts.put(type.getName(), 1);
+ } else {
+ typeNameCounts.put(type.getName(), typeNameCounts.get(type.getName())
+ 1);
+ }
+ }
for (ResourceType type : types) {
// GroupTypeForm needs this data format - a map with "value"
and "label" keys
Map<String, Object> map = new HashMap<String, Object>(2);
@@ -190,7 +189,6 @@ public class GroupForm extends BaseValidatorForm {
items.add(map);
}
}
-
return items;
}
commit 1eea642da40862bc5f0e9839542836cf7f5e8d8f
Author: Robert Buck <rbuck(a)redhat.com>
Date: Wed Aug 10 07:32:28 2011 -0400
[BZ 726435][coverity
13231,13284,13288,13343,13344,13361,13417,13424,13504,13521,13527,13542,14054] Fix
Coverity identified RESOURCE_LEAK; close some IO streams.
diff --git
a/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/PluginDocGenerator.java
b/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/PluginDocGenerator.java
index ee2681d..be7607b 100644
---
a/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/PluginDocGenerator.java
+++
b/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/PluginDocGenerator.java
@@ -67,17 +67,17 @@ public class PluginDocGenerator {
throw new IllegalArgumentException("Argument to loadProperties must not
be null");
}
- InputStream fileInputStream;
+ Properties props = new Properties();
try {
File f = new File(propertiesFileName);
- fileInputStream = new FileInputStream(f);
+ InputStream fileInputStream = new FileInputStream(f);
+ try {
+ props.load(fileInputStream);
+ } finally {
+ fileInputStream.close();
+ }
} catch (FileNotFoundException fnfe) {
throw new IllegalArgumentException(propertiesFileName + " file does not
exist");
- }
-
- Properties props = new Properties();
- try {
- props.load(fileInputStream);
} catch (IOException ioe) {
throw new IllegalStateException("Error loading properties from " +
propertiesFileName + ": "
+ ioe.getMessage());
diff --git
a/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/VelocityTemplateProcessor.java
b/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/VelocityTemplateProcessor.java
index 70b595f..fdc2af7 100644
---
a/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/VelocityTemplateProcessor.java
+++
b/modules/core/plugindoc/src/main/java/org/rhq/core/tool/plugindoc/VelocityTemplateProcessor.java
@@ -74,11 +74,15 @@ public class VelocityTemplateProcessor {
public void processTemplate(File outputFile) {
try {
- OutputStream outputStream = new FileOutputStream(outputFile);
- Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));
- this.template.merge(this.context, writer);
- writer.close();
- outputStream.close();
+ Writer writer = null;
+ try {
+ writer = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(outputFile)));
+ this.template.merge(this.context, writer);
+ } finally {
+ if (writer != null) {
+ writer.close();
+ }
+ }
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
index bad2170..ff402b5 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/DownloadsUIBean.java
@@ -42,10 +42,14 @@ public class DownloadsUIBean implements Serializable {
File file = LookupUtil.getAgentManager().getAgentUpdateVersionFile();
Properties props = new Properties();
- props.load(new FileInputStream(file));
+ FileInputStream fis = new FileInputStream(file);
+ try {
+ props.load(fis);
+ } finally {
+ fis.close();
+ }
return props;
-
} catch (Exception e) {
throw new RuntimeException("Agent download information not
available", e);
}
@@ -53,8 +57,7 @@ public class DownloadsUIBean implements Serializable {
public List<File> getConnectorDownloadFiles() throws Exception {
File downloadDir = getConnectorDownloadsDir();
- List<File> files = getFiles(downloadDir);
- return files;
+ return getFiles(downloadDir);
}
private File getConnectorDownloadsDir() throws Exception {
@@ -79,7 +82,12 @@ public class DownloadsUIBean implements Serializable {
File versionFile = new File(getClientDownloadDir(),
"rhq-client-version.properties");
try {
Properties p = new Properties();
- p.load(new FileInputStream(versionFile));
+ FileInputStream fis = new FileInputStream(versionFile);
+ try {
+ p.load(fis);
+ } finally {
+ fis.close();
+ }
return p;
} catch (Exception e) {
throw new RuntimeException("Unable to retrieve client version
info", e);
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
index 1e067be..8a97186 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/content/CreateNewPackageUIBean.java
@@ -132,8 +132,7 @@ public class CreateNewPackageUIBean {
selectedArchitectureId = getBackingPackageArchitectureId();
selectedPackageTypeId = getBackingPackageTypeId();
}
- String response = createNewPackage(packageName, version, selectedArchitectureId,
selectedPackageTypeId);
- return response;
+ return createNewPackage(packageName, version, selectedArchitectureId,
selectedPackageTypeId);
}
public String createNewPackage(String packageName, String version, int
architectureId, int packageTypeId) {
@@ -201,12 +200,56 @@ public class CreateNewPackageUIBean {
}
try {
- // Grab a stream for the file being uploaded
- InputStream packageStream;
-
+ PackageVersion packageVersion = null;
try {
log.debug("Streaming new package bits from uploaded file: " +
fileItem.getFile());
- packageStream = new FileInputStream(fileItem.getFile());
+
+ // Grab a stream for the file being uploaded
+ InputStream packageStream = new FileInputStream(fileItem.getFile());
+ try {
+ // Ask the bean to create the package
+
+ /* Currently, this is just used in the workflow for deploying a new
package. This will probably get
+ refactored in the future for a general way of adding packages to
the repo as its own operation. For
+ now, don't worry about that. The rest of this will be written
assuming it's part of the deploy
+ workflow and we'll deal with the refactoring later.
+ jdobies, Feb 27, 2008
+ */
+ try {
+ ContentManagerLocal contentManager =
LookupUtil.getContentManager();
+
+ //store information about uploaded file for packageDetails as
most of it is already available
+ Map<String, String> packageUploadDetails = new
HashMap<String, String>();
+ packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_SIZE,
String.valueOf(fileItem.getFileSize()));
+
packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_INSTALL_DATE,
String.valueOf(System
+ .currentTimeMillis()));
+ packageUploadDetails.put(ContentManagerLocal.UPLOAD_OWNER,
subject.getName());
+ packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_NAME,
fileItem.getFileName());
+
+ try {//Easier to implement here than in server side bean.
Shouldn't affect performance too much.
+ packageUploadDetails.put(ContentManagerLocal.UPLOAD_MD5, new
MessageDigestGenerator(
+
MessageDigestGenerator.MD5).calcDigestString(fileItem.getFile()));
+ packageUploadDetails.put(ContentManagerLocal.UPLOAD_SHA256,
new MessageDigestGenerator(
+
MessageDigestGenerator.SHA_256).calcDigestString(fileItem.getFile()));
+ } catch (IOException e1) {
+ log.warn("Error calculating file digest(s)", e1);
+ }
+
+ Integer iRepoId = usingARepo ? Integer.parseInt(repoId) : null;
+ packageVersion =
contentManager.getUploadedPackageVersion(subject, packageName, packageTypeId,
+ version, architectureId, packageStream, packageUploadDetails,
iRepoId);
+
+ } catch (NoResultException nre) {
+ //eat the exception. Some of the queries return no results if no
package yet exists which is fine.
+ } catch (Exception e) {
+ String errorMessages = ThrowableUtil.getAllMessages(e);
+ FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR,
"Failed to create package [" + packageName
+ + "] in repository. Cause: " + errorMessages);
+ return "failure";
+ }
+ } finally {
+ packageStream.close();
+ }
} catch (IOException e) {
String errorMessages = ThrowableUtil.getAllMessages(e);
FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR,
@@ -214,47 +257,6 @@ public class CreateNewPackageUIBean {
return "failure";
}
- // Ask the bean to create the package
-
- /* Currently, this is just used in the workflow for deploying a new package.
This will probably get
- refactored in the future for a general way of adding packages to the repo
as its own operation. For
- now, don't worry about that. The rest of this will be written assuming
it's part of the deploy
- workflow and we'll deal with the refactoring later.
- jdobies, Feb 27, 2008
- */
- PackageVersion packageVersion = null;
- try {
- ContentManagerLocal contentManager = LookupUtil.getContentManager();
-
- //store information about uploaded file for packageDetails as most of it
is already available
- Map<String, String> packageUploadDetails = new HashMap<String,
String>();
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_SIZE,
String.valueOf(fileItem.getFileSize()));
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_INSTALL_DATE,
String.valueOf(System
- .currentTimeMillis()));
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_OWNER,
subject.getName());
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_FILE_NAME,
fileItem.getFileName());
-
- try {//Easier to implement here than in server side bean. Shouldn't
affect performance too much.
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_MD5, new
MessageDigestGenerator(
-
MessageDigestGenerator.MD5).calcDigestString(fileItem.getFile()));
- packageUploadDetails.put(ContentManagerLocal.UPLOAD_SHA256, new
MessageDigestGenerator(
-
MessageDigestGenerator.SHA_256).calcDigestString(fileItem.getFile()));
- } catch (IOException e1) {
- log.warn("Error calculating file digest(s)", e1);
- }
-
- Integer iRepoId = usingARepo ? Integer.parseInt(repoId) : null;
- packageVersion = contentManager.getUploadedPackageVersion(subject,
packageName, packageTypeId,
- version, architectureId, packageStream, packageUploadDetails,
iRepoId);
-
- } catch (NoResultException nre) {
- //eat the exception. Some of the queries return no results if no package
yet exists which is fine.
- } catch (Exception e) {
- String errorMessages = ThrowableUtil.getAllMessages(e);
- FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR, "Failed
to create package [" + packageName
- + "] in repository. Cause: " + errorMessages);
- return "failure";
- }
int[] packageVersionList = new int[] { packageVersion.getId() };
@@ -321,7 +323,7 @@ public class CreateNewPackageUIBean {
private SelectItem[] getPackageTypes(boolean includeResourceTypeResolution) {
Resource resource = EnterpriseFacesContextUtility.getResourceIfExists();
- List<PackageType> packageTypes = null;
+ List<PackageType> packageTypes;
ContentUIManagerLocal contentUIManager = LookupUtil.getContentUIManager();
if (resource != null) {
packageTypes =
contentUIManager.getPackageTypes(resource.getResourceType().getId());
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
index 3f1a3cc..fcb75b4 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/resource/CreateNewPackageChildResourceUIBean.java
@@ -154,62 +154,64 @@ public class CreateNewPackageChildResourceUIBean {
}
try {
- InputStream packageContentStream;
try {
log.debug("Streaming new package bits from uploaded file: " +
fileItem.getFile());
- packageContentStream = new FileInputStream(fileItem.getFile());
- } catch (IOException e) {
- String errorMessages = ThrowableUtil.getAllMessages(e);
- FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR,
- "Failed to retrieve the input stream. Cause: " +
errorMessages);
- return OUTCOME_SUCCESS_OR_FAILURE;
- }
-
- if (isSupportsArchitecture()) {
- // pull in architecture selection
- selectedArchitectureId = getSelectedArchitectureId();
- }
-
- // Collect data for create call
- Resource parentResource = EnterpriseFacesContextUtility.getResource();
- Configuration deployTimeConfiguration = getConfiguration();
- String packageName = fileItem.getFileName();
-
- // some browsers (IE in particular) passes an absolute filename, we just want
the name of the file, no paths
- if (packageName != null) {
- packageName = packageName.replace('\\', '/');
- if (packageName.length() > 2 && packageName.charAt(1) ==
':') {
- packageName = packageName.substring(2);
- }
- packageName = new File(packageName).getName();
- }
-
- try {
- ResourceFactoryManagerLocal resourceFactoryManager =
LookupUtil.getResourceFactoryManager();
-
- // RHQ-666 - Changed to not request the resource name from the user;
simply pass null
- // JON 2.0 RC3 - use timestamp versioning; pass null for version
- // resourceFactoryManager.createResource(user,
parentResource.getId(), getResourceTypeId(), null,
- // pluginConfiguration, packageName, null,
selectedArchitectureId, deployTimeConfiguration,
- // packageContentStream);
- if (packageUploadDetails != null) {
- resourceFactoryManager.createResource(user, parentResource.getId(),
getResourceTypeId(), null,
- pluginConfiguration, packageName, getVersion(),
selectedArchitectureId,
- deployTimeConfiguration, packageContentStream,
packageUploadDetails);
- } else {
- resourceFactoryManager.createResource(user, parentResource.getId(),
getResourceTypeId(), null,
- pluginConfiguration, packageName, null, selectedArchitectureId,
deployTimeConfiguration,
- packageContentStream);
-
+ InputStream packageContentStream = new
FileInputStream(fileItem.getFile());
+ try {
+ if (isSupportsArchitecture()) {
+ // pull in architecture selection
+ selectedArchitectureId = getSelectedArchitectureId();
+ }
+
+ // Collect data for create call
+ Resource parentResource =
EnterpriseFacesContextUtility.getResource();
+ Configuration deployTimeConfiguration = getConfiguration();
+ String packageName = fileItem.getFileName();
+
+ // some browsers (IE in particular) passes an absolute filename, we
just want the name of the file, no paths
+ if (packageName != null) {
+ packageName = packageName.replace('\\', '/');
+ if (packageName.length() > 2 && packageName.charAt(1)
== ':') {
+ packageName = packageName.substring(2);
+ }
+ packageName = new File(packageName).getName();
+ }
+
+ try {
+ ResourceFactoryManagerLocal resourceFactoryManager =
LookupUtil.getResourceFactoryManager();
+
+ // RHQ-666 - Changed to not request the resource name from the
user; simply pass null
+ // JON 2.0 RC3 - use timestamp versioning; pass null for version
+ // resourceFactoryManager.createResource(user,
parentResource.getId(), getResourceTypeId(), null,
+ // pluginConfiguration, packageName, null,
selectedArchitectureId, deployTimeConfiguration,
+ // packageContentStream);
+ if (packageUploadDetails != null) {
+ resourceFactoryManager.createResource(user,
parentResource.getId(), getResourceTypeId(), null,
+ pluginConfiguration, packageName, getVersion(),
selectedArchitectureId,
+ deployTimeConfiguration, packageContentStream,
packageUploadDetails);
+ } else {
+ resourceFactoryManager.createResource(user,
parentResource.getId(), getResourceTypeId(), null,
+ pluginConfiguration, packageName, null,
selectedArchitectureId, deployTimeConfiguration,
+ packageContentStream);
+
+ }
+
+ } catch (NoResultException nre) {
+ //eat the exception. Some of the queries return no results if no
package yet exists which is fine.
+ } catch (Exception e) {
+ String errorMessages = ThrowableUtil.getAllMessages(e);
+ FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR,
+ "Failed to send create resource request to agent. Cause:
" + errorMessages);
+ log.error("Failed to create new child Resource of type
[" + getResourceType() + "].", e);
+ return OUTCOME_SUCCESS_OR_FAILURE;
+ }
+ } finally {
+ packageContentStream.close();
}
-
- } catch (NoResultException nre) {
- //eat the exception. Some of the queries return no results if no package
yet exists which is fine.
- } catch (Exception e) {
+ } catch (IOException e) {
String errorMessages = ThrowableUtil.getAllMessages(e);
FacesContextUtility.addMessage(FacesMessage.SEVERITY_ERROR,
- "Failed to send create resource request to agent. Cause: "
+ errorMessages);
- log.error("Failed to create new child Resource of type [" +
getResourceType() + "].", e);
+ "Failed to retrieve the input stream. Cause: " +
errorMessages);
return OUTCOME_SUCCESS_OR_FAILURE;
}
@@ -279,8 +281,7 @@ public class CreateNewPackageChildResourceUIBean {
resourceType = lookupResourceType();
}
ContentManagerLocal contentManager = LookupUtil.getContentManager();
- PackageType packageType =
contentManager.getResourceCreationPackageType(this.resourceType.getId());
- return packageType;
+ return contentManager.getResourceCreationPackageType(this.resourceType.getId());
}
protected ConfigurationDefinition lookupConfigurationDefinition() {
@@ -297,11 +298,10 @@ public class CreateNewPackageChildResourceUIBean {
if (configDef != null) {
deployTimeConfigurationTemplates = configDef.getDefaultTemplate();
}
- Configuration deployTimeConfiguration = (deployTimeConfigurationTemplates !=
null) ? deployTimeConfigurationTemplates
+
+ return (deployTimeConfigurationTemplates != null) ?
deployTimeConfigurationTemplates
.createConfiguration()
: new Configuration();
-
- return deployTimeConfiguration;
}
// Accessors --------------------------------------------
@@ -330,8 +330,7 @@ public class CreateNewPackageChildResourceUIBean {
}
}
- SelectItem[] items = selectItemsList.toArray(new
SelectItem[selectItemsList.size()]);
- return items;
+ return selectItemsList.toArray(new SelectItem[selectItemsList.size()]);
}
public CreateResourceHistory getRetryCreateItem() {
diff --git
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/util/ContextUtils.java
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/util/ContextUtils.java
index 994bf64..3363463 100644
---
a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/util/ContextUtils.java
+++
b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/util/ContextUtils.java
@@ -243,7 +243,11 @@ public class ContextUtils {
filename = context.getRealPath(filename);
FileOutputStream out = new FileOutputStream(filename);
- props.store(out, null);
+ try {
+ props.store(out, null);
+ } finally {
+ out.close();
+ }
}
public static boolean usingLDAPAuthentication(ServletContext context) throws
Exception {
diff --git
a/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
b/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
index 289b36f..bdda353 100644
--- a/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
+++ b/modules/helpers/bundleGen/src/main/java/org/rhq/helpers/bundleGen/BundleGen.java
@@ -22,7 +22,6 @@ import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
@@ -91,13 +90,14 @@ public class BundleGen {
try {
File outFile = new File(genPath,"generatedBundle.zip");
- FileOutputStream fos = new FileOutputStream(outFile);
- ZipOutputStream zos = new ZipOutputStream(fos);
-
- copyToOutputStream(zos,genPath,"deploy.xml");
- copyToOutputStream(zos,props.getContentDir(),props.getBundleFile());
- zos.flush();
- zos.close();
+ ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outFile));
+ try {
+ copyToOutputStream(zos,genPath,"deploy.xml");
+ copyToOutputStream(zos,props.getContentDir(),props.getBundleFile());
+ } finally {
+ // by definition this automatically flushes!
+ zos.close();
+ }
File targetFile = new File(bundleTargetDirectory + "/" +
"generatedBundle.zip");
boolean success = outFile.renameTo(targetFile);
@@ -125,10 +125,13 @@ public class BundleGen {
ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(new File(filedir , fileName));
- StreamUtil.copy(fis,zos,false);
- zos.flush();
- log.debug("Added ["+ fileName + "]");
- fis.close();
+ try {
+ StreamUtil.copy(fis,zos,false);
+ zos.flush();
+ log.debug("Added ["+ fileName + "]");
+ } finally {
+ fis.close();
+ }
}
/**
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
index 34d5a3e..6365be6 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
@@ -47,16 +47,20 @@ public class ApacheConfigWriter {
}
public void saveFile(String file,ApacheDirective dir) throws Exception{
-
File fl = new File(file);
- if (!fl.exists())
+ if (!fl.exists()) {
fl.createNewFile();
+ }
OutputStream str = new FileOutputStream(fl);
- for (ApacheDirective d : dir.getChildDirectives()){
- if (dir.getFile().equals(file)){
- writeToFile(str,dir,file);
+ try {
+ for (ApacheDirective d : dir.getChildDirectives()){
+ if (dir.getFile().equals(file)){
+ writeToFile(str,dir,file);
+ }
}
+ } finally {
+ str.close();
}
}
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JnpConfig.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JnpConfig.java
index c2c8f10..9e30732 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JnpConfig.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/util/JnpConfig.java
@@ -488,16 +488,20 @@ public class JnpConfig {
+ "jboss-system.jar");
if (systemJar.exists()) {
JarFile j = new JarFile(systemJar);
- JarEntry entry = j.getJarEntry("dtd/" + dtdName);
- if (entry == null) {
- entry = j.getJarEntry("org/jboss/metadata/" +
dtdName);
- }
-
- if (entry != null) {
- if (log.isDebugEnabled())
- log.debug("Found DTD locally: " +
entry.getName());
-
- return new InputSource(j.getInputStream(entry));
+ try {
+ JarEntry entry = j.getJarEntry("dtd/" + dtdName);
+ if (entry == null) {
+ entry = j.getJarEntry("org/jboss/metadata/" +
dtdName);
+ }
+
+ if (entry != null) {
+ if (log.isDebugEnabled())
+ log.debug("Found DTD locally: " +
entry.getName());
+
+ return new InputSource(j.getInputStream(entry));
+ }
+ } finally {
+ j.close();
}
}
}
diff --git
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 79a4fab..f9f902e 100644
---
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -61,8 +61,11 @@ public abstract class AbstractBaseDiscovery<T extends
ResourceComponent> impleme
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is = new FileInputStream(hostXmlFile);
- hostXml = builder.parse(is);
- is.close();
+ try {
+ hostXml = builder.parse(is);
+ } finally {
+ is.close();
+ }
} catch (Exception e) {
e.printStackTrace(); // TODO: Customise this generated block
}
@@ -127,8 +130,7 @@ public abstract class AbstractBaseDiscovery<T extends
ResourceComponent> impleme
hp.port = port;
String nIf = mgmtInterface.getAttribute("interface");
- String hostName = getInterface(nIf);
- hp.host = hostName;
+ hp.host = getInterface(nIf);
return hp;
}
}
@@ -174,8 +176,7 @@ public abstract class AbstractBaseDiscovery<T extends
ResourceComponent> impleme
if (nodeName.equals("any-ipv4-address"))
return "0.0.0.0";
- String x = ((Element)
nl.item(j)).getAttribute("value");
- return x;
+ return ((Element) nl.item(j)).getAttribute("value");
// TODO check for <any> and so on
}
@@ -195,8 +196,7 @@ public abstract class AbstractBaseDiscovery<T extends
ResourceComponent> impleme
if (hostXml==null)
throw new IllegalArgumentException("hostXml is null. You need to call
'readStandaloneOrHostXml' first.");
- String hostName = hostXml.getDocumentElement().getAttribute("name");
- return hostName;
+ return hostXml.getDocumentElement().getAttribute("name");
}
/**
diff --git
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JnpConfig.java
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JnpConfig.java
index 38c9f0c..4441bee 100644
--- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JnpConfig.java
+++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/JnpConfig.java
@@ -489,16 +489,20 @@ public class JnpConfig {
+ "jboss-system.jar");
if (systemJar.exists()) {
JarFile j = new JarFile(systemJar);
- JarEntry entry = j.getJarEntry("dtd/" + dtdName);
- if (entry == null) {
- entry = j.getJarEntry("org/jboss/metadata/" +
dtdName);
- }
-
- if (entry != null) {
- if (log.isDebugEnabled())
- log.debug("Found DTD locally: " +
entry.getName());
-
- return new InputSource(j.getInputStream(entry));
+ try {
+ JarEntry entry = j.getJarEntry("dtd/" + dtdName);
+ if (entry == null) {
+ entry = j.getJarEntry("org/jboss/metadata/" +
dtdName);
+ }
+
+ if (entry != null) {
+ if (log.isDebugEnabled())
+ log.debug("Found DTD locally: " +
entry.getName());
+
+ return new InputSource(j.getInputStream(entry));
+ }
+ } finally {
+ j.close();
}
}
}
commit 5cad7eabcfad901a4b1fc4673d8fa59ce5ad5de4
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Aug 9 18:34:37 2011 -0400
[BZ 726435][coverity 13112, 13113, 13276, 13277, 13041, 13025, 13005, 13012] Fix
Coverity identified RESOURCE_LEAK; close some IO streams.
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/perspective/PerspectiveServerPluginManager.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/perspective/PerspectiveServerPluginManager.java
index 88153a6..104e85d 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/perspective/PerspectiveServerPluginManager.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/perspective/PerspectiveServerPluginManager.java
@@ -100,11 +100,15 @@ public class PerspectiveServerPluginManager extends
ServerPluginManager {
String name = null;
try {
JarFile pluginJarFile = new JarFile(env.getPluginUrl().getFile());
- for (JarEntry entry : Collections.list(pluginJarFile.entries())) {
- name = entry.getName();
- if (name.toLowerCase().endsWith(".war")) {
- deployWar(env, entry.getName(),
pluginJarFile.getInputStream(entry));
+ try {
+ for (JarEntry entry : Collections.list(pluginJarFile.entries())) {
+ name = entry.getName();
+ if (name.toLowerCase().endsWith(".war")) {
+ deployWar(env, entry.getName(),
pluginJarFile.getInputStream(entry));
+ }
}
+ } finally {
+ pluginJarFile.close();
}
} catch (Exception e) {
Throwable t = (e instanceof MBeanException) ? e.getCause() : e;
@@ -225,11 +229,15 @@ public class PerspectiveServerPluginManager extends
ServerPluginManager {
String name = null;
try {
JarFile plugin = new JarFile(env.getPluginUrl().getFile());
- for (JarEntry entry : Collections.list(plugin.entries())) {
- name = entry.getName();
- if (name.toLowerCase().endsWith(".war")) {
- undeployWar(getDeployFile(env, entry.getName()));
+ try {
+ for (JarEntry entry : Collections.list(plugin.entries())) {
+ name = entry.getName();
+ if (name.toLowerCase().endsWith(".war")) {
+ undeployWar(getDeployFile(env, entry.getName()));
+ }
}
+ } finally {
+ plugin.close();
}
} catch (Exception e) {
this.log.error("Failed to deploy " +
env.getPluginKey().getPluginName() + "#" + name, e);
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKComponent.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKComponent.java
index 40d0f87..a4e1bcc 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKComponent.java
@@ -42,8 +42,6 @@ import org.rhq.plugins.apache.util.HttpdConfParser;
*/
public class ModJKComponent implements ResourceComponent<ApacheServerComponent> {
- private static final Log log = LogFactory.getLog(ModJKComponent.class);
-
private static final String OUTPUT_RESULT_PROP = "output";
public void start(ResourceContext<ApacheServerComponent>
parentResourceContext)
@@ -64,12 +62,12 @@ public class ModJKComponent implements
ResourceComponent<ApacheServerComponent>
* @param serverComponent The parents server component with the configuration
* @param params Params we got passed from the GUI
* @return The outcome of the operation
+ * @throws Exception see thrown exception for details; thrown exception summarizes
error
*/
public static OperationResult installModJk(ApacheServerComponent serverComponent,
Configuration params)
throws Exception {
StringBuilder builder = new StringBuilder();
- boolean errorSeen = false;
boolean needWorkersProps = false;
boolean needUriWorkers = false;
@@ -86,44 +84,48 @@ public class ModJKComponent implements
ResourceComponent<ApacheServerComponent>
cparser.parse(confPath);
// TODO back up original file
try {
- BufferedWriter writer = new BufferedWriter(new FileWriter(httpdConf, true));
-
- if (cparser.isModJkInstalled()) {
- builder.append("Mod_jk is already installed\n");
- if (cparser.getWorkerPropertiesFile() != null) {
- builder.append("Found a worker.properties file at
").append(cparser.getWorkerPropertiesFile());
- builder.append("\n");
- } else
+ BufferedWriter writer = null;
+ try {
+ writer = new BufferedWriter(new FileWriter(httpdConf, true));
+ if (cparser.isModJkInstalled()) {
+ builder.append("Mod_jk is already installed\n");
+ if (cparser.getWorkerPropertiesFile() != null) {
+ builder.append("Found a worker.properties file at
").append(cparser.getWorkerPropertiesFile());
+ builder.append("\n");
+ } else
+ needWorkersProps = true;
+
+ if (cparser.getUriWorkerLocation() != null) {
+ builder.append("Found a urimap file at
").append(cparser.getUriWorkerLocation());
+ } else
+ needUriWorkers = true;
+ } else {
+ builder.append("No mod_jk installed yet at
").append(confPath).append("\n");
+
+ writer.append("LoadModule jk_module modules/mod_jk.so"); //
TODO obtain modules location
+ writer.newLine();
+
+ builder.append(".. written a LoadModule line \n");
needWorkersProps = true;
-
- if (cparser.getUriWorkerLocation() != null) {
- builder.append("Found a urimap file at
").append(cparser.getUriWorkerLocation());
- } else
needUriWorkers = true;
- } else {
- builder.append("No mod_jk installed yet at
").append(confPath).append("\n");
-
- writer.append("LoadModule jk_module modules/mod_jk.so"); //
TODO obtain modules location
- writer.newLine();
-
- builder.append(".. written a LoadModule line \n");
- needWorkersProps = true;
- needUriWorkers = true;
+ }
+
+ if (needWorkersProps) {
+ writer.append("JkWorkersFile
").append("conf/workers.properties");
+ writer.newLine();
+ builder.append(".. installed worker.properties");
+ }
+ if (needUriWorkers) {
+ writer.append("JkMountFile
").append("conf/uriworkermap");
+ writer.newLine();
+ builder.append(".. installed uriworkermap");
+ }
+ } finally {
+ if (writer != null) {
+ // close automatically flushes!
+ writer.close();
+ }
}
-
- if (needWorkersProps) {
- writer.append("JkWorkersFile
").append("conf/workers.properties");
- writer.newLine();
- builder.append(".. installed worker.properties");
- }
- if (needUriWorkers) {
- writer.append("JkMountFile
").append("conf/uriworkermap");
- writer.newLine();
- builder.append(".. installed uriworkermap");
- }
- writer.flush();
- writer.close();
-
} catch (IOException e) {
builder.append("Error when installing mod_jk: \n");
builder.append(e.fillInStackTrace());
diff --git
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
index a3a715c..ba52e77 100644
---
a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
+++
b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
@@ -115,23 +115,28 @@ public class AugeasConfigurationApache extends
PluginDescriptorBasedAugeasConfig
if (fl.exists() && fl.isFile()) {
foundIncludes.add(fl.getAbsolutePath());
- FileInputStream fstream = new FileInputStream(fl);
- BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
- String strLine;
- while ((strLine = br.readLine()) != null) {
- Matcher m = includePattern.matcher(strLine);
- if (m.matches()) {
- String glob = m.group(1);
-
- module.addIncludedGlob(glob);
- loadIncludes(glob, foundIncludes);
+ BufferedReader br = null;
+ try {
+ br = new BufferedReader(new InputStreamReader(new
FileInputStream(fl)));
+ String strLine;
+ while ((strLine = br.readLine()) != null) {
+ Matcher m = includePattern.matcher(strLine);
+ if (m.matches()) {
+ String glob = m.group(1);
+
+ module.addIncludedGlob(glob);
+ loadIncludes(glob, foundIncludes);
+ }
+ Matcher serverRootMatcher = serverRootPattern.matcher(strLine);
+ if (serverRootMatcher.matches()) {
+ serverRootPath = serverRootMatcher.group(1);
+ }
}
- Matcher serverRootMatcher = serverRootPattern.matcher(strLine);
- if (serverRootMatcher.matches()) {
- serverRootPath = serverRootMatcher.group(1);
+ } finally {
+ if (br != null) {
+ br.close();
}
}
- br.close();
}
}
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
index 3bf3b09..a08e977 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/ApplicationServerDiscoveryComponent.java
@@ -146,9 +146,7 @@ public class ApplicationServerDiscoveryComponent implements
ResourceDiscoveryCom
} catch (IOException e) {
throw new InvalidPluginConfigurationException(e);
}
- DiscoveredResourceDetails resourceDetails =
createResourceDetails(discoveryContext, pluginConfig, processInfo,
- installInfo);
- return resourceDetails;
+ return createResourceDetails(discoveryContext, pluginConfig, processInfo,
installInfo);
}
@SuppressWarnings("unchecked")
@@ -413,8 +411,9 @@ public class ApplicationServerDiscoveryComponent implements
ResourceDiscoveryCom
private String getJnpURL(JBossInstanceInfo cmdLine, File installHome, File configDir)
{
File jnpServiceUrlFile = new File(configDir, "data/jnp-service.url");
if (jnpServiceUrlFile.exists() && jnpServiceUrlFile.canRead()) {
+ BufferedReader br = null;
try {
- BufferedReader br = new BufferedReader(new
FileReader(jnpServiceUrlFile));
+ br = new BufferedReader(new FileReader(jnpServiceUrlFile));
String jnpUrl = br.readLine();
if (jnpUrl != null) {
if (log.isDebugEnabled()) {
@@ -424,6 +423,14 @@ public class ApplicationServerDiscoveryComponent implements
ResourceDiscoveryCom
}
} catch (IOException ioe) {
// Nothing to do
+ } finally {
+ if (br != null) {
+ try {
+ br.close();
+ } catch (IOException e) {
+ // nada
+ }
+ }
}
}
diff --git
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/deploy/ManagedComponentDeployer.java
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/deploy/ManagedComponentDeployer.java
index 4315155..de6a174 100644
---
a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/deploy/ManagedComponentDeployer.java
+++
b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/deploy/ManagedComponentDeployer.java
@@ -146,8 +146,11 @@ public class ManagedComponentDeployer implements Deployer {
Manifest manifest;
if (manifestFile.exists()) {
FileInputStream inputStream = new FileInputStream(manifestFile);
- manifest = new Manifest(inputStream);
- inputStream.close();
+ try {
+ manifest = new Manifest(inputStream);
+ } finally {
+ inputStream.close();
+ }
} else {
File metaInf = new File(deploymentFile, "META-INF");
if (!metaInf.exists())
@@ -160,8 +163,11 @@ public class ManagedComponentDeployer implements Deployer {
Attributes attribs = manifest.getMainAttributes();
attribs.putValue("RHQ-Sha256", shaString);
FileOutputStream outputStream = new FileOutputStream(manifestFile);
- manifest.write(outputStream);
- outputStream.close();
+ try {
+ manifest.write(outputStream);
+ } finally {
+ outputStream.close();
+ }
} else {
LOG.error("Exploded deployment '" + deploymentFile
+ "' does not exist or is not a directory - unable
to add RHQ versioning metadata to META-INF/MANIFEST.MF.");
diff --git
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 1b05ae6..9d4c2f2 100644
---
a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++
b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -77,7 +77,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery
implements Resou
String serverName;
String psName = psr.getProcessScan().getName();
String description = discoveryContext.getResourceType().getDescription();
- String version = null;
+ String version;
//retrieve specific boot log file. Override for Standalone as server.log is
more appropriate
String bootLogFile = getLogFileFromCommandLine(commandLine);
@@ -232,9 +232,12 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery
implements Resou
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream is = new FileInputStream(hostXmlFile);
- Document document = builder.parse(is); // TODO keep this around
- hostName = document.getDocumentElement().getAttribute("name");
- is.close();
+ try {
+ Document document = builder.parse(is); // TODO keep this around
+ hostName = document.getDocumentElement().getAttribute("name");
+ } finally {
+ is.close();
+ }
} catch (Exception e) {
e.printStackTrace(); // TODO: Customise this generated block
}
commit 7877a3e5be5f8f0dfa657587a884b52e70ea1181
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Aug 9 17:33:24 2011 -0400
[BZ 726435][coverity 13283] Fix Coverity identified RESOURCE_LEAK; close some IO
streams.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
index 6e1f305..323a15c 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/server/EntitySerializer.java
@@ -252,14 +252,26 @@ public class EntitySerializer {
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir, "entitySerializerTest.txt");
- ObjectOutput output = new ObjectOutputStream(new FileOutputStream(tempFile));
- writeExternalRemote(writeResource, output);
- output.close();
+ ObjectOutput output = null;
+ try {
+ output = new ObjectOutputStream(new FileOutputStream(tempFile));
+ writeExternalRemote(writeResource, output);
+ } finally {
+ if (output != null) {
+ output.close();
+ }
+ }
Resource readResource = new Resource();
- ObjectInput input = new ObjectInputStream(new FileInputStream(tempFile));
- readExternalRemote(readResource, input);
- input.close();
+ ObjectInput input = null;
+ try {
+ input = new ObjectInputStream(new FileInputStream(tempFile));
+ readExternalRemote(readResource, input);
+ } finally {
+ if (input != null) {
+ input.close();
+ }
+ }
// quick verification
System.out.println("AFTER");
commit e2f2f54d036091eeda96f18151c9fdc82a3ed728
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Aug 9 11:50:19 2011 -0400
[BZ 726434] Fix io stream resource leak; also fixed a javadoc issue that caused
code-red.
diff --git
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/FileContentDelegate.java
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/FileContentDelegate.java
index 9628e25..6c4e83b 100644
---
a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/FileContentDelegate.java
+++
b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/util/FileContentDelegate.java
@@ -105,16 +105,22 @@ public class FileContentDelegate {
Manifest manifest;
if (manifestFile.exists()) {
FileInputStream inputStream = new FileInputStream(manifestFile);
- manifest = new Manifest(inputStream);
- inputStream.close();
+ try {
+ manifest = new Manifest(inputStream);
+ } finally {
+ inputStream.close();
+ }
} else {
manifest = new Manifest();
}
Attributes attribs = manifest.getMainAttributes();
attribs.putValue("RHQ-Sha256", shaString);
FileOutputStream outputStream = new FileOutputStream(manifestFile);
- manifest.write(outputStream);
- outputStream.close();
+ try {
+ manifest.write(outputStream);
+ } finally {
+ outputStream.close();
+ }
} else {
FileUtil.writeFile(content, contentFile);
}
diff --git
a/modules/plugins/tomcat/src/main/java/org/jboss/on/plugins/tomcat/helper/FileContentDelegate.java
b/modules/plugins/tomcat/src/main/java/org/jboss/on/plugins/tomcat/helper/FileContentDelegate.java
index 2087d5f..1d2b6b2 100644
---
a/modules/plugins/tomcat/src/main/java/org/jboss/on/plugins/tomcat/helper/FileContentDelegate.java
+++
b/modules/plugins/tomcat/src/main/java/org/jboss/on/plugins/tomcat/helper/FileContentDelegate.java
@@ -71,7 +71,7 @@ public class FileContentDelegate {
* Creates a new package described by the specified details. The destination of the
content in the provided input
* stream will be determined by the package name.
*
- * @param details describes the package being created
+ * @param contentFile the file to write the content to
* @param content content to be written for the package. NOTE this Stream will be
closed by this method.
* @param unzip if <code>true</code>, the content stream will be
treated like a ZIP file and be unzipped as
* it is written, using the package name as the base directory; if
<code>false</code> the
commit b65f00bca15817c5249c0c1e7e9da0a2bdd67331
Merge: 78ce519 cdd1964
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Aug 9 11:47:01 2011 -0400
Merge branch 'master' into code-smell
* master: (195 commits)
Also pick the profile via dependent value.
Add dependent values for create child operations.
Re rpcTimeout, trap numeric exceptions and fallback if a user does not provide an
integer value.
Add rpc timeout capability so users can specify an override timeout via query string
parameters. The new query string parameter is rpcTimeout, the type an integer, and the
units are expressed in seconds.
[BZ 722600,726524] Update db-upgrade to add indexes for
RHQ_ALERT_CONDITION_LOG.CONDITION_ID and RHQ_MEASUREMENT_SCHED.RESOURCE_ID to optimize
queries.
[BZ 726524] Consider adding an index for the RHQ_ALERT_CONDITION_LOG.CONDITION_ID to
optimize queries.
[BZ 722600] Add index to RHQ_MEASUREMENT_SCHED.RESOURCE_ID column as recommended by
Oracle EM to improve performance.
The exported system settings are now directly backed by the actual system settings
properties so that no changes need to be made to the export classes when a new system
setting is added. The system settings importer now accepts configuration.
more work to make the integration-tests profile actually build.
A number of test apache upgrade test cases was mis-configured.
Test config reading / updating with the socket binding group and two bindings.
adding the common module to integration-tests so that the drift and as plugins
build.
make the specification of the httpd binary needed for the apache integration tests
slightly more flexible.
Remove some accidentally checked in files I noticed in the source tree.
Remove some accidentally checked in files I noticed in the source tree.
Taking out code that results in compile errors...
BZ720674 - adding a ResourceUpgradeFacet on the Agent discovery component to deal
with the RK format change mistakenly introduced in RHQ3 codebase.
Fix updating ListsOfMaps and disable the list of includes for now (AS7-1467)
Correcting the schema version in the pom file (after a bad merge).
Reverting more code wrongly updated during merge ...
...
commit 81b1e5c4afd8d2002bdcd668d2fcbc13b1427262
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Aug 8 16:31:54 2011 -0400
tweak the metric collection intervals in the configurable-5 scenario to
approximate 100 metrics per minute per platform (30k metrics per minute
with 300 platforms) when the scenario is configured using:
-Drhq.perftest.scenario=configurable-5
-Drhq.perftest.server-d-count=2
-Drhq.perftest.service-d-metrics-count=100
diff --git
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
index 1f5b2e6..fdfb98e 100644
---
a/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
+++
b/modules/plugins/perftest/src/main/java/org/rhq/plugins/perftest/PerfTestComponent.java
@@ -32,7 +32,6 @@ import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
import org.rhq.core.domain.event.Event;
import org.rhq.core.domain.event.EventSeverity;
import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.DataType;
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.measurement.MeasurementReport;
@@ -62,7 +61,7 @@ import java.util.Set;
import java.util.Arrays;
/**
- * RHQ resource component for handling resources defined in the performance test
scenario.
+ * RHQ resource component for handling resources defined in a performance test scenario.
*
* @author Jason Dobies
*/
diff --git a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
index aa06d15..6642315 100644
--- a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml
@@ -306,17 +306,24 @@
<server name="server-c" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Test Server
C"/>
- <!-- used to perftest measurement collection -->
+ <!-- used to perftest measurement collection w/ the following schedules:
+ 5 metrics every 10 mins == 0.5 metrics per minute, per service-d-metrics
Resource
+ 3 traits every 1 hour == 0.05 traits per minute, per service-d-metrics
Resource
+ -->
<server name="server-d" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Test Server
D">
<service name="service-d-metrics" class="PerfTestComponent"
discovery="PerfTestDiscoveryComponent" description="Nested Service D With
Metrics">
- <metric property="metric000" defaultOn="true"
displayType="summary" defaultInterval="200000"/>
- <metric property="metric001" defaultOn="true"
displayType="summary" defaultInterval="300000"/>
- <metric property="metric002" defaultOn="true"
displayType="summary" defaultInterval="400000"/>
- <metric property="metric003" defaultOn="true"
displayType="summary" defaultInterval="500000"/>
- <metric property="metric004" defaultOn="true"
displayType="summary" defaultInterval="600000"/>
- <metric property="trait001" defaultOn="true"
dataType="trait" displayType="summary"
defaultInterval="2000000"/>
- <metric property="trait002" defaultOn="true"
dataType="trait" displayType="summary"
defaultInterval="3000000"/>
+ <metric property="metric000" defaultOn="true"
displayType="summary" defaultInterval="570000"/>
+ <metric property="metric001" defaultOn="true"
displayType="summary" defaultInterval="570000"/>
+ <metric property="metric002" defaultOn="true"
displayType="summary" defaultInterval="600000"/>
+ <metric property="metric003" defaultOn="true"
displayType="summary" defaultInterval="630000"/>
+ <metric property="metric004" defaultOn="true"
displayType="summary" defaultInterval="630000"/>
+
+ <metric property="trait000" defaultOn="true"
dataType="trait" displayType="summary"
defaultInterval="3570000"/>
+ <metric property="trait001" defaultOn="true"
dataType="trait" displayType="summary"
defaultInterval="3600000"/>
+ <metric property="trait002" defaultOn="true"
dataType="trait" displayType="summary"
defaultInterval="3630000"/>
+
<metric displayName="CallTime" property="calltime"
defaultOn="false" dataType="calltime"
defaultInterval="2400000" units="milliseconds"/>
+
<event name="PerfTestEventType" description="a test event
type"/>
</service>
</server>
diff --git a/modules/plugins/perftest/src/main/resources/configurable-5.xml
b/modules/plugins/perftest/src/main/resources/configurable-5.xml
index 769fed9..5a9e720 100644
--- a/modules/plugins/perftest/src/main/resources/configurable-5.xml
+++ b/modules/plugins/perftest/src/main/resources/configurable-5.xml
@@ -4,18 +4,18 @@
xmlns="urn:xmlns:jboss.org:rhq-perftest">
<!--
- This scenario will create one server with a service that has 5 summary
measurements in them.
- To create 10 servers, each with 170 services, the following should be passed to
the agent:
+ This scenario will create n servers each with m services each defining 5 numeric
metrics and 3 traits.
+ To create 2 servers per platform, each with 100 services, the following should be
passed to the Agent:
- -Drhq.perftest.scenario=configurable-5 -Drhq.perftest.server-d-count=10
-Drhq.perftest.service-d-metrics-count=170
+ -Drhq.perftest.scenario=configurable-5 -Drhq.perftest.server-d-count=2
-Drhq.perftest.service-d-metrics-count=100
- This collects, on average, 170 measurements per minute (assuming summary
measurement collection interval is 5 mins)
+ This results in 200 service-d-metrics Resources per platform, which collectively
collect on average 100 numeric
+ metrics per minute and 10 traits per minute, assuming rhq-plugin.xml configures
schedules of 0.5 numeric metrics
+ per minute and 0.05 traits per minute, per Resource.
-->
-
<resource type="server-d">
<simpleResourceGenerator property="rhq.perftest.server-d-count"/>
- <simpleNumericMeasurementGenerator/>
</resource>
<resource type="service-d-metrics">
commit f80da2681e44c985650bc7cdad86e036a2092a20
Merge: f69f395 6328219
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Mon Aug 8 15:58:27 2011 -0400
Merge branch 'master' into feature/performance
* master:
[BZ 726524] Consider adding an index for the RHQ_ALERT_CONDITION_LOG.CONDITION_ID to
optimize queries.
[BZ 722600] Add index to RHQ_MEASUREMENT_SCHED.RESOURCE_ID column as recommended by
Oracle EM to improve performance.
commit f69f3956a61cc387f7e6e9c35d5d2eca78962358
Merge: 234156f 26461c2
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Mon Aug 8 13:32:04 2011 -0400
Merge branch 'master' into feature/performance
* master:
The exported system settings are now directly backed by the actual system settings
properties so that no changes need to be made to the export classes when a new system
setting is added. The system settings importer now accepts configuration.
Test config reading / updating with the socket binding group and two bindings.
Fix updating ListsOfMaps and disable the list of includes for now (AS7-1467)
Switch over to use of Address and add a test to simulate composite read-attribute
operations for batching.
Do some cleanup and fix a bug where more subsystems were discovered than available.
Catch the case where AS7 claims success at returning an attribute but in fact
returns null.
Get rid of the usage of List<PROPERTY_VALUE> and use Address uniformly. Also
remove some unused classes.
Better display names for host & domain config.
commit 234156f4ee7cca737d245ad8d1fc11f2d3e35873
Merge: b28a689 1dcabba
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Mon Aug 8 10:29:06 2011 -0400
Merge branch 'master' into feature/performance
* master: (249 commits)
more work to make the integration-tests profile actually build.
A number of test apache upgrade test cases was mis-configured.
adding the common module to integration-tests so that the drift and as plugins
build.
make the specification of the httpd binary needed for the apache integration tests
slightly more flexible.
Remove some accidentally checked in files I noticed in the source tree.
Remove some accidentally checked in files I noticed in the source tree.
Taking out code that results in compile errors...
BZ720674 - adding a ResourceUpgradeFacet on the Agent discovery component to deal
with the RK format change mistakenly introduced in RHQ3 codebase.
Correcting the schema version in the pom file (after a bad merge).
Reverting more code wrongly updated during merge ...
Removing junk characteres introduced at merge time.
Throw an exception if trying to use dbreset with anything else other than Oracle and
Postgres.
Forgot to replace three properties with the params after refactoring dbreset.
DB installation test now uses dbreset to propertly reset the database (even for
Oracle configurations).
Make dbreset configurable to it can be used/consumed by other modules.
Removing extra character inserted inadvertently.
Correct the class file name.
Adding driver class to the property list.
Move conditional properties to maven profiles. This reduces code duplication and
makes the pom smaller and more manageable.
Complete format of the pom file to make it easier to read.
...
commit b28a689660f5f1a13ac8b50dfea5aa8dace33cdb
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Aug 4 17:00:22 2011 -0400
add more detailed logging of SQLExceptions in a couple places
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/jdbc/JDBCUtil.java
b/modules/core/util/src/main/java/org/rhq/core/util/jdbc/JDBCUtil.java
index ca36c96..cad259c 100644
--- a/modules/core/util/src/main/java/org/rhq/core/util/jdbc/JDBCUtil.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/jdbc/JDBCUtil.java
@@ -227,4 +227,17 @@ public class JDBCUtil {
}
}
}
-}
\ No newline at end of file
+
+ public static String convertSQLExceptionToString(SQLException e) {
+ StringBuilder result = new StringBuilder(e.toString());
+ if (e.getNextException() != null) {
+ result.append(" - causes:");
+ SQLException cause = e;
+ while ((cause = cause.getNextException()) != null) {
+ result.append("\n\t").append(e);
+ }
+ }
+ return result.toString();
+ }
+
+}
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
index 98110ac..701876b 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java
@@ -21,6 +21,7 @@ package org.rhq.enterprise.server.measurement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
+import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -522,10 +523,20 @@ public class MeasurementScheduleManagerBean implements
MeasurementScheduleManage
}
}
}
-
} catch (Exception e) {
- log.error("Error updating measurement definitions: ", e);
- throw new MeasurementException("Error updating measurement definitions:
" + e.getMessage());
+ String errorMessage = "Error updating measurement definitions";
+ SQLException sqle = null;
+ if (e instanceof SQLException) {
+ sqle = (SQLException) e;
+ } else if (e.getCause() instanceof SQLException) {
+ sqle = (SQLException) e.getCause();
+ }
+ if (sqle != null) {
+ String s = JDBCUtil.convertSQLExceptionToString((SQLException) e);
+ errorMessage += ": " + s;
+ }
+ log.error(errorMessage, e);
+ throw new MeasurementException("Error updating measurement definitions:
" + e);
} finally {
JDBCUtil.safeClose(defUpdateStmt);
JDBCUtil.safeClose(schedUpdateStmt);
diff --git
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
index 45c7504..e8e90b2 100644
---
a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
+++
b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceAvailabilityManagerBean.java
@@ -166,6 +166,13 @@ public class ResourceAvailabilityManagerBean implements
ResourceAvailabilityMana
return result;
} catch (NoResultException nre) {
return null;
+ } catch (RuntimeException re) {
+ Throwable cause = re.getCause();
+ if (cause instanceof SQLException) {
+ log.error("Failed to get latest avail for Resource [" +
resourceId + "]: "
+ + JDBCUtil.convertSQLExceptionToString((SQLException)cause));
+ }
+ throw re;
}
}
commit 78ce51980e1fbb6ece062825c813722b46e4952c
Merge: fbc31a7 ec88d4b
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Mon Aug 1 08:42:38 2011 +0200
Merge branch 'master' into code-smell
commit fbc31a7aae1ffc7949789473bfe7a72c5777d862
Merge: b38642e c4a82bc
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Mon Aug 1 08:38:51 2011 +0200
Merge branch 'master' into code-smell
commit ac43c7cb5873e56349f0700cdf9407c11d61ebb3
Merge: 5b82b1e b35ba5b
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Thu Jul 28 18:25:26 2011 -0400
Merge branch 'master' into feature/performance
* master: (147 commits)
BZ 726378 - management port settings on AS7 were not honored.
Initial support for messaging (JMS)
Add more properties for JBossWeb. Unfortunately they are read-only in AS7
Get rid of the explicit version number and let maven do the magic.
Log the property being null and don't pollute stdout.
Provide more connection properties for standalone servers as well as the version.
Add start and restart operations for standalone servers.
BZ 725417 - if the 'default' attribute is missing on a required property,
throw a descriptive exception instead of a NPE.
Extract the deploy-to-server-magic from createChild() and add tests to use this
extracted code to deploy to domain and server-group.
BZ 726378 - management port settings on AS7 were not honored.
Initial support for messaging (JMS)
Move mod_cluster integration tests in the correct integration folder.
Make the error message useful by adding the name of the attribute that failed to
set.
Final touches for mod_cluster plugin configuration. Updated a couple of the plugin
settings to match mod_cluster specifications.
Fully enable jvmRoute for context identification and discovery. Also, addressed all
the compiler warnings in the plugin code.
Adding jvmRoute in the mix for webapp context identification. jvmRoute uniquely
identifies nodes in a cluster and will be used to decide which contexts run on the node
monitored by RHQ.
Added support for stopContext operation for webapp contexts. Updated service
description. Added more complex integration tests for webapp context service.
Returning back to simple availability methods (no availability collectors) after
getting clarifications from the mod_cluster team with regards to JMX attributes and node
refresh operations.
Implemented getAvailability using the async collector because there is no guarantee
when node full refreshes its configuration. The configuration is read from the httpd proxy
and parsed; so network latency and number of loaded contexts influence the reload time.
A couple of small configuration and test corrections.
The configuration needs to be refreshed before computing availability on all the
contexts. Attempt to correctly invoke the operation.
...
commit 5b82b1e38bc6df304ae5eb11dfa87a13091c20d5
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Thu Jul 28 18:22:40 2011 -0400
[BZ 726524] Consider adding an index for the RHQ_ALERT_CONDITION_LOG.CONDITION_ID to
optimize queries.
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml
b/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml
index 100296c..6c5714d 100644
--- a/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml
+++ b/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml
@@ -112,6 +112,9 @@
<index name="RHQ_ALERT_COND_LOG_IDX_ALERT">
<field ref="ALERT_ID"/>
</index>
+ <index name="RHQ_ALERT_COND_LOG_COND_IDX">
+ <field ref="CONDITION_ID"/>
+ </index>
</table>
<table name="RHQ_ALERT_NOTIFICATION"
tablespace="@@@LARGE_TABLESPACE_FOR_DATA@@@"
commit 110a606c698a3aa2540f54c6c5de5c3988e2d749
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Thu Jul 28 18:07:55 2011 -0400
Hide Eclipse plugin .metadata directory from Git.
diff --git a/.gitignore b/.gitignore
index e4ae4cd..2b3fb38 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,7 +15,8 @@ logs
*.ipr
*.iws
.idea
-.idea/*
+.idea/
+.metadata/
dev-container
dev-agent
antlr-generated/
commit 5697849505fb1a792f3a45935b82aeb6ea3f0234
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Thu Jul 28 18:06:59 2011 -0400
[BZ 722600] Add index to RHQ_MEASUREMENT_SCHED.RESOURCE_ID column as recommended by
Oracle EM to improve performance.
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml
b/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml
index 903f334..bb57378 100644
--- a/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml
+++ b/modules/core/dbutils/src/main/scripts/dbsetup/measurement-schema.xml
@@ -53,6 +53,9 @@
<field ref="RESOURCE_ID"/>
<field ref="DEFINITION"/>
</index>
+ <index name="RHQ_MEAS_SCHED_RESID_IDX">
+ <field ref="RESOURCE_ID"/>
+ </index>
</table>
commit 41810f98e0cba59699c9f47ec0e716a5ab7a11b7
Merge: 585895f e7947ed
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Wed Jul 20 14:09:03 2011 -0400
Merge branch 'master' into rbuck/rpctimeout
* master:
Add gitignore for gwt-tmp directory.
Move the sources that need resource filtering into a separate source directory so
that we don't have to redefine the source directory of the whole project. This
provides a clearer separation between "ordinary" source and the source files
that need special attention during the build. We also no longer have to recompile all 600+
files each time even if none of them changed (only the filtered ones are recompiled each
time).
commit 585895f5e320423ae21caec07546bf3b70fee4ee
Author: Robert Buck <buck.robert.j(a)gmail.com>
Date: Wed Jul 20 14:05:43 2011 -0400
Re rpcTimeout, trap numeric exceptions and fallback if a user does not provide an
integer value.
diff --git a/.gitignore b/.gitignore
index 92d8d5e..e4ae4cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,7 @@ logs
dev-container
dev-agent
antlr-generated/
+gwt-tmp/
*.tokens
modules/enterprise/gui/portal-war/build/classes/*
modules/enterprise/gui/coregui/build/classes/*
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
index 28ce749..65d9a67 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
@@ -125,7 +125,11 @@ public class CoreGUI implements EntryPoint,
ValueChangeHandler<String>, Event.Na
rpcTimeout = -1;
String rpcTimeoutParam = Location.getParameter("rpcTimeout");
if (rpcTimeoutParam != null) {
- rpcTimeout = Integer.parseInt(rpcTimeoutParam) * 1000;
+ try {
+ rpcTimeout = Integer.parseInt(rpcTimeoutParam) * 1000;
+ } catch (NumberFormatException ignored) {
+ // nada
+ }
}
coreGUI = this;
commit 6104594fa7d8a03fb12fe3489ed58b7fa12fa4dc
Author: Robert Buck <rbuck(a)redhat.com>
Date: Tue Jul 19 14:49:15 2011 -0400
Add rpc timeout capability so users can specify an override timeout via query string
parameters. The new query string parameter is rpcTimeout, the type an integer, and the
units are expressed in seconds.
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
index 85f5e92..28ce749 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java
@@ -108,6 +108,7 @@ public class CoreGUI implements EntryPoint,
ValueChangeHandler<String>, Event.Na
private RootCanvas rootCanvas;
private MenuBarView menuBarView;
private Footer footer;
+ private int rpcTimeout;
public void onModuleLoad() {
String hostPageBaseURL = GWT.getHostPageBaseURL();
@@ -121,6 +122,12 @@ public class CoreGUI implements EntryPoint,
ValueChangeHandler<String>, Event.Na
SeleniumUtility.setUseDefaultIds(false);
}
+ rpcTimeout = -1;
+ String rpcTimeoutParam = Location.getParameter("rpcTimeout");
+ if (rpcTimeoutParam != null) {
+ rpcTimeout = Integer.parseInt(rpcTimeoutParam) * 1000;
+ }
+
coreGUI = this;
Event.addNativePreviewHandler(this);
@@ -151,6 +158,10 @@ public class CoreGUI implements EntryPoint,
ValueChangeHandler<String>, Event.Na
loadingPanel.removeFromParent();
}
+ public int getRpcTimeout() {
+ return rpcTimeout;
+ }
+
public void onPreviewNativeEvent(Event.NativePreviewEvent event) {
if (SC.isIE() && event.getTypeInt() == Event.ONCLICK) {
NativeEvent nativeEvent = event.getNativeEvent();
diff --git
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java
index 65af432..e6cdef4 100644
---
a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java
+++
b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java
@@ -216,6 +216,11 @@ public class GWTServiceLookup {
this.timeout = (timeout <= 0) ? DEFAULT_RPC_TIMEOUT : timeout;
+ int rpcTimeout = CoreGUI.get().getRpcTimeout();
+ if (rpcTimeout > -1) {
+ this.timeout = rpcTimeout;
+ }
+
if (CoreGUI.isDebugMode()) {
// debug mode is slow, so give requests more time to complete otherwise
you'll get
// weird exceptions whose messages are extremely unhelpful in finding
root cause