.classpath | 4 etc/cli-scripts/drift.js | 122 ++- etc/eclipse-tools/maven/RHQ | 4 etc/samples/custom-serverplugin/pom.xml | 9 etc/samples/custom-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml | 4 etc/samples/simplereport-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml | 4 modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java | 68 + modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java | 36 modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java | 91 +- modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java | 43 - modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java | 27 modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java | 76 - modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java | 105 -- modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java | 48 - modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/PluginMetadataParserTest.java | 18 modules/core/dbutils/pom.xml | 2 modules/core/dbutils/src/main/scripts/dbsetup/authz-data.xml | 18 modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml | 4 modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 10 modules/core/domain/src/main/java/org/rhq/core/domain/common/EntityContext.java | 34 modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java | 108 +- modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java | 136 +++ modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationDefinition.java | 140 ++- modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java | 59 + modules/core/domain/src/main/java/org/rhq/core/domain/drift/Filter.java | 85 ++ modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java | 9 modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java | 27 modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java | 6 modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceTypeFacet.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java | 33 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourcePermission.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/MetricTemplate.java | 47 - modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java | 196 ++++ modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainerConfiguration.java | 49 + modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DirectoryAnalyzer.java | 115 -- modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftClient.java | 9 modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionException.java | 39 modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetector.java | 215 ++--- modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftFilesSender.java | 12 modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftManager.java | 85 +- modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java | 153 +++ modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueue.java | 38 modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/ScheduleQueueImpl.java | 38 modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java | 34 modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DirectoryAnalyzerTest.java | 121 -- modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java | 234 ++--- modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java | 21 modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java | 264 ++++++ modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java | 14 modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java | 224 +++++ modules/core/plugin-container/src/test/xml/rhq-plugin-jmx-server-test.xml | 2 modules/core/util/pom.xml | 14 modules/core/util/src/main/java/org/rhq/core/util/file/FileUtil.java | 125 +++ modules/core/util/src/main/java/org/rhq/core/util/file/FileVisitor.java | 37 modules/core/util/src/main/java/org/rhq/core/util/file/PathFilter.java | 40 modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java | 170 ++++ modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfiguration.java | 9 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfigurationConstants.java | 20 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentSetupInstructions.java | 19 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/SetupPromptCommand.java | 14 modules/enterprise/agent/src/main/resources/agent-configuration.xml | 25 modules/enterprise/gui/coregui/pom.xml | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/CoreGUI.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java | 102 -- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java | 48 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LinkManager.java | 26 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java | 67 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java | 32 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java | 73 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentOptionsStep.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleStep.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleVersionStep.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSelectedEvent.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java | 48 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection2.java | 367 --------- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tagging/TagEditorView.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/view/AbstractSectionedLeftNavigationView.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/WizardView.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java | 312 +++---- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletFactory.java | 345 +++----- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletViewFactory.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupAlertsPortlet.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupBundleDeploymentsPortlet.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java | 67 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupEventsPortlet.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupMetricsPortlet.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOobsPortlet.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupPkgHistoryPortlet.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/groups/graph/ResourceGroupGraphPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/ResourceGraphPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/RecentDriftsPortlet.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationHistoryPortlet.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationSchedulePortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceAlertsPortlet.java | 18 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceBundleDeploymentsPortlet.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java | 76 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceEventsPortlet.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceMetricsPortlet.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOobsPortlet.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOperationsPortlet.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java | 7 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java | 145 ++- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationEditView.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftConfigurationView.java | 76 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java | 45 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDetailsView.java | 208 ++++- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftHistoryView.java | 115 -- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java | 42 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java | 56 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDataSource.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java | 151 ++- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java | 35 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupContextMenu.java | 41 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java | 83 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java | 11 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/HistoryGroupResourceConfigurationSettings.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/GroupPluginConfigurationEditView.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/ActivityView.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceCompositeSearchView.java | 33 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java | 38 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ChildHistoryView.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java | 80 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java | 50 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java | 51 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceAgentView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView.java | 10 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/TimelineView.java | 66 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/AbstractResourceFactoryWizard.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java | 87 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java | 17 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryInfoStep.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java | 212 ----- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ResourceInstallReport.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java | 101 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenterView.java | 9 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java | 101 +- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/TrackingRequestCallback.java | 42 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java | 69 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java | 9 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml | 8 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties | 35 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties | 31 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_ja.properties | 27 modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_pt.properties | 208 ++--- modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_zh.properties | 26 modules/enterprise/gui/coregui/src/main/webapp/css/search.css | 119 +- modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_closed.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_opened.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_failed_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_success_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_failed_16.png |binary modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_success_16.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_failed.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_success.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_failed.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_success.png |binary modules/enterprise/gui/portal-war/src/main/webapp/images/icons/Drift_16.png |binary modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventAlertJSON.jsp | 1 modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventContentJSON.jsp | 9 modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp | 4 modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventDriftJSON.jsp | 59 + modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventInventoryJSON.jsp | 52 + modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp | 356 ++++---- modules/enterprise/server/container/src/main/resources/jbossas/server/default/conf/jboss-log4j.xml | 16 modules/enterprise/server/ear/pom.xml | 7 modules/enterprise/server/jar/pom.xml | 6 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/RHQConstants.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java | 202 ++-- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/util/ConfigurationMaskingUtility.java | 17 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java | 224 +++-- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java | 72 - modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerRemote.java | 31 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java | 101 +- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java | 19 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerBean.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/measurement/MeasurementScheduleManagerLocal.java | 14 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java | 57 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java | 20 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GlobalActivationContext.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GroupActivationContext.java | 5 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/ResourceActivationContext.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java | 28 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java | 20 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/search/SavedSearchManagerBean.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/DefaultImportConfigurationDescriptor.java | 43 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java | 222 ++++- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java | 28 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/Synchronizer.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/Importer.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java | 185 ++-- modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java | 46 - modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/util/IndentingXMLStreamWriter.java | 393 +++++++++ modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/ConsistencyValidator.java | 9 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java | 22 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/MetricTemplateValidator.java | 121 ++ modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/SystemSettingsValidator.java | 4 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java | 8 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java | 76 + modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/resource/metadata/ResourceMetadataManagerBeanTest.java | 2 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java | 219 +++++ modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyExporter.java | 38 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyImporter.java | 60 - modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummySynchronizer.java | 60 - modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java | 215 +++++ modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java | 193 +--- modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java | 380 +++++++++ modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateValidatorTest.java | 161 +++ modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java | 152 --- modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsImporterTest.java | 120 ++ modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java | 79 + modules/enterprise/server/plugins/alert-cli/src/main/java/org/rhq/enterprise/server/plugins/alertCli/CliSender.java | 14 modules/enterprise/server/plugins/cloud/src/main/resources/META-INF/rhq-serverplugin.xml | 2 modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java | 32 modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java | 10 modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java | 27 modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/GridFSTest.java | 63 + modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java | 16 modules/enterprise/server/plugins/drift-rhq/pom.xml | 6 modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java | 18 modules/enterprise/server/plugins/perspectives/core/perspective/src/main/resources/META-INF/rhq-serverplugin.xml | 2 modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java | 208 ++++- modules/enterprise/server/safe-invoker/src/test/java/org/rhq/enterprise/server/util/HibernateDetachUtilityTest.java | 141 +++ modules/enterprise/server/sars/agent-sar/src/main/resources/META-INF/embedded-agent-configuration.xml | 24 modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtil.java | 406 ++++++++++ modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/XmlSchemas.java | 8 modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd | 24 modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd | 231 +++++ modules/enterprise/server/xml-schemas/src/test/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtilTest.java | 229 +++++ modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstallationInfo.java | 4 modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml | 2 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java | 5 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java | 12 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java | 37 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java | 13 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java | 9 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java | 9 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java | 2 modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarComponent.java | 58 - modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarDiscovery.java | 45 - modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 133 ++- modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstallationInfo.java | 6 modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml | 2 modules/test-utils/src/main/java/org/rhq/test/JPAUtils.java | 10 294 files changed, 9886 insertions(+), 4629 deletions(-)
New commits: commit 18105773312c888d884f71541f6ed778408aee6e Merge: fbcf5fd 0b63dbe Author: Stefan Negrea snegrea@redhat.com Date: Thu Aug 25 13:42:57 2011 -0500
Merge branch 'mod_cluster_plugin' of ssh://git.fedorahosted.org/git/rhq/rhq into mod_cluster_plugin
commit fbcf5fd1fe8ef454578d00c2617bde54f353ecd7 Author: Stefan Negrea snegrea@redhat.com Date: Thu Aug 25 00:14:01 2011 -0500
Small refactoring and code formating change to make the class easier to read and understand.
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java index 6abf955..8cff302 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java @@ -75,6 +75,7 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { */ public void setPropertyValue(String propertyName, String value) { boolean propertyFound = false; + for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { Node currentNode = beanNode.getChildNodes().item(i);
@@ -107,8 +108,10 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { * @return */ public String getPropertyValue(String propertyName) { - for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { - Node currentNode = beanNode.getChildNodes().item(i); + NodeList nodeList = beanNode.getChildNodes(); + + for (int i = 0; i < nodeList.getLength(); i++) { + Node currentNode = nodeList.item(i);
if (currentNode.getNodeName().equals("property") && currentNode.getAttributes().getNamedItem("name") != null @@ -126,10 +129,11 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { * @return */ private Node getBeanNodeByClass(String className) { - NodeList result = this.getDocument().getElementsByTagName("bean"); + NodeList nodeList = this.getDocument().getElementsByTagName("bean"); + + for (int i = 1; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i);
- for (int i = 1; i < result.getLength(); i++) { - Node node = result.item(i); if (node.getAttributes().getNamedItem("class") != null && className.equals(node.getAttributes().getNamedItem("class").getTextContent())) { return node; @@ -144,10 +148,11 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { * @return */ private Node getBeanNodeByName(String beanName) { - NodeList result = this.getDocument().getElementsByTagName("bean"); + NodeList nodeList = this.getDocument().getElementsByTagName("bean"); + + for (int i = 1; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i);
- for (int i = 1; i < result.getLength(); i++) { - Node node = result.item(i); if (node.getAttributes().getNamedItem("name") != null && beanName.equals(node.getAttributes().getNamedItem("name").getTextContent())) { return node; @@ -163,17 +168,17 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { * @return */ private String getBeanFromConstructorArgument(Node beanNode, String constructorArgumentClassName) { - List<Node> tempNodeList = this.getChildNodesByName(beanNode, "constructor"); + List<Node> nodeList = this.getChildrenNodesByName(beanNode, "constructor");
- if (tempNodeList.size() > 0) { - Node constructorNode = tempNodeList.get(0); + if (nodeList.size() > 0) { + Node constructorNode = nodeList.get(0);
- tempNodeList = this.getChildNodesByName(constructorNode, "parameter"); + nodeList = this.getChildrenNodesByName(constructorNode, "parameter");
- if (tempNodeList.size() > 0) { + if (nodeList.size() > 0) { Node parameterNode = null;
- for (Node currentNode : tempNodeList) { + for (Node currentNode : nodeList) { if (currentNode.getAttributes().getNamedItem("class") != null && constructorArgumentClassName.equals(currentNode.getAttributes().getNamedItem("class") .getTextContent())) { @@ -183,10 +188,10 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { }
if (parameterNode != null) { - tempNodeList = this.getChildNodesByName(parameterNode, "inject"); + nodeList = this.getChildrenNodesByName(parameterNode, "inject");
- if (tempNodeList.size() > 0) { - Node injectNode = tempNodeList.get(0); + if (nodeList.size() > 0) { + Node injectNode = nodeList.get(0); Node beanAttribute = injectNode.getAttributes().getNamedItem("bean");
if (beanAttribute != null) { @@ -205,17 +210,17 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { * @param nodeName * @return */ - private List<Node> getChildNodesByName(Node node, String nodeName) { - List<Node> listOfNodes = new ArrayList<Node>(); + private List<Node> getChildrenNodesByName(Node node, String nodeName) { + List<Node> nodeList = new ArrayList<Node>();
for (int i = 0; i < node.getChildNodes().getLength(); i++) { Node currentNode = node.getChildNodes().item(i);
if (nodeName.equals(currentNode.getNodeName())) { - listOfNodes.add(currentNode); + nodeList.add(currentNode); } }
- return listOfNodes; + return nodeList; } }
commit 0967165a89cef5268c8dcf6834b71cdefbb31032 Author: Stefan Negrea snegrea@redhat.com Date: Thu Aug 25 00:12:49 2011 -0500
Added the proxyInfo metric back to Catalina service context since it is readly available.
diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index 6f46849..3e523f7 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -374,6 +374,7 @@ </operation>
<metric property="proxyConfiguration" displayName="Proxy Configuration" displayType="summary" dataType="trait" /> + <metric property="proxyInfo" displayName="Proxy Info" displayType="summary" dataType="trait" /> <metric property="modelerType" displayName="Type of the modeled resource" displayType="summary" dataType="trait" /> <metric property="className" displayName="Fully qualified class name of the managed object" displayType="summary" dataType="trait" /> <metric property="advertise" displayName="Enable autodiscovery of httpd servers." displayType="summary" dataType="trait" />
commit 0a99815d01e6cf0d5554cc4c86bcac3b63d3bce6 Author: Stefan Negrea snegrea@redhat.com Date: Wed Aug 24 11:18:01 2011 -0500
More updates to the naming of each plugin component to match the intent and purpose. Also updated the integration tests to test each resource type.
diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModClusterPluginIntegrationTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModClusterPluginIntegrationTest.java new file mode 100644 index 0000000..625163b --- /dev/null +++ b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModClusterPluginIntegrationTest.java @@ -0,0 +1,229 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster.test; + +import java.io.File; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.measurement.MeasurementData; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.PluginContainerConfiguration; +import org.rhq.core.pc.plugin.FileSystemPluginFinder; +import org.rhq.core.pc.plugin.PluginEnvironment; +import org.rhq.core.pc.plugin.PluginManager; +import org.rhq.core.pluginapi.configuration.ConfigurationFacet; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; + +/** + * @author Stefan Negrea + */ +@SuppressWarnings("rawtypes") +@Test(groups = "modcluster-plugin") +public class ModClusterPluginIntegrationTest { + private Log log = LogFactory.getLog(this.getClass()); + private static final String PLUGIN_NAME = "mod_cluster"; + + @BeforeSuite + public void start() { + try { + File pluginDir = new File("target/testsetup/plugins"); + PluginContainerConfiguration pcConfig = new PluginContainerConfiguration(); + pcConfig.setPluginFinder(new FileSystemPluginFinder(pluginDir)); + pcConfig.setPluginDirectory(pluginDir); + + pcConfig.setInsideAgent(false); + PluginContainer.getInstance().setConfiguration(pcConfig); + PluginContainer.getInstance().initialize(); + log.info("PC started."); + for (String plugin : PluginContainer.getInstance().getPluginManager().getMetadataManager().getPluginNames()) { + log.info("...Loaded plugin: " + plugin); + } + } catch (Exception e) { + log.info("Error initializing the context", e); + } + } + + @AfterSuite + public void stop() { + PluginContainer.getInstance().shutdown(); + } + + @Test + public void testPluginLoad() { + PluginManager pluginManager = PluginContainer.getInstance().getPluginManager(); + PluginEnvironment pluginEnvironment = pluginManager.getPlugin(PLUGIN_NAME); + assert (pluginEnvironment != null) : "Null environment, plugin not loaded"; + assert (pluginEnvironment.getPluginName().equals(PLUGIN_NAME)); + } + + @Test(dependsOnMethods = "testPluginLoad") + public void testDiscovery() throws Exception { + InventoryReport report = PluginContainer.getInstance().getInventoryManager().executeServerScanImmediately(); + assert report != null; + log.info("Discovery took: " + (report.getEndTime() - report.getStartTime()) + "ms"); + + Thread.sleep(1000); + + report = PluginContainer.getInstance().getInventoryManager().executeServiceScanImmediately(); + assert report != null; + log.info("Discovery took: " + (report.getEndTime() - report.getStartTime()) + "ms"); + + Set<Resource> resources = findResource(PluginContainer.getInstance().getInventoryManager().getPlatform()); + log.info("Found " + resources.size() + " mod_cluster and mod_cluster_context instance(s)."); + + assert (resources.size() != 0) : "No mod_cluster or related instances found."; + + if (resources.size() != 0) { + for (Object objectResource : resources.toArray()) { + Resource resource = (Resource) objectResource; + if (resource.getResourceType().getName().equals("mod_cluster")) { + testMainResource(resource); + } else if (resource.getResourceType().getName().equals("Webapp Context")) { + testWebappContext(resource); + } else if (resource.getResourceType().getName().equals("HA Service Configuration")) { + testLoadServiceConfiguration(resource); + } else if (resource.getResourceType().getName().equals("HA Service")) { + testServiceMeasurement(resource); + testServiceMethodInvocation(resource); + } + } + } + } + + private void testServiceMethodInvocation(Resource resource) throws InterruptedException, Exception { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + + Configuration config = new Configuration(); + config.put(new PropertySimple("p1", "1")); + config.put(new PropertySimple("p2", java.util.concurrent.TimeUnit.SECONDS)); + OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("stop", config); + log.info("Result of operation stopContext was: " + result.getSimpleResult()); + } + + private void testLoadServiceConfiguration(Resource resource) throws Exception { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + ((ConfigurationFacet) resourceComponent).loadResourceConfiguration(); + } + + private void testServiceMeasurement(Resource resource) throws Exception { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + + if (resourceComponent instanceof MeasurementFacet) { + for (MeasurementDefinition def : resource.getResourceType().getMetricDefinitions()) { + Set<MeasurementScheduleRequest> metricList = new HashSet<MeasurementScheduleRequest>(); + metricList.add(new MeasurementScheduleRequest(1, def.getName(), 1000, true, def.getDataType(), null)); + MeasurementReport report = new MeasurementReport(); + ((MeasurementFacet) resourceComponent).getValues(report, metricList); + + MeasurementData data = report.getTraitData().iterator().next(); + assert data != null : "Unable to collect trait [" + def.getName() + "] on " + resource; + log.info("Measurement: " + def.getName() + "=" + data.getValue()); + } + } + } + + private void testMainResource(Resource resource) throws Exception { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + + if (resourceComponent instanceof OperationFacet) { + OperationResult result = null; + + result = ((OperationFacet) resourceComponent).invokeOperation("reset", new Configuration()); + log.info("Result of operation test was: " + result); + + result = ((OperationFacet) resourceComponent).invokeOperation("refresh", new Configuration()); + log.info("Result of operation test was: " + result); + } + } + + private void testWebappContext(Resource resource) throws Exception { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + + if (resourceComponent instanceof OperationFacet) { + try { + OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("enableContext", null); + log.info("Result of operation " + "enableContext" + " was: " + result.getSimpleResult()); + + Configuration config = new Configuration(); + config.put(new PropertySimple("timeout", "1")); + config.put(new PropertySimple("unit", java.util.concurrent.TimeUnit.SECONDS)); + result = ((OperationFacet) resourceComponent).invokeOperation("stopContext", config); + log.info("Result of operation stopContext was: " + result.getSimpleResult()); + + result = ((OperationFacet) resourceComponent).invokeOperation("enableContext", null); + log.info("Result of operation enableContext was: " + result.getSimpleResult()); + + result = ((OperationFacet) resourceComponent).invokeOperation("disableContext", null); + log.info("Result of operation disableContext was: " + result.getSimpleResult()); + + } catch (Exception e) { + log.info("Operation failed. ", e); + } + + } + } + + private Set<Resource> findResource(Resource parent) { + Set<Resource> found = new HashSet<Resource>(); + + Queue<Resource> discoveryQueue = new LinkedList<Resource>(); + discoveryQueue.add(parent); + + while (!discoveryQueue.isEmpty()) { + Resource currentResource = discoveryQueue.poll(); + + log.info("Discovered resource of type: " + currentResource.getResourceType().getName()); + if (currentResource.getResourceType().getPlugin().equals(PLUGIN_NAME)) { + found.add(currentResource); + } + + if (currentResource.getChildResources() != null) { + for (Resource child : currentResource.getChildResources()) { + discoveryQueue.add(child); + } + } + } + + return found; + } +} diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java deleted file mode 100644 index f27b153..0000000 --- a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 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.plugins.modcluster.test; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; - -import org.rhq.core.clientapi.server.discovery.InventoryReport; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.measurement.MeasurementData; -import org.rhq.core.domain.measurement.MeasurementDefinition; -import org.rhq.core.domain.measurement.MeasurementReport; -import org.rhq.core.domain.measurement.MeasurementScheduleRequest; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.pc.PluginContainer; -import org.rhq.core.pc.PluginContainerConfiguration; -import org.rhq.core.pc.plugin.FileSystemPluginFinder; -import org.rhq.core.pc.plugin.PluginEnvironment; -import org.rhq.core.pc.plugin.PluginManager; -import org.rhq.core.pluginapi.configuration.ConfigurationFacet; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.measurement.MeasurementFacet; -import org.rhq.core.pluginapi.operation.OperationFacet; -import org.rhq.core.pluginapi.operation.OperationResult; - -/** - * @author Stefan Negrea - */ -@SuppressWarnings("rawtypes") -@Test(groups = "modcluster-plugin") -public class ModclusterPluginTest { - private Log log = LogFactory.getLog(this.getClass()); - private static final String PLUGIN_NAME = "mod_cluster"; - - @BeforeSuite - public void start() { - try { - File pluginDir = new File("target/testsetup/plugins"); - PluginContainerConfiguration pcConfig = new PluginContainerConfiguration(); - pcConfig.setPluginFinder(new FileSystemPluginFinder(pluginDir)); - pcConfig.setPluginDirectory(pluginDir); - - pcConfig.setInsideAgent(false); - PluginContainer.getInstance().setConfiguration(pcConfig); - PluginContainer.getInstance().initialize(); - log.info("PC started."); - for (String plugin : PluginContainer.getInstance().getPluginManager().getMetadataManager().getPluginNames()) { - log.info("...Loaded plugin: " + plugin); - } - } catch (Exception e) { - log.info("Error initializing the context", e); - } - } - - @AfterSuite - public void stop() { - PluginContainer.getInstance().shutdown(); - } - - @Test - public void testPluginLoad() { - PluginManager pluginManager = PluginContainer.getInstance().getPluginManager(); - PluginEnvironment pluginEnvironment = pluginManager.getPlugin(PLUGIN_NAME); - assert (pluginEnvironment != null) : "Null environment, plugin not loaded"; - assert (pluginEnvironment.getPluginName().equals(PLUGIN_NAME)); - } - - @Test(dependsOnMethods = "testPluginLoad") - public void testDiscovery() throws Exception { - InventoryReport report = PluginContainer.getInstance().getInventoryManager().executeServerScanImmediately(); - assert report != null; - log.info("Discovery took: " + (report.getEndTime() - report.getStartTime()) + "ms"); - - Thread.sleep(1000); - - report = PluginContainer.getInstance().getInventoryManager().executeServiceScanImmediately(); - assert report != null; - log.info("Discovery took: " + (report.getEndTime() - report.getStartTime()) + "ms"); - - List<String> typeNames = new ArrayList<String>() { - private static final long serialVersionUID = 1L; - - { - add(PLUGIN_NAME); - add("Webapp Context"); - add("HA Service Configuration"); - add("HA Service"); - } - }; - - Set<Resource> resources = findResource(PluginContainer.getInstance().getInventoryManager().getPlatform(), - typeNames); - log.info("Found " + resources.size() + " mod_cluster and mod_cluster_context instance(s)."); - - assert (resources.size() != 0) : "No mod_cluster or related instances found."; - - if (resources.size() != 0) { - for (Object objectResource : resources.toArray()) { - Resource resource = (Resource) objectResource; - if (resource.getResourceType().getName().equals("mod_cluster")) { - testResourceMeasurement(resource); - } else if (resource.getResourceType().getName().equals("Webapp Context")) { - testContextOperations(resource); - } else if (resource.getResourceType().getName().equals("HA Service Configuration")) { - ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() - .getResourceComponent(resource); - ((ConfigurationFacet) resourceComponent).loadResourceConfiguration(); - } else if (resource.getResourceType().getName().equals("HA Service")) { - ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() - .getResourceComponent(resource); - - Configuration config = new Configuration(); - config.put(new PropertySimple("p1", "1")); - config.put(new PropertySimple("p2", java.util.concurrent.TimeUnit.SECONDS)); - OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("stop", config); - log.info("Result of operation stopContext was: " + result.getSimpleResult()); - } - } - } - } - - private void testResourceMeasurement(Resource resource) throws Exception { - ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() - .getResourceComponent(resource); - if (resourceComponent instanceof MeasurementFacet) { - for (MeasurementDefinition def : resource.getResourceType().getMetricDefinitions()) { - Set<MeasurementScheduleRequest> metricList = new HashSet<MeasurementScheduleRequest>(); - metricList.add(new MeasurementScheduleRequest(1, def.getName(), 1000, true, def.getDataType(), null)); - MeasurementReport report = new MeasurementReport(); - ((MeasurementFacet) resourceComponent).getValues(report, metricList); - - MeasurementData data = report.getTraitData().iterator().next(); - assert data != null : "Unable to collect trait [" + def.getName() + "] on " + resource; - log.info("Measurement: " + def.getName() + "=" + data.getValue()); - } - } - - if (resourceComponent instanceof OperationFacet) { - OperationResult result = null; - - result = ((OperationFacet) resourceComponent).invokeOperation("reset", new Configuration()); - log.info("Result of operation test was: " + result); - - result = ((OperationFacet) resourceComponent).invokeOperation("disable", new Configuration()); - log.info("Result of operation test was: " + result.getSimpleResult()); - } - } - - private void testContextOperations(Resource resource) throws Exception { - ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() - .getResourceComponent(resource); - - if (resourceComponent instanceof OperationFacet) { - try { - OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("enableContext", null); - log.info("Result of operation " + "enableContext" + " was: " + result.getSimpleResult()); - - Configuration config = new Configuration(); - config.put(new PropertySimple("timeout", "1")); - config.put(new PropertySimple("unit", java.util.concurrent.TimeUnit.SECONDS)); - result = ((OperationFacet) resourceComponent).invokeOperation("stopContext", config); - log.info("Result of operation stopContext was: " + result.getSimpleResult()); - - result = ((OperationFacet) resourceComponent).invokeOperation("enableContext", null); - log.info("Result of operation enableContext was: " + result.getSimpleResult()); - - result = ((OperationFacet) resourceComponent).invokeOperation("disableContext", null); - log.info("Result of operation disableContext was: " + result.getSimpleResult()); - - } catch (Exception e) { - log.info("Operation failed. ", e); - } - - } - } - - private Set<Resource> findResource(Resource parent, List<String> typeNames) { - Set<Resource> found = new HashSet<Resource>(); - - Queue<Resource> discoveryQueue = new LinkedList<Resource>(); - discoveryQueue.add(parent); - - while (!discoveryQueue.isEmpty()) { - Resource currentResource = discoveryQueue.poll(); - - log.info("Discovered resource of type: " + currentResource.getResourceType().getName()); - if (typeNames.contains(currentResource.getResourceType().getName())) { - found.add(currentResource); - } - - if (currentResource.getChildResources() != null) { - for (Resource child : currentResource.getChildResources()) { - discoveryQueue.add(child); - } - } - } - - return found; - } -} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java index b9ce25e..b854398 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java @@ -89,7 +89,7 @@ public class ClassNameMBeanDiscoveryComponent<T extends JMXComponent> extends MB emsConnection.queryBeans(objectName); bean = emsConnection.getBean(objectName); } + return bean; } - -} \ No newline at end of file +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java deleted file mode 100644 index 4c8b437..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 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.plugins.modcluster; - -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.mc4j.ems.connection.bean.EmsBean; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.pluginapi.operation.OperationResult; -import org.rhq.plugins.jmx.MBeanResourceComponent; -import org.rhq.plugins.modcluster.helper.JBossHelper; - -/** - * Manages a mod_cluster context entity. - * - * @author Stefan Negrea - */ -@SuppressWarnings({ "rawtypes", "deprecation" }) -public class ContextComponent extends MBeanResourceComponent<MBeanResourceComponent> { - - private static final Log log = LogFactory.getLog(ContextComponent.class); - - @Override - protected EmsBean loadBean() { - return getResourceContext().getParentResourceComponent().getEmsBean(); - } - - @Override - public AvailabilityType getAvailability() { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - try { - Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); - String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean()); - - ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); - - ProxyInfo.Context context = ProxyInfo.Context.fromString(resourceContext.getResourceKey()); - - int indexOfCurrentContext = proxyInfo.getAvailableContexts().indexOf(context); - - if (indexOfCurrentContext != -1) { - ProxyInfo.Context currentContext = proxyInfo.getAvailableContexts().get(indexOfCurrentContext); - - if (currentContext.isEnabled()) { - return AvailabilityType.UP; - } - } - - return AvailabilityType.DOWN; - } catch (Exception e) { - log.info(e); - return AvailabilityType.DOWN; - } finally { - Thread.currentThread().setContextClassLoader(cl); - } - } - - @Override - public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { - if ("enableContext".equals(name) || "disableContext".equals(name) || "stopContext".equals(name)) { - - ProxyInfo.Context context = ProxyInfo.Context.fromString(resourceContext.getResourceKey()); - - Object[] configuration = null; - if ("stopContext".equals(name)) { - configuration = new Object[] { context.getHost(), context.getPath(), - parameters.getSimple("timeout").getLongValue(), - TimeUnit.valueOf(parameters.getSimple("unit").getStringValue()) }; - } else { - configuration = new Object[] { context.getHost(), context.getPath() }; - } - - if (context.getPath().equals("/")) { - configuration[1] = "ROOT"; - } - - log.info(name + " - " + context.getHost() + " " + context.getPath()); - - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - try { - Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); - Object resultObject = getEmsBean().getOperation(name).invoke(configuration); - - if (resultObject instanceof OperationResult) { - return (OperationResult) resultObject; - } else { - return new OperationResult(String.valueOf(resultObject)); - } - } finally { - Thread.currentThread().setContextClassLoader(cl); - } - } - - throw new Exception("Operation " + name + " not available mod_cluster WebApp service."); - } -} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java deleted file mode 100644 index 788cbce..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 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.plugins.modcluster; - -import java.util.HashSet; -import java.util.Set; - -import org.mc4j.ems.connection.EmsConnection; -import org.mc4j.ems.connection.bean.EmsBean; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; -import org.rhq.plugins.jmx.MBeanResourceComponent; -import org.rhq.plugins.modcluster.helper.JBossHelper; - -/** - * Discovers mod_cluster contexts from the proxyInfo mbean property. - * - * @author Stefan Negrea - */ -@SuppressWarnings("rawtypes") -public class ContextDiscoveryComponent implements ResourceDiscoveryComponent<MBeanResourceComponent> { - - private static final String JVM_ROUTE_PROPERTY = "jvmRoute"; - private static final String ENGINE_OBJECT_NAME = "engineObjectName"; - - /* (non-Javadoc) - * @see org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent#discoverResources(org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext) - */ - public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent> context) { - String jvmRoute = this.getJvmRoute(context); - - EmsBean configBean = context.getParentResourceComponent().getEmsBean(); - String rawProxyInfo = JBossHelper.getRawProxyInfo(configBean); - - ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); - Set<DiscoveredResourceDetails> entities = new HashSet<DiscoveredResourceDetails>(); - - for (ProxyInfo.Context availableContext : proxyInfo.getAvailableContexts()) { - if (availableContext.getJvmRoute().equals(jvmRoute)) { - DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(), - availableContext.createKey(), availableContext.createName(), null, "Webapp Context", null, null); - entities.add(detail); - } - } - - return entities; - } - - /** - * Retrieves the jvm route for the node from the parent context. - * - * @param context the discovery context - * @return node's jvm route - */ - private String getJvmRoute(ResourceDiscoveryContext<MBeanResourceComponent> context) { - Configuration pluginConfig = context.getParentResourceComponent().getResourceContext().getPluginConfiguration(); - String engineObjectName = pluginConfig.getSimple(ENGINE_OBJECT_NAME).getStringValue(); - EmsBean engineBean = this.loadBean(engineObjectName, context.getParentResourceComponent()); - - return (String) engineBean.getAttribute(JVM_ROUTE_PROPERTY).refresh().toString(); - } - - /** - * Loads the bean with the given object name. - * - * Subclasses are free to override this method in order to load the bean. - * - * @param objectName the name of the bean to load - * @return the bean that is loaded - */ - protected EmsBean loadBean(String objectName, MBeanResourceComponent context) { - EmsConnection emsConnection = context.getEmsConnection(); - EmsBean bean = emsConnection.getBean(objectName); - if (bean == null) { - // In some cases, this resource component may have been discovered by some means other than querying its - // parent's EMSConnection (e.g. ApplicationDiscoveryComponent uses a filesystem to discover EARs and - // WARs that are not yet deployed). In such cases, getBean() will return null, since EMS won't have the - // bean in its cache. To cover such cases, make an attempt to query the underlying MBeanServer for the - // bean before giving up. - emsConnection.queryBeans(objectName); - bean = emsConnection.getBean(objectName); - } - return bean; - } -} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java index 7d5f0dc..0db722e 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java @@ -21,6 +21,7 @@ package org.rhq.plugins.modcluster; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.plugins.jmx.MBeanResourceComponent; import org.rhq.plugins.modcluster.helper.JBossHelper; +import org.rhq.plugins.modcluster.model.ProxyInfo;
/** * @author Stefan Negrea diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ProxyInfo.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ProxyInfo.java deleted file mode 100644 index 8614402..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ProxyInfo.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2008 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.plugins.modcluster; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Simple parser for the raw proxy information provided by mod_cluster. - * - * @author Stefan Negrea - */ -public class ProxyInfo { - - private Map<String, Node> availableNodes = new HashMap<String, Node>(); - private Map<String, Vhost> availableVhosts = new HashMap<String, Vhost>(); - private List<Context> availableContexts = new ArrayList<ProxyInfo.Context>(); - - public ProxyInfo(String rawProxyInfo) { - parseNodes(rawProxyInfo); - parseVhosts(rawProxyInfo); - parseContexts(rawProxyInfo); - } - - private void parseNodes(String rawProxyInfo) { - Pattern nodePattern = Pattern.compile("Node:.*\n"); - Matcher nodeMatcher = nodePattern.matcher(rawProxyInfo); - while (nodeMatcher.find()) { - String rawNode = nodeMatcher.group(); - String[] nodePieces = rawNode.split(","); - - String identifier = nodePieces[0]; - identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); - - String jvmRoute = nodePieces[1]; - jvmRoute = jvmRoute.substring(jvmRoute.indexOf(':') + 1).trim(); - - availableNodes.put(identifier, new Node(jvmRoute, identifier)); - } - } - - private void parseVhosts(String rawProxyInfo) { - Pattern vhostPattern = Pattern.compile("Vhost:.*\n"); - Matcher vhostMatcher = vhostPattern.matcher(rawProxyInfo); - while (vhostMatcher.find()) { - String rawVhost = vhostMatcher.group(); - String[] vhostPieces = rawVhost.split(","); - - String identifier = vhostPieces[0].trim(); - identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); - identifier = identifier.substring(0, identifier.lastIndexOf(":")); - - String host = vhostPieces[1].trim(); - host = host.substring(host.indexOf(":") + 1).trim(); - - availableVhosts.put(identifier, new Vhost(identifier, host)); - } - } - - private void parseContexts(String rawProxyInfo) { - Pattern contextPattern = Pattern.compile("Context:.*[\n|}]"); - Matcher contextMatcher = contextPattern.matcher(rawProxyInfo); - while (contextMatcher.find()) { - String rawContext = contextMatcher.group(); - String[] contextPieces = rawContext.split(","); - String actualContext = contextPieces[1].substring(contextPieces[1].indexOf("/")).trim(); - - String identifier = contextPieces[0]; - identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); - identifier = identifier.substring(0, identifier.lastIndexOf(":")); - - String nodeIdentifier = contextPieces[0]; - nodeIdentifier = nodeIdentifier.substring(nodeIdentifier.indexOf("[") + 1, nodeIdentifier.indexOf("]")); - nodeIdentifier = nodeIdentifier.substring(0, nodeIdentifier.indexOf(":")); - String jvmRoute = availableNodes.get(nodeIdentifier).getJvmRoute(); - - String rawIsEnabled = contextPieces[2]; - rawIsEnabled = rawIsEnabled.substring(rawIsEnabled.indexOf(':') + 1).trim(); - boolean isEnabled = rawIsEnabled.equals("ENABLED") ? true : false; - - Vhost relatedVhost = availableVhosts.get(identifier); - - availableContexts.add(new Context(jvmRoute, relatedVhost.getHost(), actualContext, isEnabled)); - } - } - - public List<Context> getAvailableContexts() { - return Collections.unmodifiableList(availableContexts); - } - - public List<Vhost> getAvailableVhosts() { - return Collections.unmodifiableList(new ArrayList<Vhost>(availableVhosts.values())); - } - - public List<Node> getAvailableNodes() { - return Collections.unmodifiableList(new ArrayList<Node>(availableNodes.values())); - } - - public static class Node { - private String jvmRoute; - private String nodeId; - - public Node(String jvmRoute, String nodeId) { - this.jvmRoute = jvmRoute; - this.nodeId = nodeId; - } - - public String getNodeId() { - return nodeId; - } - - public String getJvmRoute() { - return jvmRoute; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((jvmRoute == null) ? 0 : jvmRoute.hashCode()); - result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Node other = (Node) obj; - if (jvmRoute == null) { - if (other.jvmRoute != null) - return false; - } else if (!jvmRoute.equals(other.jvmRoute)) - return false; - if (nodeId == null) { - if (other.nodeId != null) - return false; - } else if (!nodeId.equals(other.nodeId)) - return false; - return true; - } - } - - public static class Vhost { - private String identifier; - private String host; - - public Vhost(String identifier, String host) { - this.identifier = identifier; - this.host = host; - } - - public String getIdentifier() { - return identifier; - } - - public String getHost() { - return host; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((identifier == null) ? 0 : identifier.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Vhost other = (Vhost) obj; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (identifier == null) { - if (other.identifier != null) - return false; - } else if (!identifier.equals(other.identifier)) - return false; - return true; - } - } - - public static class Context { - private String path; - private String host; - private String jvmRoute; - private boolean isEnabled; - - public Context(String jvmRoute, String host, String path) { - this(jvmRoute, host, path, false); - } - - public Context(String jvmRoute, String host, String path, boolean isEnabled) { - this.jvmRoute = jvmRoute; - this.host = host; - this.path = path; - this.isEnabled = isEnabled; - } - - public String getPath() { - return path; - } - - public String getHost() { - return host; - } - - public String getJvmRoute() { - return jvmRoute; - } - - public boolean isEnabled() { - return isEnabled; - } - - public String createKey() { - return jvmRoute + ":" + host + ":" + path; - } - - public String createName() { - return host + ":" + path; - } - - @Override - public String toString() { - return createKey(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((jvmRoute == null) ? 0 : jvmRoute.hashCode()); - result = prime * result + ((path == null) ? 0 : path.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Context other = (Context) obj; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (jvmRoute == null) { - if (other.jvmRoute != null) - return false; - } else if (!jvmRoute.equals(other.jvmRoute)) - return false; - if (path == null) { - if (other.path != null) - return false; - } else if (!path.equals(other.path)) - return false; - return true; - } - - public static Context fromString(String stringRepresentation) throws Exception { - String parts[] = stringRepresentation.trim().split(":"); - if (parts.length < 3) { - throw new Exception("Parsing error. Not enough information to create a context."); - } - - return new Context(parts[0], parts[1], parts[2]); - } - } -} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextComponent.java new file mode 100644 index 0000000..6131578 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextComponent.java @@ -0,0 +1,117 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster; + +import java.util.concurrent.TimeUnit; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.mc4j.ems.connection.bean.EmsBean; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper; +import org.rhq.plugins.modcluster.model.ProxyInfo; + +/** + * Manages a mod_cluster context entity. + * + * @author Stefan Negrea + */ +@SuppressWarnings({ "rawtypes", "deprecation" }) +public class WebappContextComponent extends MBeanResourceComponent<MBeanResourceComponent> { + + private static final Log log = LogFactory.getLog(WebappContextComponent.class); + + @Override + protected EmsBean loadBean() { + return getResourceContext().getParentResourceComponent().getEmsBean(); + } + + @Override + public AvailabilityType getAvailability() { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); + String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean()); + + ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); + + ProxyInfo.Context context = ProxyInfo.Context.fromString(resourceContext.getResourceKey()); + + int indexOfCurrentContext = proxyInfo.getAvailableContexts().indexOf(context); + + if (indexOfCurrentContext != -1) { + ProxyInfo.Context currentContext = proxyInfo.getAvailableContexts().get(indexOfCurrentContext); + + if (currentContext.isEnabled()) { + return AvailabilityType.UP; + } + } + + return AvailabilityType.DOWN; + } catch (Exception e) { + log.info(e); + return AvailabilityType.DOWN; + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + @Override + public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { + if ("enableContext".equals(name) || "disableContext".equals(name) || "stopContext".equals(name)) { + + ProxyInfo.Context context = ProxyInfo.Context.fromString(resourceContext.getResourceKey()); + + Object[] configuration = null; + if ("stopContext".equals(name)) { + configuration = new Object[] { context.getHost(), context.getPath(), + parameters.getSimple("timeout").getLongValue(), + TimeUnit.valueOf(parameters.getSimple("unit").getStringValue()) }; + } else { + configuration = new Object[] { context.getHost(), context.getPath() }; + } + + if (context.getPath().equals("/")) { + configuration[1] = "ROOT"; + } + + log.info(name + " - " + context.getHost() + " " + context.getPath()); + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); + Object resultObject = getEmsBean().getOperation(name).invoke(configuration); + + if (resultObject instanceof OperationResult) { + return (OperationResult) resultObject; + } else { + return new OperationResult(String.valueOf(resultObject)); + } + } finally { + Thread.currentThread().setContextClassLoader(cl); + } + } + + throw new Exception("Operation " + name + " not available mod_cluster WebApp service."); + } +} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextDiscoveryComponent.java new file mode 100644 index 0000000..559e1b6 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/WebappContextDiscoveryComponent.java @@ -0,0 +1,105 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster; + +import java.util.HashSet; +import java.util.Set; + +import org.mc4j.ems.connection.EmsConnection; +import org.mc4j.ems.connection.bean.EmsBean; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper; +import org.rhq.plugins.modcluster.model.ProxyInfo; + +/** + * Discovers mod_cluster contexts from the proxyInfo mbean property. + * + * @author Stefan Negrea + */ +@SuppressWarnings("rawtypes") +public class WebappContextDiscoveryComponent implements ResourceDiscoveryComponent<MBeanResourceComponent> { + + private static final String JVM_ROUTE_PROPERTY = "jvmRoute"; + private static final String ENGINE_OBJECT_NAME = "engineObjectName"; + + /* (non-Javadoc) + * @see org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent#discoverResources(org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext) + */ + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent> context) { + String jvmRoute = this.getJvmRoute(context); + + EmsBean configBean = context.getParentResourceComponent().getEmsBean(); + String rawProxyInfo = JBossHelper.getRawProxyInfo(configBean); + + ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); + Set<DiscoveredResourceDetails> entities = new HashSet<DiscoveredResourceDetails>(); + + for (ProxyInfo.Context availableContext : proxyInfo.getAvailableContexts()) { + if (availableContext.getJvmRoute().equals(jvmRoute)) { + DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(), + availableContext.createKey(), availableContext.createName(), null, "Webapp Context", null, null); + entities.add(detail); + } + } + + return entities; + } + + /** + * Retrieves the jvm route for the node from the parent context. + * + * @param context the discovery context + * @return node's jvm route + */ + private String getJvmRoute(ResourceDiscoveryContext<MBeanResourceComponent> context) { + Configuration pluginConfig = context.getParentResourceComponent().getResourceContext().getPluginConfiguration(); + String engineObjectName = pluginConfig.getSimple(ENGINE_OBJECT_NAME).getStringValue(); + EmsBean engineBean = this.loadBean(engineObjectName, context.getParentResourceComponent()); + + return (String) engineBean.getAttribute(JVM_ROUTE_PROPERTY).refresh().toString(); + } + + /** + * Loads the bean with the given object name. + * + * Subclasses are free to override this method in order to load the bean. + * + * @param objectName the name of the bean to load + * @return the bean that is loaded + */ + protected EmsBean loadBean(String objectName, MBeanResourceComponent context) { + EmsConnection emsConnection = context.getEmsConnection(); + EmsBean bean = emsConnection.getBean(objectName); + if (bean == null) { + // In some cases, this resource component may have been discovered by some means other than querying its + // parent's EMSConnection (e.g. ApplicationDiscoveryComponent uses a filesystem to discover EARs and + // WARs that are not yet deployed). In such cases, getBean() will return null, since EMS won't have the + // bean in its cache. To cover such cases, make an attempt to query the underlying MBeanServer for the + // bean before giving up. + emsConnection.queryBeans(objectName); + bean = emsConnection.getBean(objectName); + } + return bean; + } +} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/model/ProxyInfo.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/model/ProxyInfo.java new file mode 100644 index 0000000..9cedad5 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/model/ProxyInfo.java @@ -0,0 +1,310 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Simple parser for the raw proxy information provided by mod_cluster. + * + * @author Stefan Negrea + */ +public class ProxyInfo { + + private Map<String, Node> availableNodes = new HashMap<String, Node>(); + private Map<String, Vhost> availableVhosts = new HashMap<String, Vhost>(); + private List<Context> availableContexts = new ArrayList<ProxyInfo.Context>(); + + public ProxyInfo(String rawProxyInfo) { + parseNodes(rawProxyInfo); + parseVhosts(rawProxyInfo); + parseContexts(rawProxyInfo); + } + + private void parseNodes(String rawProxyInfo) { + Pattern nodePattern = Pattern.compile("Node:.*\n"); + Matcher nodeMatcher = nodePattern.matcher(rawProxyInfo); + while (nodeMatcher.find()) { + String rawNode = nodeMatcher.group(); + String[] nodePieces = rawNode.split(","); + + String identifier = nodePieces[0]; + identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); + + String jvmRoute = nodePieces[1]; + jvmRoute = jvmRoute.substring(jvmRoute.indexOf(':') + 1).trim(); + + availableNodes.put(identifier, new Node(jvmRoute, identifier)); + } + } + + private void parseVhosts(String rawProxyInfo) { + Pattern vhostPattern = Pattern.compile("Vhost:.*\n"); + Matcher vhostMatcher = vhostPattern.matcher(rawProxyInfo); + while (vhostMatcher.find()) { + String rawVhost = vhostMatcher.group(); + String[] vhostPieces = rawVhost.split(","); + + String identifier = vhostPieces[0].trim(); + identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); + identifier = identifier.substring(0, identifier.lastIndexOf(":")); + + String host = vhostPieces[1].trim(); + host = host.substring(host.indexOf(":") + 1).trim(); + + availableVhosts.put(identifier, new Vhost(identifier, host)); + } + } + + private void parseContexts(String rawProxyInfo) { + Pattern contextPattern = Pattern.compile("Context:.*[\n|}]"); + Matcher contextMatcher = contextPattern.matcher(rawProxyInfo); + while (contextMatcher.find()) { + String rawContext = contextMatcher.group(); + String[] contextPieces = rawContext.split(","); + String actualContext = contextPieces[1].substring(contextPieces[1].indexOf("/")).trim(); + + String identifier = contextPieces[0]; + identifier = identifier.substring(identifier.indexOf("[") + 1, identifier.indexOf("]")); + identifier = identifier.substring(0, identifier.lastIndexOf(":")); + + String nodeIdentifier = contextPieces[0]; + nodeIdentifier = nodeIdentifier.substring(nodeIdentifier.indexOf("[") + 1, nodeIdentifier.indexOf("]")); + nodeIdentifier = nodeIdentifier.substring(0, nodeIdentifier.indexOf(":")); + String jvmRoute = availableNodes.get(nodeIdentifier).getJvmRoute(); + + String rawIsEnabled = contextPieces[2]; + rawIsEnabled = rawIsEnabled.substring(rawIsEnabled.indexOf(':') + 1).trim(); + boolean isEnabled = rawIsEnabled.equals("ENABLED") ? true : false; + + Vhost relatedVhost = availableVhosts.get(identifier); + + availableContexts.add(new Context(jvmRoute, relatedVhost.getHost(), actualContext, isEnabled)); + } + } + + public List<Context> getAvailableContexts() { + return Collections.unmodifiableList(availableContexts); + } + + public List<Vhost> getAvailableVhosts() { + return Collections.unmodifiableList(new ArrayList<Vhost>(availableVhosts.values())); + } + + public List<Node> getAvailableNodes() { + return Collections.unmodifiableList(new ArrayList<Node>(availableNodes.values())); + } + + public static class Node { + private String jvmRoute; + private String nodeId; + + public Node(String jvmRoute, String nodeId) { + this.jvmRoute = jvmRoute; + this.nodeId = nodeId; + } + + public String getNodeId() { + return nodeId; + } + + public String getJvmRoute() { + return jvmRoute; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((jvmRoute == null) ? 0 : jvmRoute.hashCode()); + result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Node other = (Node) obj; + if (jvmRoute == null) { + if (other.jvmRoute != null) + return false; + } else if (!jvmRoute.equals(other.jvmRoute)) + return false; + if (nodeId == null) { + if (other.nodeId != null) + return false; + } else if (!nodeId.equals(other.nodeId)) + return false; + return true; + } + } + + public static class Vhost { + private String identifier; + private String host; + + public Vhost(String identifier, String host) { + this.identifier = identifier; + this.host = host; + } + + public String getIdentifier() { + return identifier; + } + + public String getHost() { + return host; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((host == null) ? 0 : host.hashCode()); + result = prime * result + ((identifier == null) ? 0 : identifier.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vhost other = (Vhost) obj; + if (host == null) { + if (other.host != null) + return false; + } else if (!host.equals(other.host)) + return false; + if (identifier == null) { + if (other.identifier != null) + return false; + } else if (!identifier.equals(other.identifier)) + return false; + return true; + } + } + + public static class Context { + private String path; + private String host; + private String jvmRoute; + private boolean isEnabled; + + public Context(String jvmRoute, String host, String path) { + this(jvmRoute, host, path, false); + } + + public Context(String jvmRoute, String host, String path, boolean isEnabled) { + this.jvmRoute = jvmRoute; + this.host = host; + this.path = path; + this.isEnabled = isEnabled; + } + + public String getPath() { + return path; + } + + public String getHost() { + return host; + } + + public String getJvmRoute() { + return jvmRoute; + } + + public boolean isEnabled() { + return isEnabled; + } + + public String createKey() { + return jvmRoute + ":" + host + ":" + path; + } + + public String createName() { + return host + ":" + path; + } + + @Override + public String toString() { + return createKey(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((host == null) ? 0 : host.hashCode()); + result = prime * result + ((jvmRoute == null) ? 0 : jvmRoute.hashCode()); + result = prime * result + ((path == null) ? 0 : path.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Context other = (Context) obj; + if (host == null) { + if (other.host != null) + return false; + } else if (!host.equals(other.host)) + return false; + if (jvmRoute == null) { + if (other.jvmRoute != null) + return false; + } else if (!jvmRoute.equals(other.jvmRoute)) + return false; + if (path == null) { + if (other.path != null) + return false; + } else if (!path.equals(other.path)) + return false; + return true; + } + + public static Context fromString(String stringRepresentation) throws Exception { + String parts[] = stringRepresentation.trim().split(":"); + if (parts.length < 3) { + throw new Exception("Parsing error. Not enough information to create a context."); + } + + return new Context(parts[0], parts[1], parts[2]); + } + } +} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index 7e1a79f..6f46849 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -440,7 +440,7 @@ </resource-configuration> </service>
- <service name="Webapp Context" discovery="ContextDiscoveryComponent" class="ContextComponent" description="Webapp Context"> + <service name="Webapp Context" discovery="WebappContextDiscoveryComponent" class="WebappContextComponent" description="Webapp Context">
<operation name="disableContext" displayName="Disable webapp" description="Disable this webapp."> <results> diff --git a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ProxyInfoTest.java b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ProxyInfoTest.java index 625d8d4..ebadd86 100644 --- a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ProxyInfoTest.java +++ b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ProxyInfoTest.java @@ -23,7 +23,7 @@ import java.io.InputStream;
import org.testng.annotations.Test;
-import org.rhq.plugins.modcluster.ProxyInfo; +import org.rhq.plugins.modcluster.model.ProxyInfo;
/** * @author Stefan Negrea
commit bf99abb7942ffafbd7aad728698105f8f0fc3a63 Author: Stefan Negrea snegrea@redhat.com Date: Tue Aug 23 16:12:11 2011 -0500
Renaming mod_cluster components to match their explicit purpose.
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java index 0a0a570..b87bfcd 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java @@ -30,14 +30,16 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport; import org.rhq.core.util.exception.ThrowableUtil; +import org.rhq.plugins.jmx.JMXComponent; +import org.rhq.plugins.jmx.MBeanResourceComponent; import org.rhq.plugins.modcluster.config.ModClusterBeanFile;
/** * @author Stefan Negrea * */ -@SuppressWarnings({ "deprecation" }) -public class FileConfiguredMBeanResourceComponent extends TimeUnitParamResourceComponent { +@SuppressWarnings({ "deprecation", "rawtypes" }) +public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent<JMXComponent> {
private static final Log log = LogFactory.getLog(FileConfiguredMBeanResourceComponent.class);
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServiceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServiceComponent.java new file mode 100644 index 0000000..d9da81c --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServiceComponent.java @@ -0,0 +1,52 @@ +package org.rhq.plugins.modcluster; + +import java.util.concurrent.TimeUnit; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.pluginapi.operation.OperationResult; + +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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. + */ + +/** + * + * @author Stefan Negrea + */ +public class ModClusterServiceComponent extends FileConfiguredMBeanResourceComponent { + + @Override + public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { + if (name.toLowerCase().startsWith("ping")) { + name = "ping"; + } + + return super.invokeOperation(name, parameters); + } + + @Override + protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { + System.out.println(typeName); + if (typeName.equals(TimeUnit.class.getName())) { + return TimeUnit.valueOf(propSimple.getStringValue()); + } + + return super.getPropertyValueAsType(propSimple, typeName); + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java deleted file mode 100644 index c67bf61..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.rhq.plugins.modcluster; - -import java.util.concurrent.TimeUnit; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.pluginapi.operation.OperationResult; - -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 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. - */ - -/** - * - * @author Stefan Negrea - */ -public class PolyPingMBeanResourceComponent extends FileConfiguredMBeanResourceComponent { - - @Override - public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { - if (name.toLowerCase().startsWith("ping")) { - name = "ping"; - } - - return super.invokeOperation(name, parameters); - } - - @Override - protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { - System.out.println(typeName); - if (typeName.equals(TimeUnit.class.getName())) { - return TimeUnit.valueOf(propSimple.getStringValue()); - } - - return super.getPropertyValueAsType(propSimple, typeName); - } -} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java deleted file mode 100644 index 0296eaf..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 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.plugins.modcluster; - -import java.util.concurrent.TimeUnit; - -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.plugins.jmx.MBeanResourceComponent; - -/** - * @author Stefan Negrea - * - */ -@SuppressWarnings("rawtypes") -public class TimeUnitParamResourceComponent extends MBeanResourceComponent { - - @Override - protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { - System.out.println(typeName); - if (typeName.equals(TimeUnit.class.getName())) { - return TimeUnit.valueOf(propSimple.getStringValue()); - } - - return super.getPropertyValueAsType(propSimple, typeName); - } -} diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index ed82f7c..7e1a79f 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -27,7 +27,7 @@
<!-- Start - Configuration for HAModClusterService --> <service name="HA Service" discovery="ClassNameMBeanDiscoveryComponent" - class="PolyPingMBeanResourceComponent" + class="ModClusterServiceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true">
@@ -199,7 +199,7 @@ <!-- End - Configuration for HAModClusterService -->
<!-- Start - Configuration for ModClusterService --> - <service name="Service" discovery="ClassNameMBeanDiscoveryComponent" class="PolyPingMBeanResourceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true"> + <service name="Service" discovery="ClassNameMBeanDiscoveryComponent" class="ModClusterServiceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true">
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" />
commit 0218f0b41bfb7e1ae6e6ddb12565c396c7ef813d Author: Stefan Negrea snegrea@redhat.com Date: Tue Aug 23 15:39:58 2011 -0500
Updates to support integration with JBoss' mod_cluster module for AS6 and EAP5.1.x
diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java index b642573..f27b153 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java +++ b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java @@ -112,6 +112,7 @@ public class ModclusterPluginTest { add(PLUGIN_NAME); add("Webapp Context"); add("HA Service Configuration"); + add("HA Service"); } };
@@ -132,6 +133,15 @@ public class ModclusterPluginTest { ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() .getResourceComponent(resource); ((ConfigurationFacet) resourceComponent).loadResourceConfiguration(); + } else if (resource.getResourceType().getName().equals("HA Service")) { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + + Configuration config = new Configuration(); + config.put(new PropertySimple("p1", "1")); + config.put(new PropertySimple("p2", java.util.concurrent.TimeUnit.SECONDS)); + OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("stop", config); + log.info("Result of operation stopContext was: " + result.getSimpleResult()); } } } diff --git a/modules/plugins/jmx/src/main/java/org/rhq/plugins/jmx/MBeanResourceComponent.java b/modules/plugins/jmx/src/main/java/org/rhq/plugins/jmx/MBeanResourceComponent.java index 6a60a93..8da6a2d 100644 --- a/modules/plugins/jmx/src/main/java/org/rhq/plugins/jmx/MBeanResourceComponent.java +++ b/modules/plugins/jmx/src/main/java/org/rhq/plugins/jmx/MBeanResourceComponent.java @@ -561,15 +561,15 @@ public class MBeanResourceComponent<T extends JMXComponent> implements Measureme paramIndex = Integer.valueOf(propName.substring(propName.indexOf('[') + 1, propName.indexOf(']'))); if (paramIndex < 0 || paramIndex >= emsParams.size()) { throw new IllegalStateException("Index [" + paramIndex + "] specified for parameter of operation [" - + name + "] on MBean [" + emsBean.getBeanName() + "] is invalid. The MBean operation takes " - + emsParams.size() + " parameters."); + + name + "] on MBean [" + emsBean.getBeanName() + "] is invalid. The MBean operation takes " + + emsParams.size() + " parameters."); } } else { paramIndex = emsParamIndexesByName.get(propName); if (paramIndex == null) { throw new IllegalStateException("Name [" + propName + "] specified for parameter of operation [" - + name + "] on MBean [" + emsBean.getBeanName() - + "] is invalid. The MBean operation does not take a parameter by that name."); + + name + "] on MBean [" + emsBean.getBeanName() + + "] is invalid. The MBean operation does not take a parameter by that name."); } } EmsParameter emsParam = emsParams.get(paramIndex); @@ -611,7 +611,7 @@ public class MBeanResourceComponent<T extends JMXComponent> implements Measureme return resultToReturn; }
- private Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { + protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { Object value; if (typeName.equals(String.class.getName())) { value = (propSimple == null) ? null : propSimple.getStringValue(); @@ -626,7 +626,8 @@ public class MBeanResourceComponent<T extends JMXComponent> implements Measureme } else if (typeName.equals(Double.class.getName()) || typeName.equals(double.class.getName())) { value = (propSimple == null) ? null : propSimple.getDoubleValue(); } else { - throw new IllegalStateException("Operation parameter maps to MBean parameter with an unsupported type (" + typeName + ")."); + throw new IllegalStateException("Operation parameter maps to MBean parameter with an unsupported type (" + + typeName + ")."); } // TODO GH: Handle rest of types. (I think i have a mapper for this in mc4j return value; diff --git a/modules/plugins/mod-cluster/pom.xml b/modules/plugins/mod-cluster/pom.xml index 35c5b28..3a6deaa 100644 --- a/modules/plugins/mod-cluster/pom.xml +++ b/modules/plugins/mod-cluster/pom.xml @@ -31,6 +31,11 @@ <scope>provided</scope> </dependency>
+ <dependency> + <groupId>org.jboss.on</groupId> + <artifactId>jopr-jboss-as-plugin</artifactId> + <version>${project.version}</version> + </dependency>
<dependency> <groupId>log4j</groupId> diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java index c5343d0..4c8b437 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java @@ -90,6 +90,10 @@ public class ContextComponent extends MBeanResourceComponent<MBeanResourceCompon configuration = new Object[] { context.getHost(), context.getPath() }; }
+ if (context.getPath().equals("/")) { + configuration[1] = "ROOT"; + } + log.info(name + " - " + context.getHost() + " " + context.getPath());
ClassLoader cl = Thread.currentThread().getContextClassLoader(); diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java index ee0369c..0a0a570 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java @@ -30,21 +30,20 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport; import org.rhq.core.util.exception.ThrowableUtil; -import org.rhq.plugins.jmx.MBeanResourceComponent; import org.rhq.plugins.modcluster.config.ModClusterBeanFile;
/** * @author Stefan Negrea * */ -@SuppressWarnings({ "rawtypes", "deprecation" }) -public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent { +@SuppressWarnings({ "deprecation" }) +public class FileConfiguredMBeanResourceComponent extends TimeUnitParamResourceComponent {
private static final Log log = LogFactory.getLog(FileConfiguredMBeanResourceComponent.class);
private static final String BEAN_CLASS_NAME_PROPERTY = "className"; private static final String DEPENDENCY_BEAN_CLASS_NAME_PROPERTY = "dependencyClassName"; - private static final String SERVER_HOME_DIR = "jboss.server.home.dir"; + private static final String SERVER_HOME_DIR = "serverHomeDir"; private static final String CONFIGURATION_FILE_RELATIVE_PATH = "/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml";
/** @@ -105,7 +104,7 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent }
private String getServerHomeDirectory() { - ModclusterServerComponent modClusterComponent = (ModclusterServerComponent) this.resourceContext + ModClusterServerComponent modClusterComponent = (ModClusterServerComponent) this.resourceContext .getParentResourceComponent();
PropertySimple property = modClusterComponent.getResourceContext().getPluginConfiguration() diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java index 496068c..3eb7cbe 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java @@ -36,9 +36,6 @@ import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent; @SuppressWarnings("rawtypes") public class LoadMetricDiscoveryComponent extends MBeanResourceDiscoveryComponent<JMXComponent> {
- /* (non-Javadoc) - * @see org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent#discoverResources(org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext, boolean) - */ @Override public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<JMXComponent> context, boolean skipUnknownProps) { diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterDiscoveryComponent.java new file mode 100644 index 0000000..b9a73b5 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterDiscoveryComponent.java @@ -0,0 +1,70 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster; + +import java.util.Set; + +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.plugins.jbossas.JBossASServerComponent; +import org.rhq.plugins.jbossas5.ApplicationServerComponent; +import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent; + +/** + * @author Stefan Negrea + * + */ +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class ModClusterDiscoveryComponent extends MBeanResourceDiscoveryComponent { + + private final static String JBOSS_SERVER_HOME_DIR = "serverHomeDir"; + + @Override + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext context) { + Set<DiscoveredResourceDetails> tempSet = super.discoverResources(context); + + for (DiscoveredResourceDetails detail : tempSet) { + String serverHomeDirectory = findServerHomeDirectory(context.getParentResourceComponent()); + detail.getPluginConfiguration().put(new PropertySimple(JBOSS_SERVER_HOME_DIR, serverHomeDirectory)); + } + + return tempSet; + } + + @SuppressWarnings("static-access") + public String findServerHomeDirectory(ResourceComponent parentResourceComponent) { + if (parentResourceComponent instanceof ApplicationServerComponent) { + ApplicationServerComponent parentComponent = (ApplicationServerComponent) parentResourceComponent; + + return parentComponent.getResourceContext().getPluginConfiguration().getSimple("serverHomeDir") + .getStringValue(); + + } else if (parentResourceComponent instanceof JBossASServerComponent) { + JBossASServerComponent parentComponent = (JBossASServerComponent) parentResourceComponent; + + return parentComponent.getPluginConfiguration().getSimple(parentComponent.JBOSS_HOME_DIR_CONFIG_PROP) + .getStringValue(); + } + + return null; + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java new file mode 100644 index 0000000..7d5f0dc --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModClusterServerComponent.java @@ -0,0 +1,47 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster; + +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper; + +/** + * @author Stefan Negrea + * + */ +@SuppressWarnings({ "rawtypes" }) +public class ModClusterServerComponent extends MBeanResourceComponent { + + @Override + public AvailabilityType getAvailability() { + String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean()); + + if (rawProxyInfo == null) { + return AvailabilityType.DOWN; + } + + ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); + if (proxyInfo.getAvailableNodes().size() == 0) { + return AvailabilityType.DOWN; + } + + return super.getAvailability(); + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java deleted file mode 100644 index 03598e9..0000000 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 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.plugins.modcluster; - -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.pluginapi.inventory.ResourceContext; -import org.rhq.plugins.jbossas.JBossASServerComponent; -import org.rhq.plugins.jbossas5.ApplicationServerComponent; -import org.rhq.plugins.jmx.MBeanResourceComponent; -import org.rhq.plugins.modcluster.helper.JBossHelper; - -/** - * @author Stefan Negrea - * - */ -@SuppressWarnings({ "rawtypes" }) -public class ModclusterServerComponent extends MBeanResourceComponent { - - private final static String JBOSS_SERVER_HOME_DIR = "jboss.server.home.dir"; - - @SuppressWarnings({ "unchecked", "deprecation", "static-access" }) - @Override - public void start(ResourceContext context) { - super.start(context); - - String serverHomeDirectory = null; - if (this.resourceContext.getParentResourceComponent() instanceof ApplicationServerComponent) { - ApplicationServerComponent parentComponent = (ApplicationServerComponent) this.resourceContext - .getParentResourceComponent(); - - serverHomeDirectory = parentComponent.getResourceContext().getPluginConfiguration() - .getSimple("serverHomeDir").getStringValue(); - - } else if (this.resourceContext.getParentResourceComponent() instanceof JBossASServerComponent) { - JBossASServerComponent parentComponent = (JBossASServerComponent) this.resourceContext - .getParentResourceComponent(); - - serverHomeDirectory = parentComponent.getPluginConfiguration() - .getSimple(parentComponent.JBOSS_HOME_DIR_CONFIG_PROP).getStringValue(); - } - - if (serverHomeDirectory != null) { - PropertySimple serverHomeDirectoryProperty = null; - serverHomeDirectoryProperty = new PropertySimple(); - serverHomeDirectoryProperty.setName(JBOSS_SERVER_HOME_DIR); - serverHomeDirectoryProperty.setStringValue(serverHomeDirectory); - this.resourceContext.getPluginConfiguration().put(serverHomeDirectoryProperty); - } - }; - - //private final static String PROXY_INFO_PROPERTY_NAME - - /* (non-Javadoc) - * @see org.rhq.plugins.jmx.MBeanResourceComponent#getAvailability() - */ - @Override - public AvailabilityType getAvailability() { - String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean()); - - if (rawProxyInfo == null) { - return AvailabilityType.DOWN; - } - - ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); - if (proxyInfo.getAvailableNodes().size() == 0) { - return AvailabilityType.DOWN; - } - - return super.getAvailability(); - } -} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java index bc54267..c67bf61 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java @@ -1,6 +1,9 @@ package org.rhq.plugins.modcluster;
+import java.util.concurrent.TimeUnit; + import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.pluginapi.operation.OperationResult;
/* @@ -36,4 +39,14 @@ public class PolyPingMBeanResourceComponent extends FileConfiguredMBeanResourceC
return super.invokeOperation(name, parameters); } + + @Override + protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { + System.out.println(typeName); + if (typeName.equals(TimeUnit.class.getName())) { + return TimeUnit.valueOf(propSimple.getStringValue()); + } + + return super.getPropertyValueAsType(propSimple, typeName); + } } diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java new file mode 100644 index 0000000..0296eaf --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/TimeUnitParamResourceComponent.java @@ -0,0 +1,42 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster; + +import java.util.concurrent.TimeUnit; + +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.plugins.jmx.MBeanResourceComponent; + +/** + * @author Stefan Negrea + * + */ +@SuppressWarnings("rawtypes") +public class TimeUnitParamResourceComponent extends MBeanResourceComponent { + + @Override + protected Object getPropertyValueAsType(PropertySimple propSimple, String typeName) { + System.out.println(typeName); + if (typeName.equals(TimeUnit.class.getName())) { + return TimeUnit.valueOf(propSimple.getStringValue()); + } + + return super.getPropertyValueAsType(propSimple, typeName); + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java index 6c00130..dee2f81 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java @@ -18,11 +18,18 @@ */ package org.rhq.plugins.modcluster.config;
+import java.io.File; import java.io.IOException;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -38,11 +45,13 @@ public abstract class AbstractConfigurationFile { public AbstractConfigurationFile(String fileName) throws ParserConfigurationException, SAXException, IOException { this.fileName = fileName;
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - this.document = docBuilder.parse(this.getFileName()); + loadConfiguratonFile(); }
+ abstract void setPropertyValue(String propertyName, String value); + + abstract String getPropertyValue(String propertyName); + /** * @return the fileName */ @@ -57,9 +66,19 @@ public abstract class AbstractConfigurationFile { return document; }
- abstract void setPropertyValue(String propertyName, String value); + public void saveConfigurationFile() throws Exception { + File file = new File(this.getFileName()); + StreamResult result = new StreamResult(file); + Source source = new DOMSource(this.getDocument());
- abstract String getPropertyValue(String propertyName); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.transform(source, result); + }
- abstract void saveConfigurationFile() throws Exception; + private void loadConfiguratonFile() throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + this.document = docBuilder.parse(this.getFileName()); + } } diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java index 1d008ee..354fa99 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java @@ -47,11 +47,4 @@ public class JBossWebServerFile extends AbstractConfigurationFile { // TODO Auto-generated method stub return null; } - - @Override - void saveConfigurationFile() throws Exception { - // TODO Auto-generated method stub - - } - } diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java index 45053f7..6abf955 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java @@ -19,17 +19,10 @@ package org.rhq.plugins.modcluster.config;
import java.io.IOException; -import java.io.StringWriter; import java.util.ArrayList; import java.util.List;
import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr; import org.w3c.dom.Node; @@ -129,22 +122,6 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { }
/** - * @throws TransformerException - */ - public void saveConfigurationFile() throws TransformerException { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "no"); - - //initialize StreamResult with File object to save to file - StreamResult result = new StreamResult(new StringWriter()); - DOMSource source = new DOMSource(this.getDocument()); - transformer.transform(source, result); - - String xmlString = result.getWriter().toString(); - System.out.println(xmlString); - } - - /** * @param className * @return */ @@ -155,7 +132,6 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { Node node = result.item(i); if (node.getAttributes().getNamedItem("class") != null && className.equals(node.getAttributes().getNamedItem("class").getTextContent())) { - System.out.println(node.getAttributes().getNamedItem("class").getTextContent()); return node; } } @@ -174,7 +150,6 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { Node node = result.item(i); if (node.getAttributes().getNamedItem("name") != null && beanName.equals(node.getAttributes().getNamedItem("name").getTextContent())) { - System.out.println(node.getAttributes().getNamedItem("name").getTextContent()); return node; } } @@ -243,5 +218,4 @@ public class ModClusterBeanFile extends AbstractConfigurationFile {
return listOfNodes; } - } diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index 4f3010f..ed82f7c 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -6,7 +6,9 @@ <depends plugin="JMX" />
<service name="mod_cluster" - discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" class="ModclusterServerComponent" supportsManualAdd="true" description="mod_cluster plugin" singleton="true"> + discovery="ModClusterDiscoveryComponent" + class="ModClusterServerComponent" + supportsManualAdd="true" description="mod_cluster plugin" singleton="true">
<runs-inside> <parent-resource-type name="JBossAS Server" plugin="JBossAS" /> @@ -17,13 +19,17 @@ <c:simple-property name="objectName" readOnly="true" default="Catalina:type=ModClusterListener,*|jboss.web:service=ModCluster" /> <c:simple-property name="engineObjectName" readOnly="true" default="jboss.web:type=Engine" /> <c:simple-property name="nameTemplate" default="mod_cluster" /> + <c:simple-property name="serverHomeDir"/> </plugin-configuration>
<operation name="reset" displayName="Reset the node" description="Move this application server out of an error state." /> <operation name="refresh" displayName="Refresh configuration" description="Refresh configuration for this application server." />
<!-- Start - Configuration for HAModClusterService --> - <service name="HA Service" discovery="ClassNameMBeanDiscoveryComponent" class="PolyPingMBeanResourceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true"> + <service name="HA Service" discovery="ClassNameMBeanDiscoveryComponent" + class="PolyPingMBeanResourceComponent" + supportsManualAdd="true" + description="HA Service Listener" singleton="true">
<plugin-configuration> <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" /> @@ -35,18 +41,18 @@ <!-- HA Operations --> <operation name="disableDomain" displayName="Disable domain" description="Disables all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> <results> - <c:simple-property name="result" description="The result of the operation" /> + <c:simple-property name="operationResult" description="The result of the operation" /> </results> </operation> <operation name="enableDomain" displayName="Enable domain" description="Enable all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="stopDomain" displayName="Stop domain" description="Gracefully stops all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> <parameters> - <c:simple-property required="true" name="timeout" type="string" displayName="The number of units of time for which to wait for all sessions to drain on a given node." /> - <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:simple-property required="true" name="p1" type="string" displayName="The number of units of time for which to wait for all sessions to drain on a given node." /> + <c:simple-property required="true" name="p2" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> <c:property-options allowCustomValue="false"> <c:option value="MICROSECONDS" name="MICROSECONDS" /> <c:option value="MILLISECONDS" name="MILLISECONDS" /> @@ -58,7 +64,7 @@ </c:simple-property> </parameters> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation>
@@ -66,59 +72,60 @@
<operation name="pingHTTPD" displayName="Ping httpd" description="Ping httpd and determine whether each proxy is accessible and healthy. Returns the PING_RSP grouped by proxy address."> <results> - <c:simple-property name="result" description="Map of PING_RPS response, grouped by proxy."> + <c:simple-property name="operationResult" description="Map of PING_RPS response, grouped by proxy."> </c:simple-property> </results> </operation> <operation name="pingNodeByJVMRoute" displayName="Ping node by JVM Route" description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Dtermines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> <parameters> - <c:simple-property required="true" name="jvmRoute" type="string" displayName="JVM Route of node to ping." /> + <c:simple-property required="true" name="p1" type="string" displayName="JVM Route of node to ping." /> </parameters> <results> - <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + <c:simple-property name="operationResult" type="string" description="Map of PING_RPS response, grouped by proxy." /> </results> </operation> <operation name="pingNodeByAddress" displayName="Ping node by address" description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Determines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> <parameters> - <c:simple-property required="true" name="scheme" type="string" displayName="Scheme (ajp, http, https)" /> - <c:simple-property required="true" name="hostname" type="string" displayName="Name or ip address of a node." /> - <c:simple-property required="true" name="port" type="string" displayName="Port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Scheme (ajp, http, https)" /> + <c:simple-property required="true" name="p2" type="string" displayName="Name or ip address of a node." /> + <c:simple-property required="true" name="p3" type="integer" displayName="Port" /> </parameters> <results> - <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + <c:simple-property name="operationResult" type="string" description="Map of PING_RPS response, grouped by proxy." /> </results> </operation>
<operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="p2" type="integer" displayName="Proxy port" /> </parameters> </operation> <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="p2" type="integer" displayName="Proxy port" /> </parameters> </operation> + <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" description="The result of the operation"> + <c:simple-property name="operationResult" description="The result of the operation"> </c:simple-property> </results> </operation> <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" description="The result of the operation"> + <c:simple-property name="operationResult" description="The result of the operation"> </c:simple-property> </results> </operation> <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> <parameters> - <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout" /> - <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:simple-property required="true" name="p1" type="string" displayName="Session draining timeout" /> + <c:simple-property required="true" name="p2" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> <c:property-options allowCustomValue="false"> <c:option value="MICROSECONDS" name="MICROSECONDS" /> <c:option value="MILLISECONDS" name="MILLISECONDS" /> @@ -130,7 +137,7 @@ </c:simple-property> </parameters> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation>
@@ -139,7 +146,7 @@ <metric property="ProxyInfo" displayName="Proxy Info" displayType="summary" dataType="trait" />
<resource-configuration> - <c:simple-property name="processStatusFrequency" type="integer" description="Process status frequency." /> + <c:simple-property name="processStatusFrequency" type="integer" required="false" description="Process status frequency." /> </resource-configuration> </service>
@@ -203,56 +210,57 @@
<operation name="pingHTTPD" displayName="Ping httpd" description="Ping httpd and determine whether each proxy is accessible and healthy. Returns the PING_RSP grouped by proxy address."> <results> - <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + <c:simple-property name="operationResult" type="string" description="Map of PING_RPS response, grouped by proxy." /> </results> </operation> <operation name="pingNodeByJVMRoute" displayName="Ping node by JVM Route" description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Dtermines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> <parameters> - <c:simple-property required="true" name="jvmRoute" type="string" displayName="JVM Route of node to ping." /> + <c:simple-property required="true" name="p1" type="string" displayName="JVM Route of node to ping." /> </parameters> <results> - <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + <c:simple-property name="operationResult" type="string" description="Map of PING_RPS response, grouped by proxy." /> </results> </operation> <operation name="pingNodeByAddress" displayName="Ping node by address" description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Determines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> <parameters> - <c:simple-property required="true" name="scheme" type="string" displayName="Scheme (ajp, http, https)" /> - <c:simple-property required="true" name="hostname" type="string" displayName="Name or ip address of a node." /> - <c:simple-property required="true" name="port" type="string" displayName="Port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Scheme (ajp, http, https)" /> + <c:simple-property required="true" name="p2" type="string" displayName="Name or ip address of a node." /> + <c:simple-property required="true" name="p3" type="integer" displayName="Port" /> </parameters> <results> - <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + <c:simple-property name="operationResult" type="string" description="Map of PING_RPS response, grouped by proxy." /> </results> </operation>
<operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="p2" type="integer" displayName="Proxy port" /> </parameters> </operation> <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + <c:simple-property required="true" name="p1" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="p2" type="integer" displayName="Proxy port" /> </parameters> </operation> + <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> <parameters> - <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout" /> - <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:simple-property required="true" name="p1" type="string" displayName="Session draining timeout" /> + <c:simple-property required="true" name="p2" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> <c:property-options allowCustomValue="false"> <c:option value="MICROSECONDS" name="MICROSECONDS" /> <c:option value="MILLISECONDS" name="MILLISECONDS" /> @@ -264,7 +272,7 @@ </c:simple-property> </parameters> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation>
@@ -338,12 +346,12 @@ </operation> <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> @@ -361,7 +369,7 @@ </c:simple-property> </parameters> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation>
@@ -396,11 +404,9 @@ <c:simple-property name="nameTemplate" default="Dynamic Load Balancer Factor" /> </plugin-configuration>
- <metric property="Metrics" displayName="Collected Metrics" displayType="summary" dataType="trait" /> - <resource-configuration> - <c:simple-property name="DecayFactor" type="integer" description="The number of historical load values used to determine load factor." /> - <c:simple-property name="History" type="integer" description="The exponential decay factor for historical load values." /> + <c:simple-property name="decayFactor" type="integer" required="false" description="The number of historical load values used to determine load factor." /> + <c:simple-property name="history" type="integer" required="false" description="The exponential decay factor for historical load values." /> </resource-configuration> </service>
@@ -424,11 +430,13 @@ <c:simple-property name="nameTemplate" default="Load Metric" /> </plugin-configuration>
- <metric property="Load" displayName="Load" category="utilization" description="The current load of this metric as a percent of the metric's capacity." dataType="measurement" /> + <metric property="Load" displayName="Load" category="utilization" + description="The current load of this metric as a percent of the metric's capacity." dataType="measurement" + defaultOn="true" displayType="summary"/>
<resource-configuration> - <c:simple-property name="Weight" type="integer" description="The significance of this load metric compared to the other metrics." /> - <c:simple-property name="Capacity" type="double" description="Used to normalize the value returned by load expressed as a percentage of the capacity, such that: 0 < (load/capacity) < 1" /> + <c:simple-property name="weight" type="integer" description="The significance of this load metric compared to the other metrics." /> + <c:simple-property name="capacity" type="double" description="Used to normalize the value returned by load expressed as a percentage of the capacity, such that: 0 < (load/capacity) < 1" /> </resource-configuration> </service>
@@ -436,7 +444,7 @@
<operation name="disableContext" displayName="Disable webapp" description="Disable this webapp."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation." /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation." /> </results> </operation> <operation name="stopContext" displayName="Stop webapp" description="Gracefully stops this webapp."> @@ -454,12 +462,12 @@ </c:simple-property> </parameters> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation> <operation name="enableContext" displayName="Enable webapp" description="Enable this webapp."> <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> + <c:simple-property name="operationResult" type="boolean" description="The result of the operation" /> </results> </operation>
diff --git a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java index c50b0e6..cba5672 100644 --- a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java +++ b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java @@ -28,16 +28,19 @@ public class ServerConfigTest { public void TestConfig() {
try { + //Test simple bean configuration ModClusterBeanFile config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService", "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); config.setPropertyValue("processStatusFrequency", "4"); config.setPropertyValue("test", "5"); config.setPropertyValue("test", "123");
- System.out.println(config.getPropertyValue("test")); + config.setPropertyValue("test", null); + config.setPropertyValue("processStatusFrequency", null);
config.saveConfigurationFile();
+ //Test bean configuration with constructor dependency config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService", "org.jboss.modcluster.config.ha.HAModClusterConfig", "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); @@ -45,11 +48,8 @@ public class ServerConfigTest { config.setPropertyValue("test", "5"); config.setPropertyValue("test", "123");
- System.out.println(config.getPropertyValue("test")); - - config.saveConfigurationFile(); - config.setPropertyValue("test", null); + config.setPropertyValue("processStatusFrequency", null); config.saveConfigurationFile(); } catch (Exception e) { // TODO Auto-generated catch block
commit 8a35caa7f9b3d2093e7cdd495cf65f4572bca065 Author: Stefan Negrea snegrea@redhat.com Date: Mon Aug 15 14:59:16 2011 -0500
The JBoss server home directory is now correctly retrieved from the parent resource component. Included some other minor code tweaks and refactorings.
diff --git a/modules/integration-tests/mod_cluster-plugin-test/pom.xml b/modules/integration-tests/mod_cluster-plugin-test/pom.xml index 77a81b2..ba94746 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/pom.xml +++ b/modules/integration-tests/mod_cluster-plugin-test/pom.xml @@ -42,7 +42,13 @@ </dependencyManagement>
<dependencies> - + <dependency> + <groupId>org.jboss.on</groupId> + <artifactId>jopr-jboss-as-5-plugin</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> <groupId>org.jboss.integration</groupId> <artifactId>jboss-profileservice-spi</artifactId> diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java index 0a39eab..b642573 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java +++ b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java @@ -45,6 +45,7 @@ import org.rhq.core.pc.PluginContainerConfiguration; import org.rhq.core.pc.plugin.FileSystemPluginFinder; import org.rhq.core.pc.plugin.PluginEnvironment; import org.rhq.core.pc.plugin.PluginManager; +import org.rhq.core.pluginapi.configuration.ConfigurationFacet; import org.rhq.core.pluginapi.inventory.ResourceComponent; import org.rhq.core.pluginapi.measurement.MeasurementFacet; import org.rhq.core.pluginapi.operation.OperationFacet; @@ -109,7 +110,8 @@ public class ModclusterPluginTest {
{ add(PLUGIN_NAME); - add(PLUGIN_NAME + " Webapp Context"); + add("Webapp Context"); + add("HA Service Configuration"); } };
@@ -124,8 +126,12 @@ public class ModclusterPluginTest { Resource resource = (Resource) objectResource; if (resource.getResourceType().getName().equals("mod_cluster")) { testResourceMeasurement(resource); - } else { + } else if (resource.getResourceType().getName().equals("Webapp Context")) { testContextOperations(resource); + } else if (resource.getResourceType().getName().equals("HA Service Configuration")) { + ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager() + .getResourceComponent(resource); + ((ConfigurationFacet) resourceComponent).loadResourceConfiguration(); } } } diff --git a/modules/plugins/mod-cluster/pom.xml b/modules/plugins/mod-cluster/pom.xml index fdc4f37..35c5b28 100644 --- a/modules/plugins/mod-cluster/pom.xml +++ b/modules/plugins/mod-cluster/pom.xml @@ -23,6 +23,14 @@ <version>${project.version}</version> <scope>provided</scope> </dependency> + + <dependency> + <groupId>org.jboss.on</groupId> + <artifactId>jopr-jboss-as-5-plugin</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> +
<dependency> <groupId>log4j</groupId> diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java index 8e14f9b..c5343d0 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java @@ -20,6 +20,8 @@ package org.rhq.plugins.modcluster;
import java.util.concurrent.TimeUnit;
+import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.mc4j.ems.connection.bean.EmsBean;
import org.rhq.core.domain.configuration.Configuration; @@ -35,6 +37,9 @@ import org.rhq.plugins.modcluster.helper.JBossHelper; */ @SuppressWarnings({ "rawtypes", "deprecation" }) public class ContextComponent extends MBeanResourceComponent<MBeanResourceComponent> { + + private static final Log log = LogFactory.getLog(ContextComponent.class); + @Override protected EmsBean loadBean() { return getResourceContext().getParentResourceComponent().getEmsBean(); diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java index 9b511b3..ee0369c 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java @@ -19,6 +19,9 @@
package org.rhq.plugins.modcluster;
+import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.ConfigurationUpdateStatus; import org.rhq.core.domain.configuration.PropertySimple; @@ -34,11 +37,15 @@ import org.rhq.plugins.modcluster.config.ModClusterBeanFile; * @author Stefan Negrea * */ -@SuppressWarnings("rawtypes") +@SuppressWarnings({ "rawtypes", "deprecation" }) public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent {
+ private static final Log log = LogFactory.getLog(FileConfiguredMBeanResourceComponent.class); + private static final String BEAN_CLASS_NAME_PROPERTY = "className"; private static final String DEPENDENCY_BEAN_CLASS_NAME_PROPERTY = "dependencyClassName"; + private static final String SERVER_HOME_DIR = "jboss.server.home.dir"; + private static final String CONFIGURATION_FILE_RELATIVE_PATH = "/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml";
/** * This default setup of configuration properties can map to mbean attributes @@ -46,15 +53,14 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent * @return the configuration of the component */ @Override - @SuppressWarnings("deprecation") public Configuration loadResourceConfiguration() { + Configuration configuration = new Configuration(); ConfigurationDefinition configurationDefinition = this.resourceContext.getResourceType() .getResourceConfigurationDefinition();
try { - ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance(this.resourceContext - .getPluginConfiguration()); + ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance();
for (PropertyDefinition property : configurationDefinition.getPropertyDefinitions().values()) { if (property instanceof PropertyDefinitionSimple) { @@ -69,8 +75,7 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent } } } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + log.debug("Unable to load mod_cluster configuration file.", e); }
return configuration; @@ -84,19 +89,35 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent updateResourceConfiguration(report, false); }
- private ModClusterBeanFile getModClusterBeanFileInstance(Configuration pluginConfig) throws Exception { + private ModClusterBeanFile getModClusterBeanFileInstance() throws Exception { + Configuration pluginConfig = this.resourceContext.getPluginConfiguration(); String beanClassName = pluginConfig.getSimple(BEAN_CLASS_NAME_PROPERTY).getStringValue();
+ String fileName = this.getServerHomeDirectory() + CONFIGURATION_FILE_RELATIVE_PATH; + if (pluginConfig.getSimple(DEPENDENCY_BEAN_CLASS_NAME_PROPERTY) != null) { String dependencyBeanClassName = pluginConfig.getSimple(DEPENDENCY_BEAN_CLASS_NAME_PROPERTY) .getStringValue(); - return new ModClusterBeanFile(dependencyBeanClassName); + return new ModClusterBeanFile(beanClassName, dependencyBeanClassName, fileName); + } + + return new ModClusterBeanFile(beanClassName, fileName); + } + + private String getServerHomeDirectory() { + ModclusterServerComponent modClusterComponent = (ModclusterServerComponent) this.resourceContext + .getParentResourceComponent(); + + PropertySimple property = modClusterComponent.getResourceContext().getPluginConfiguration() + .getSimple(SERVER_HOME_DIR); + + if (property != null) { + return property.getStringValue(); }
- return new ModClusterBeanFile(beanClassName); + return null; }
- @SuppressWarnings("deprecation") @Override public void updateResourceConfiguration(ConfigurationUpdateReport report, boolean ignoreReadOnly) { ConfigurationDefinition configurationDefinition = this.getResourceContext().getResourceType() @@ -106,8 +127,7 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent report.setStatus(ConfigurationUpdateStatus.SUCCESS);
try { - ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance(this.resourceContext - .getPluginConfiguration()); + ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance();
for (String key : report.getConfiguration().getSimpleProperties().keySet()) { PropertySimple property = report.getConfiguration().getSimple(key); @@ -127,10 +147,9 @@ public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent } }
- modClusterBeanFile.saveConfigFile(); + modClusterBeanFile.saveConfigurationFile(); } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + log.debug("Unable to save mod_cluster configuration file.", e); } }
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java index fb944c8..496068c 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java @@ -30,7 +30,7 @@ import org.rhq.plugins.jmx.JMXComponent; import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent;
/** - * @author snegrea + * @author Stefan Negrea * */ @SuppressWarnings("rawtypes") diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java index 2c964c0..03598e9 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java @@ -18,7 +18,11 @@ */ package org.rhq.plugins.modcluster;
+import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.inventory.ResourceContext; +import org.rhq.plugins.jbossas.JBossASServerComponent; +import org.rhq.plugins.jbossas5.ApplicationServerComponent; import org.rhq.plugins.jmx.MBeanResourceComponent; import org.rhq.plugins.modcluster.helper.JBossHelper;
@@ -29,6 +33,38 @@ import org.rhq.plugins.modcluster.helper.JBossHelper; @SuppressWarnings({ "rawtypes" }) public class ModclusterServerComponent extends MBeanResourceComponent {
+ private final static String JBOSS_SERVER_HOME_DIR = "jboss.server.home.dir"; + + @SuppressWarnings({ "unchecked", "deprecation", "static-access" }) + @Override + public void start(ResourceContext context) { + super.start(context); + + String serverHomeDirectory = null; + if (this.resourceContext.getParentResourceComponent() instanceof ApplicationServerComponent) { + ApplicationServerComponent parentComponent = (ApplicationServerComponent) this.resourceContext + .getParentResourceComponent(); + + serverHomeDirectory = parentComponent.getResourceContext().getPluginConfiguration() + .getSimple("serverHomeDir").getStringValue(); + + } else if (this.resourceContext.getParentResourceComponent() instanceof JBossASServerComponent) { + JBossASServerComponent parentComponent = (JBossASServerComponent) this.resourceContext + .getParentResourceComponent(); + + serverHomeDirectory = parentComponent.getPluginConfiguration() + .getSimple(parentComponent.JBOSS_HOME_DIR_CONFIG_PROP).getStringValue(); + } + + if (serverHomeDirectory != null) { + PropertySimple serverHomeDirectoryProperty = null; + serverHomeDirectoryProperty = new PropertySimple(); + serverHomeDirectoryProperty.setName(JBOSS_SERVER_HOME_DIR); + serverHomeDirectoryProperty.setStringValue(serverHomeDirectory); + this.resourceContext.getPluginConfiguration().put(serverHomeDirectoryProperty); + } + }; + //private final static String PROXY_INFO_PROPERTY_NAME
/* (non-Javadoc) diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java index 8f5d08b..bc54267 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java @@ -22,6 +22,10 @@ import org.rhq.core.pluginapi.operation.OperationResult; * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
+/** + * + * @author Stefan Negrea + */ public class PolyPingMBeanResourceComponent extends FileConfiguredMBeanResourceComponent {
@Override diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java index 4fe5788..6c00130 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java @@ -32,9 +32,6 @@ import org.xml.sax.SAXException; * @author Stefan Negrea */ public abstract class AbstractConfigurationFile { - - public static final String SERVER_HOME_DIR = "jboss.server.home.dir"; - private String fileName; private Document document;
@@ -60,4 +57,9 @@ public abstract class AbstractConfigurationFile { return document; }
+ abstract void setPropertyValue(String propertyName, String value); + + abstract String getPropertyValue(String propertyName); + + abstract void saveConfigurationFile() throws Exception; } diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java index 602e52b..1d008ee 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java @@ -36,4 +36,22 @@ public class JBossWebServerFile extends AbstractConfigurationFile { // TODO Auto-generated constructor stub }
+ @Override + void setPropertyValue(String propertyName, String value) { + // TODO Auto-generated method stub + + } + + @Override + String getPropertyValue(String propertyName) { + // TODO Auto-generated method stub + return null; + } + + @Override + void saveConfigurationFile() throws Exception { + // TODO Auto-generated method stub + + } + } diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java index 0e25f26..45053f7 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java @@ -16,7 +16,6 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ - package org.rhq.plugins.modcluster.config;
import java.io.IOException; @@ -38,24 +37,38 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
/** - * @author snegrea + * @author Stefan Negrea * */ public class ModClusterBeanFile extends AbstractConfigurationFile {
private Node beanNode;
- public ModClusterBeanFile(String className) throws ParserConfigurationException, SAXException, IOException { - super( - "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); + /** + * @param className + * @param configurationFile + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + */ + public ModClusterBeanFile(String className, String configurationFile) throws ParserConfigurationException, + SAXException, IOException { + super(configurationFile);
beanNode = this.getBeanNodeByClass(className); }
- public ModClusterBeanFile(String className, String constructorArgumentClassName) + /** + * @param className + * @param constructorArgumentClassName + * @param configurationFile + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + */ + public ModClusterBeanFile(String className, String constructorArgumentClassName, String configurationFile) throws ParserConfigurationException, SAXException, IOException { - super( - "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); + super(configurationFile);
Node primaryBeanNode = this.getBeanNodeByClass(className); String dependencyName = this.getBeanFromConstructorArgument(primaryBeanNode, constructorArgumentClassName); @@ -63,58 +76,10 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { beanNode = this.getBeanNodeByName(dependencyName); }
- private String getBeanFromConstructorArgument(Node beanNode, String constructorArgumentClassName) { - List<Node> tempNodeList = this.getChildNodesByName(beanNode, "constructor"); - - if (tempNodeList.size() > 0) { - Node constructorNode = tempNodeList.get(0); - - tempNodeList = this.getChildNodesByName(constructorNode, "parameter"); - - if (tempNodeList.size() > 0) { - Node parameterNode = null; - - for (Node currentNode : tempNodeList) { - if (currentNode.getAttributes().getNamedItem("class") != null - && constructorArgumentClassName.equals(currentNode.getAttributes().getNamedItem("class") - .getTextContent())) { - parameterNode = currentNode; - break; - } - } - - if (parameterNode != null) { - tempNodeList = this.getChildNodesByName(parameterNode, "inject"); - - if (tempNodeList.size() > 0) { - Node injectNode = tempNodeList.get(0); - Node beanAttribute = injectNode.getAttributes().getNamedItem("bean"); - - if (beanAttribute != null) { - return beanAttribute.getTextContent(); - } - } - } - } - } - - return null; - } - - private List<Node> getChildNodesByName(Node node, String nodeName) { - List<Node> listOfNodes = new ArrayList<Node>(); - - for (int i = 0; i < node.getChildNodes().getLength(); i++) { - Node currentNode = node.getChildNodes().item(i); - - if (nodeName.equals(currentNode.getNodeName())) { - listOfNodes.add(currentNode); - } - } - - return listOfNodes; - } - + /** + * @param propertyName + * @param value + */ public void setPropertyValue(String propertyName, String value) { boolean propertyFound = false; for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { @@ -144,6 +109,10 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { } }
+ /** + * @param propertyName + * @return + */ public String getPropertyValue(String propertyName) { for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { Node currentNode = beanNode.getChildNodes().item(i); @@ -159,7 +128,10 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { return null; }
- public void saveConfigFile() throws TransformerException { + /** + * @throws TransformerException + */ + public void saveConfigurationFile() throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "no");
@@ -172,7 +144,11 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { System.out.println(xmlString); }
- public Node getBeanNodeByClass(String className) { + /** + * @param className + * @return + */ + private Node getBeanNodeByClass(String className) { NodeList result = this.getDocument().getElementsByTagName("bean");
for (int i = 1; i < result.getLength(); i++) { @@ -187,7 +163,11 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { return null; }
- public Node getBeanNodeByName(String beanName) { + /** + * @param beanName + * @return + */ + private Node getBeanNodeByName(String beanName) { NodeList result = this.getDocument().getElementsByTagName("bean");
for (int i = 1; i < result.getLength(); i++) { @@ -202,4 +182,66 @@ public class ModClusterBeanFile extends AbstractConfigurationFile { return null; }
+ /** + * @param beanNode + * @param constructorArgumentClassName + * @return + */ + private String getBeanFromConstructorArgument(Node beanNode, String constructorArgumentClassName) { + List<Node> tempNodeList = this.getChildNodesByName(beanNode, "constructor"); + + if (tempNodeList.size() > 0) { + Node constructorNode = tempNodeList.get(0); + + tempNodeList = this.getChildNodesByName(constructorNode, "parameter"); + + if (tempNodeList.size() > 0) { + Node parameterNode = null; + + for (Node currentNode : tempNodeList) { + if (currentNode.getAttributes().getNamedItem("class") != null + && constructorArgumentClassName.equals(currentNode.getAttributes().getNamedItem("class") + .getTextContent())) { + parameterNode = currentNode; + break; + } + } + + if (parameterNode != null) { + tempNodeList = this.getChildNodesByName(parameterNode, "inject"); + + if (tempNodeList.size() > 0) { + Node injectNode = tempNodeList.get(0); + Node beanAttribute = injectNode.getAttributes().getNamedItem("bean"); + + if (beanAttribute != null) { + return beanAttribute.getTextContent(); + } + } + } + } + } + + return null; + } + + /** + * @param node + * @param nodeName + * @return + */ + private List<Node> getChildNodesByName(Node node, String nodeName) { + List<Node> listOfNodes = new ArrayList<Node>(); + + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + Node currentNode = node.getChildNodes().item(i); + + if (nodeName.equals(currentNode.getNodeName())) { + listOfNodes.add(currentNode); + } + } + + return listOfNodes; + } + } diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index fe4ac7d..4f3010f 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -5,7 +5,8 @@
<depends plugin="JMX" />
- <service name="mod_cluster" discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" class="ModclusterServerComponent" supportsManualAdd="true" description="mod_cluster plugin" singleton="true"> + <service name="mod_cluster" + discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" class="ModclusterServerComponent" supportsManualAdd="true" description="mod_cluster plugin" singleton="true">
<runs-inside> <parent-resource-type name="JBossAS Server" plugin="JBossAS" /> diff --git a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java index 4e4aac1..c50b0e6 100644 --- a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java +++ b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java @@ -28,27 +28,29 @@ public class ServerConfigTest { public void TestConfig() {
try { - ModClusterBeanFile config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService"); + ModClusterBeanFile config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService", + "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); config.setPropertyValue("processStatusFrequency", "4"); config.setPropertyValue("test", "5"); config.setPropertyValue("test", "123");
System.out.println(config.getPropertyValue("test"));
- config.saveConfigFile(); + config.saveConfigurationFile();
config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService", - "org.jboss.modcluster.config.ha.HAModClusterConfig"); + "org.jboss.modcluster.config.ha.HAModClusterConfig", + "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); config.setPropertyValue("processStatusFrequency", "4"); config.setPropertyValue("test", "5"); config.setPropertyValue("test", "123");
System.out.println(config.getPropertyValue("test"));
- config.saveConfigFile(); + config.saveConfigurationFile();
config.setPropertyValue("test", null); - config.saveConfigFile(); + config.saveConfigurationFile(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace();
commit eb9e67e2c2115a941044fe5e03782ac524d60550 Author: Stefan Negrea snegrea@redhat.com Date: Sun Aug 14 12:06:26 2011 -0500
Enable mod_cluster support for JBoss 5&6 with simple and HA configuration listeners. Also, added metric collections and configuration save to bean file.
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java new file mode 100644 index 0000000..b9ce25e --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ClassNameMBeanDiscoveryComponent.java @@ -0,0 +1,95 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster; + +import java.util.Set; + +import org.mc4j.ems.connection.EmsConnection; +import org.mc4j.ems.connection.bean.EmsBean; + +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.plugins.jmx.JMXComponent; +import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent; + +/** + * Discovers mod_cluster contexts from the proxyInfo mbean property. + * + * @author Stefan Negrea + */ +@SuppressWarnings("rawtypes") +public class ClassNameMBeanDiscoveryComponent<T extends JMXComponent> extends MBeanResourceDiscoveryComponent<T> { + + private static final String CLASS_NAME = "className"; + + /* (non-Javadoc) + * @see org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent#discoverResources(org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext, boolean) + */ + @Override + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<T> context, + boolean skipUnknownProps) { + + Set<DiscoveredResourceDetails> results = super.discoverResources(context, skipUnknownProps); + + for (DiscoveredResourceDetails discoveredResource : results) { + if (!isBeanConfiguredClassName(context, discoveredResource.getResourceKey())) { + results.remove(discoveredResource); + } + } + + return results; + } + + /** + * @param context + * @param objectName + * @return + */ + public boolean isBeanConfiguredClassName(ResourceDiscoveryContext<T> context, String objectName) { + String className = context.getDefaultPluginConfiguration().getSimple(CLASS_NAME).getStringValue(); + + EmsConnection connection = context.getParentResourceComponent().getEmsConnection(); + EmsBean emsBean = loadBean(connection, objectName); + + return className.equals(emsBean.getClassTypeName()); + } + + /** + * Loads the bean with the given object name. + * + * Subclasses are free to override this method in order to load the bean. + * + * @param objectName the name of the bean to load + * @return the bean that is loaded + */ + protected EmsBean loadBean(EmsConnection emsConnection, String objectName) { + EmsBean bean = emsConnection.getBean(objectName); + if (bean == null) { + // In some cases, this resource component may have been discovered by some means other than querying its + // parent's EMSConnection (e.g. ApplicationDiscoveryComponent uses a filesystem to discover EARs and + // WARs that are not yet deployed). In such cases, getBean() will return null, since EMS won't have the + // bean in its cache. To cover such cases, make an attempt to query the underlying MBeanServer for the + // bean before giving up. + emsConnection.queryBeans(objectName); + bean = emsConnection.getBean(objectName); + } + return bean; + } + +} \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java index 3545fa5..8e14f9b 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextComponent.java @@ -26,6 +26,7 @@ import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.pluginapi.operation.OperationResult; import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper;
/** * Manages a mod_cluster context entity. @@ -44,7 +45,7 @@ public class ContextComponent extends MBeanResourceComponent<MBeanResourceCompon ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); - String rawProxyInfo = (String) getEmsBean().getAttribute("proxyInfo").refresh().toString(); + String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean());
ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo);
@@ -91,12 +92,16 @@ public class ContextComponent extends MBeanResourceComponent<MBeanResourceCompon Thread.currentThread().setContextClassLoader(getEmsBean().getClass().getClassLoader()); Object resultObject = getEmsBean().getOperation(name).invoke(configuration);
- return new OperationResult(String.valueOf(resultObject)); + if (resultObject instanceof OperationResult) { + return (OperationResult) resultObject; + } else { + return new OperationResult(String.valueOf(resultObject)); + } } finally { Thread.currentThread().setContextClassLoader(cl); } }
- throw new Exception("Operation " + name + " not available mod_cluster_context service"); + throw new Exception("Operation " + name + " not available mod_cluster WebApp service."); } } \ No newline at end of file diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java index 3d03715..788cbce 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ContextDiscoveryComponent.java @@ -1,24 +1,20 @@ /* - * Jopr Management Platform + * RHQ Management Platform * Copyright (C) 2005-2008 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. + * 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 and the GNU Lesser General Public License - * for more details. + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.rhq.plugins.modcluster;
@@ -33,6 +29,7 @@ import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper;
/** * Discovers mod_cluster contexts from the proxyInfo mbean property. @@ -43,7 +40,6 @@ import org.rhq.plugins.jmx.MBeanResourceComponent; public class ContextDiscoveryComponent implements ResourceDiscoveryComponent<MBeanResourceComponent> {
private static final String JVM_ROUTE_PROPERTY = "jvmRoute"; - private static final String PROXY_INFO_PROPERTY = "proxyInfo"; private static final String ENGINE_OBJECT_NAME = "engineObjectName";
/* (non-Javadoc) @@ -51,7 +47,9 @@ public class ContextDiscoveryComponent implements ResourceDiscoveryComponent<MBe */ public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<MBeanResourceComponent> context) { String jvmRoute = this.getJvmRoute(context); - String rawProxyInfo = this.getRawProxyInfo(context); + + EmsBean configBean = context.getParentResourceComponent().getEmsBean(); + String rawProxyInfo = JBossHelper.getRawProxyInfo(configBean);
ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); Set<DiscoveredResourceDetails> entities = new HashSet<DiscoveredResourceDetails>(); @@ -59,8 +57,7 @@ public class ContextDiscoveryComponent implements ResourceDiscoveryComponent<MBe for (ProxyInfo.Context availableContext : proxyInfo.getAvailableContexts()) { if (availableContext.getJvmRoute().equals(jvmRoute)) { DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(), - availableContext.createKey(), availableContext.createName(), null, "mod_cluster Webapp Context", - null, null); + availableContext.createKey(), availableContext.createName(), null, "Webapp Context", null, null); entities.add(detail); } } @@ -83,17 +80,6 @@ public class ContextDiscoveryComponent implements ResourceDiscoveryComponent<MBe }
/** - * Retrieves raw proxy configuration from the parent context. - * - * @param context the discovery context - * @return raw proxy configuration - */ - private String getRawProxyInfo(ResourceDiscoveryContext<MBeanResourceComponent> context) { - EmsBean statsBean = context.getParentResourceComponent().getEmsBean(); - return (String) statsBean.getAttribute(PROXY_INFO_PROPERTY).refresh().toString(); - } - - /** * Loads the bean with the given object name. * * Subclasses are free to override this method in order to load the bean. diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java new file mode 100644 index 0000000..9b511b3 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/FileConfiguredMBeanResourceComponent.java @@ -0,0 +1,137 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.ConfigurationUpdateStatus; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport; +import org.rhq.core.util.exception.ThrowableUtil; +import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.config.ModClusterBeanFile; + +/** + * @author Stefan Negrea + * + */ +@SuppressWarnings("rawtypes") +public class FileConfiguredMBeanResourceComponent extends MBeanResourceComponent { + + private static final String BEAN_CLASS_NAME_PROPERTY = "className"; + private static final String DEPENDENCY_BEAN_CLASS_NAME_PROPERTY = "dependencyClassName"; + + /** + * This default setup of configuration properties can map to mbean attributes + * + * @return the configuration of the component + */ + @Override + @SuppressWarnings("deprecation") + public Configuration loadResourceConfiguration() { + Configuration configuration = new Configuration(); + ConfigurationDefinition configurationDefinition = this.resourceContext.getResourceType() + .getResourceConfigurationDefinition(); + + try { + ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance(this.resourceContext + .getPluginConfiguration()); + + for (PropertyDefinition property : configurationDefinition.getPropertyDefinitions().values()) { + if (property instanceof PropertyDefinitionSimple) { + String value = modClusterBeanFile.getPropertyValue(property.getName()); + if (value != null) { + configuration.put(new PropertySimple(property.getName(), value)); + } else { + PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple) property; + configuration.put(new PropertySimple(property.getName(), propertyDefinitionSimple + .getDefaultValue())); + } + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return configuration; + } + + /** + * Equivalent to updateResourceConfiguration(report, false); + */ + @Override + public void updateResourceConfiguration(ConfigurationUpdateReport report) { + updateResourceConfiguration(report, false); + } + + private ModClusterBeanFile getModClusterBeanFileInstance(Configuration pluginConfig) throws Exception { + String beanClassName = pluginConfig.getSimple(BEAN_CLASS_NAME_PROPERTY).getStringValue(); + + if (pluginConfig.getSimple(DEPENDENCY_BEAN_CLASS_NAME_PROPERTY) != null) { + String dependencyBeanClassName = pluginConfig.getSimple(DEPENDENCY_BEAN_CLASS_NAME_PROPERTY) + .getStringValue(); + return new ModClusterBeanFile(dependencyBeanClassName); + } + + return new ModClusterBeanFile(beanClassName); + } + + @SuppressWarnings("deprecation") + @Override + public void updateResourceConfiguration(ConfigurationUpdateReport report, boolean ignoreReadOnly) { + ConfigurationDefinition configurationDefinition = this.getResourceContext().getResourceType() + .getResourceConfigurationDefinition(); + + // assume we succeed - we'll set to failure if we can't set all properties + report.setStatus(ConfigurationUpdateStatus.SUCCESS); + + try { + ModClusterBeanFile modClusterBeanFile = this.getModClusterBeanFileInstance(this.resourceContext + .getPluginConfiguration()); + + for (String key : report.getConfiguration().getSimpleProperties().keySet()) { + PropertySimple property = report.getConfiguration().getSimple(key); + if (property != null) { + try { + PropertyDefinitionSimple def = configurationDefinition.getPropertyDefinitionSimple(property + .getName()); + if (!(ignoreReadOnly && def.isReadOnly())) { + modClusterBeanFile.setPropertyValue(property.getName(), property.getStringValue()); + } + } catch (Exception e) { + property.setErrorMessage(ThrowableUtil.getStackAsString(e)); + report + .setErrorMessage("Failed setting resource configuration - see property error messages for details"); + log.info("Failure setting MBean Resource configuration value for " + key, e); + } + } + } + + modClusterBeanFile.saveConfigFile(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java new file mode 100644 index 0000000..fb944c8 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/LoadMetricDiscoveryComponent.java @@ -0,0 +1,95 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster; + +import java.util.Set; + +import org.mc4j.ems.connection.EmsConnection; +import org.mc4j.ems.connection.bean.EmsBean; + +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.plugins.jmx.JMXComponent; +import org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent; + +/** + * @author snegrea + * + */ +@SuppressWarnings("rawtypes") +public class LoadMetricDiscoveryComponent extends MBeanResourceDiscoveryComponent<JMXComponent> { + + /* (non-Javadoc) + * @see org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent#discoverResources(org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext, boolean) + */ + @Override + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<JMXComponent> context, + boolean skipUnknownProps) { + + Set<DiscoveredResourceDetails> results = super.discoverResources(context, skipUnknownProps); + + for (DiscoveredResourceDetails discoveredResource : results) { + + String name = getBeanConfiguredClassName(context, discoveredResource.getResourceKey()); + + name = name.substring(name.lastIndexOf(".") + 1); + name = name.substring(0, name.lastIndexOf("LoadMetric")); + + discoveredResource.setResourceName(name); + discoveredResource.setResourceDescription("Load Metric"); + } + + return results; + } + + /** + * @param context + * @param objectName + * @return + */ + public String getBeanConfiguredClassName(ResourceDiscoveryContext<JMXComponent> context, String objectName) { + EmsConnection connection = context.getParentResourceComponent().getEmsConnection(); + EmsBean emsBean = loadBean(connection, objectName); + + return emsBean.getClassTypeName(); + } + + /** + * Loads the bean with the given object name. + * + * Subclasses are free to override this method in order to load the bean. + * + * @param objectName the name of the bean to load + * @return the bean that is loaded + */ + protected EmsBean loadBean(EmsConnection emsConnection, String objectName) { + EmsBean bean = emsConnection.getBean(objectName); + if (bean == null) { + // In some cases, this resource component may have been discovered by some means other than querying its + // parent's EMSConnection (e.g. ApplicationDiscoveryComponent uses a filesystem to discover EARs and + // WARs that are not yet deployed). In such cases, getBean() will return null, since EMS won't have the + // bean in its cache. To cover such cases, make an attempt to query the underlying MBeanServer for the + // bean before giving up. + emsConnection.queryBeans(objectName); + bean = emsConnection.getBean(objectName); + } + return bean; + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java index 70898ef..2c964c0 100644 --- a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/ModclusterServerComponent.java @@ -20,6 +20,7 @@ package org.rhq.plugins.modcluster;
import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.plugins.jmx.MBeanResourceComponent; +import org.rhq.plugins.modcluster.helper.JBossHelper;
/** * @author Stefan Negrea @@ -28,15 +29,21 @@ import org.rhq.plugins.jmx.MBeanResourceComponent; @SuppressWarnings({ "rawtypes" }) public class ModclusterServerComponent extends MBeanResourceComponent {
+ //private final static String PROXY_INFO_PROPERTY_NAME + /* (non-Javadoc) * @see org.rhq.plugins.jmx.MBeanResourceComponent#getAvailability() */ @Override public AvailabilityType getAvailability() { - String rawProxyInfo = (String) getEmsBean().getAttribute("proxyInfo").refresh().toString(); - ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); + String rawProxyInfo = JBossHelper.getRawProxyInfo(getEmsBean()); + + if (rawProxyInfo == null) { + return AvailabilityType.DOWN; + }
- if (proxyInfo.getAvailableContexts().size() == 0) { + ProxyInfo proxyInfo = new ProxyInfo(rawProxyInfo); + if (proxyInfo.getAvailableNodes().size() == 0) { return AvailabilityType.DOWN; }
diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java new file mode 100644 index 0000000..8f5d08b --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/PolyPingMBeanResourceComponent.java @@ -0,0 +1,35 @@ +package org.rhq.plugins.modcluster; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.operation.OperationResult; + +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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. + */ + +public class PolyPingMBeanResourceComponent extends FileConfiguredMBeanResourceComponent { + + @Override + public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { + if (name.toLowerCase().startsWith("ping")) { + name = "ping"; + } + + return super.invokeOperation(name, parameters); + } +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java new file mode 100644 index 0000000..4fe5788 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/AbstractConfigurationFile.java @@ -0,0 +1,63 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster.config; + +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +/** + * + * @author Stefan Negrea + */ +public abstract class AbstractConfigurationFile { + + public static final String SERVER_HOME_DIR = "jboss.server.home.dir"; + + private String fileName; + private Document document; + + public AbstractConfigurationFile(String fileName) throws ParserConfigurationException, SAXException, IOException { + this.fileName = fileName; + + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + this.document = docBuilder.parse(this.getFileName()); + } + + /** + * @return the fileName + */ + public String getFileName() { + return fileName; + } + + /** + * @return the doc + */ + public Document getDocument() { + return document; + } + +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java new file mode 100644 index 0000000..602e52b --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/JBossWebServerFile.java @@ -0,0 +1,39 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster.config; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.xml.sax.SAXException; + +/** + * @author Stefan Negrea + * + */ +public class JBossWebServerFile extends AbstractConfigurationFile { + + public JBossWebServerFile(String fileName) throws ParserConfigurationException, SAXException, IOException { + super(fileName); + // TODO Auto-generated constructor stub + } + +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java new file mode 100644 index 0000000..0e25f26 --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/config/ModClusterBeanFile.java @@ -0,0 +1,205 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster.config; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Attr; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +/** + * @author snegrea + * + */ +public class ModClusterBeanFile extends AbstractConfigurationFile { + + private Node beanNode; + + public ModClusterBeanFile(String className) throws ParserConfigurationException, SAXException, IOException { + super( + "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); + + beanNode = this.getBeanNodeByClass(className); + } + + public ModClusterBeanFile(String className, String constructorArgumentClassName) + throws ParserConfigurationException, SAXException, IOException { + super( + "/home/snegrea/Downloads/jboss51eap/jboss-as/server/all/deploy/mod_cluster.sar/META-INF/mod_cluster-jboss-beans.xml"); + + Node primaryBeanNode = this.getBeanNodeByClass(className); + String dependencyName = this.getBeanFromConstructorArgument(primaryBeanNode, constructorArgumentClassName); + + beanNode = this.getBeanNodeByName(dependencyName); + } + + private String getBeanFromConstructorArgument(Node beanNode, String constructorArgumentClassName) { + List<Node> tempNodeList = this.getChildNodesByName(beanNode, "constructor"); + + if (tempNodeList.size() > 0) { + Node constructorNode = tempNodeList.get(0); + + tempNodeList = this.getChildNodesByName(constructorNode, "parameter"); + + if (tempNodeList.size() > 0) { + Node parameterNode = null; + + for (Node currentNode : tempNodeList) { + if (currentNode.getAttributes().getNamedItem("class") != null + && constructorArgumentClassName.equals(currentNode.getAttributes().getNamedItem("class") + .getTextContent())) { + parameterNode = currentNode; + break; + } + } + + if (parameterNode != null) { + tempNodeList = this.getChildNodesByName(parameterNode, "inject"); + + if (tempNodeList.size() > 0) { + Node injectNode = tempNodeList.get(0); + Node beanAttribute = injectNode.getAttributes().getNamedItem("bean"); + + if (beanAttribute != null) { + return beanAttribute.getTextContent(); + } + } + } + } + } + + return null; + } + + private List<Node> getChildNodesByName(Node node, String nodeName) { + List<Node> listOfNodes = new ArrayList<Node>(); + + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + Node currentNode = node.getChildNodes().item(i); + + if (nodeName.equals(currentNode.getNodeName())) { + listOfNodes.add(currentNode); + } + } + + return listOfNodes; + } + + public void setPropertyValue(String propertyName, String value) { + boolean propertyFound = false; + for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { + Node currentNode = beanNode.getChildNodes().item(i); + + if (currentNode.getNodeName().equals("property") + && currentNode.getAttributes().getNamedItem("name") != null + && propertyName.equals(currentNode.getAttributes().getNamedItem("name").getTextContent())) { + + if (value != null) { + currentNode.setTextContent(value); + } else { + beanNode.removeChild(currentNode); + } + + propertyFound = true; + } + } + + if (value != null && !propertyFound) { + Node propertyChild = this.getDocument().createElement("property"); + Attr nameProperty = this.getDocument().createAttribute("name"); + nameProperty.setValue(propertyName); + propertyChild.setTextContent(value); + propertyChild.getAttributes().setNamedItem(nameProperty); + beanNode.appendChild(propertyChild); + } + } + + public String getPropertyValue(String propertyName) { + for (int i = 0; i < beanNode.getChildNodes().getLength(); i++) { + Node currentNode = beanNode.getChildNodes().item(i); + + if (currentNode.getNodeName().equals("property") + && currentNode.getAttributes().getNamedItem("name") != null + && propertyName.equals(currentNode.getAttributes().getNamedItem("name").getTextContent())) { + + return currentNode.getTextContent(); + } + } + + return null; + } + + public void saveConfigFile() throws TransformerException { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + + //initialize StreamResult with File object to save to file + StreamResult result = new StreamResult(new StringWriter()); + DOMSource source = new DOMSource(this.getDocument()); + transformer.transform(source, result); + + String xmlString = result.getWriter().toString(); + System.out.println(xmlString); + } + + public Node getBeanNodeByClass(String className) { + NodeList result = this.getDocument().getElementsByTagName("bean"); + + for (int i = 1; i < result.getLength(); i++) { + Node node = result.item(i); + if (node.getAttributes().getNamedItem("class") != null + && className.equals(node.getAttributes().getNamedItem("class").getTextContent())) { + System.out.println(node.getAttributes().getNamedItem("class").getTextContent()); + return node; + } + } + + return null; + } + + public Node getBeanNodeByName(String beanName) { + NodeList result = this.getDocument().getElementsByTagName("bean"); + + for (int i = 1; i < result.getLength(); i++) { + Node node = result.item(i); + if (node.getAttributes().getNamedItem("name") != null + && beanName.equals(node.getAttributes().getNamedItem("name").getTextContent())) { + System.out.println(node.getAttributes().getNamedItem("name").getTextContent()); + return node; + } + } + + return null; + } + +} diff --git a/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/helper/JBossHelper.java b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/helper/JBossHelper.java new file mode 100644 index 0000000..364f3ef --- /dev/null +++ b/modules/plugins/mod-cluster/src/main/java/org/rhq/plugins/modcluster/helper/JBossHelper.java @@ -0,0 +1,49 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.plugins.modcluster.helper; + +import org.mc4j.ems.connection.bean.EmsBean; + +/** + * @author Stefan Negrea + * + */ +public class JBossHelper { + + public static String getRawProxyInfo(EmsBean emsBean) { + String rawProxyInfo = null; + + //try first to get the value for JBoss EAP5.x or AS6 + try { + rawProxyInfo = (String) emsBean.getAttribute("ProxyInfo").refresh().toString(); + } catch (Exception e) { + } + + //if not able to get the value after the first attempt try to get the value for JBoss 4.2/4.3 + if (rawProxyInfo == null) { + try { + rawProxyInfo = (String) emsBean.getAttribute("proxyInfo").refresh().toString(); + } catch (Exception e) { + } + } + + return rawProxyInfo; + } +} diff --git a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml index 4846490..fe4ac7d 100644 --- a/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/mod-cluster/src/main/resources/META-INF/rhq-plugin.xml @@ -1,132 +1,466 @@ <?xml version="1.0" encoding="UTF-8" ?>
-<plugin name="mod_cluster" - displayName="mod_cluster" - description="Monitoring and management of mod_cluster plugin." - version="1.0" - package="org.rhq.plugins.modcluster" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns="urn:xmlns:rhq-plugin" - xmlns:c="urn:xmlns:rhq-configuration"> +<plugin name="mod_cluster" displayName="mod_cluster" description="Monitoring and management of mod_cluster plugin." version="1.0" package="org.rhq.plugins.modcluster" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration">
<depends plugin="JMX" />
- <service name="mod_cluster" - discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" - class="ModclusterServerComponent" - supportsManualAdd="true" - description="mod_cluster plugin" - singleton="true"> - + <service name="mod_cluster" discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" class="ModclusterServerComponent" supportsManualAdd="true" description="mod_cluster plugin" singleton="true"> + <runs-inside> - <parent-resource-type name="JBossAS Server" plugin="JBossAS"/> - <parent-resource-type name="JBossAS5 Server" plugin="JBossAS5"/> + <parent-resource-type name="JBossAS Server" plugin="JBossAS" /> + <parent-resource-type name="JBossAS Server" plugin="JBossAS5" /> </runs-inside> - + <plugin-configuration> - <c:simple-property name="objectName" readOnly="true" default="Catalina:type=ModClusterListener,*"/> - <c:simple-property name="engineObjectName" readOnly="true" default="jboss.web:type=Engine"/> - <c:simple-property name="nameTemplate" default="mod_cluster"/> + <c:simple-property name="objectName" readOnly="true" default="Catalina:type=ModClusterListener,*|jboss.web:service=ModCluster" /> + <c:simple-property name="engineObjectName" readOnly="true" default="jboss.web:type=Engine" /> + <c:simple-property name="nameTemplate" default="mod_cluster" /> </plugin-configuration> - - <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> - <parameters> - <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout"/> - <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> - <c:property-options allowCustomValue="false"> - <c:option value="MICROSECONDS" name="MICROSECONDS"/> - <c:option value="MILLISECONDS" name="MILLISECONDS"/> - <c:option value="NANOSECONDS" name="NANOSECONDS"/> - <c:option value="SECONDS" name="SECONDS"/> - <c:option value="HOURS" name="HOURS"/> - <c:option value="DAYS" name="DAYS"/> - </c:property-options> - </c:simple-property> - </parameters> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> - </results> - </operation> - <operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> - <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address"/> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port"/> - </parameters> - </operation> - <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> - </results> - </operation> + <operation name="reset" displayName="Reset the node" description="Move this application server out of an error state." /> - <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> - </results> - </operation> - <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> - <parameters> - <c:simple-property required="true" name="host" type="string" displayName="Proxy address"/> - <c:simple-property required="true" name="port" type="string" displayName="Proxy port"/> - </parameters> - </operation> <operation name="refresh" displayName="Refresh configuration" description="Refresh configuration for this application server." /> - - <metric property="proxyConfiguration" displayName="Proxy Configuration" displayType="summary" dataType="trait" /> - <metric property="modelerType" displayName="Type of the modeled resource" displayType="summary" dataType="trait" /> - <metric property="className" displayName="Fully qualified class name of the managed object" displayType="summary" dataType="trait" /> - <metric property="advertise" displayName="Enable autodiscovery of httpd servers." displayType="summary" dataType="trait" /> - - <resource-configuration> - <c:simple-property name="workerTimeout" type="integer" description="Timeout to wait for an available worker (default is no wait)." /> - <c:simple-property name="stickySession" type="boolean" description="Enables sticky session for the cluster."/> - <c:simple-property name="stickySessionRemove" type="boolean" description="Remove session when the request cannot be routed to the right node for this cluster."/> - <c:simple-property name="smax" type="integer" description="Maximum time on seconds for idle connections above smax."/> - <c:simple-property name="maxAttempts" type="integer" description="Maximum number of attempts to send the request to the backend server."/> - <c:simple-property name="advertiseSecurityKey" type="string" required="false" description="Security key for discovery."/> - <c:simple-property name="stickySessionForce" type="boolean" description="Return an error when the request cannot be routed to the right node."/> - <c:simple-property name="balancer" type="string" required="false" description="Name of the balancer."/> - <c:simple-property name="flushPackets" type="boolean" description="Allows controlling flusing of packets."/> - <c:simple-property name="socketTimeout" type="integer" description="Connection timeout for communication with the proxy." /> - <c:simple-property name="advertisePort" type="integer" required="false" description="Multicast port for discovery" /> - <c:simple-property name="advertiseGroupAddress" type="string" required="false" description="Multicast address for discovery."/> - <c:simple-property name="flushWait" type="integer" description="Time in ms to wait before flushing packets."/> - <c:simple-property name="ping" type="integer" description="Time in s to wait for a pong answer to a ping."/> - </resource-configuration> - - <service name="mod_cluster Webapp Context" - discovery="ContextDiscoveryComponent" - class="ContextComponent" - description="mod_cluster webapp context"> - - <operation name="disableContext" displayName="Disable webapp" description="Disable this webapp."> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation."/> - </results> - </operation> - <operation name="stopContext" displayName="Stop webapp" description="Gracefully stops this webapp."> + + <!-- Start - Configuration for HAModClusterService --> + <service name="HA Service" discovery="ClassNameMBeanDiscoveryComponent" class="PolyPingMBeanResourceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" /> + <c:simple-property name="nameTemplate" default="HA Service" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.ha.HAModClusterService" /> + <c:simple-property name="proxyInfoProperty" readOnly="true" default="ProxyInfo" /> + </plugin-configuration> + + <!-- HA Operations --> + <operation name="disableDomain" displayName="Disable domain" description="Disables all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> + <results> + <c:simple-property name="result" description="The result of the operation" /> + </results> + </operation> + <operation name="enableDomain" displayName="Enable domain" description="Enable all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="stopDomain" displayName="Stop domain" description="Gracefully stops all contexts on each node within the current domain. If the current domain is null, then all nodes are stopped."> + <parameters> + <c:simple-property required="true" name="timeout" type="string" displayName="The number of units of time for which to wait for all sessions to drain on a given node." /> + <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:property-options allowCustomValue="false"> + <c:option value="MICROSECONDS" name="MICROSECONDS" /> + <c:option value="MILLISECONDS" name="MILLISECONDS" /> + <c:option value="NANOSECONDS" name="NANOSECONDS" /> + <c:option value="SECONDS" name="SECONDS" /> + <c:option value="HOURS" name="HOURS" /> + <c:option value="DAYS" name="DAYS" /> + </c:property-options> + </c:simple-property> + </parameters> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + + <!-- Regular Operations --> + + <operation name="pingHTTPD" displayName="Ping httpd" description="Ping httpd and determine whether each proxy is accessible and healthy. Returns the PING_RSP grouped by proxy address."> + <results> + <c:simple-property name="result" description="Map of PING_RPS response, grouped by proxy."> + </c:simple-property> + </results> + </operation> + <operation name="pingNodeByJVMRoute" displayName="Ping node by JVM Route" + description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Dtermines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> + <parameters> + <c:simple-property required="true" name="jvmRoute" type="string" displayName="JVM Route of node to ping." /> + </parameters> + <results> + <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + </results> + </operation> + <operation name="pingNodeByAddress" displayName="Ping node by address" + description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Determines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> + <parameters> + <c:simple-property required="true" name="scheme" type="string" displayName="Scheme (ajp, http, https)" /> + <c:simple-property required="true" name="hostname" type="string" displayName="Name or ip address of a node." /> + <c:simple-property required="true" name="port" type="string" displayName="Port" /> + </parameters> + <results> + <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + </results> + </operation> + + <operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" description="The result of the operation"> + </c:simple-property> + </results> + </operation> + <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" description="The result of the operation"> + </c:simple-property> + </results> + </operation> + <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> + <parameters> + <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout" /> + <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:property-options allowCustomValue="false"> + <c:option value="MICROSECONDS" name="MICROSECONDS" /> + <c:option value="MILLISECONDS" name="MILLISECONDS" /> + <c:option value="NANOSECONDS" name="NANOSECONDS" /> + <c:option value="SECONDS" name="SECONDS" /> + <c:option value="HOURS" name="HOURS" /> + <c:option value="DAYS" name="DAYS" /> + </c:property-options> + </c:simple-property> + </parameters> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + + <metric property="MasterNode" displayName="Master Node" displayType="summary" dataType="trait" /> + <metric property="ProxyConfiguration" displayName="Proxy Configuration" displayType="summary" dataType="trait" /> + <metric property="ProxyInfo" displayName="Proxy Info" displayType="summary" dataType="trait" /> + + <resource-configuration> + <c:simple-property name="processStatusFrequency" type="integer" description="Process status frequency." /> + </resource-configuration> + </service> + + <service name="HA Service Configuration" discovery="ClassNameMBeanDiscoveryComponent" class="FileConfiguredMBeanResourceComponent" supportsManualAdd="true" description="HA Service Configuration" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" /> + <c:simple-property name="nameTemplate" default="HA Service Configuration" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.ha.HAModClusterService" /> + <c:simple-property name="dependencyClassName" readOnly="true" default="org.jboss.modcluster.config.ha.HAModClusterConfig" /> + <c:simple-property name="proxyInfoProperty" readOnly="true" default="ProxyInfo" /> + </plugin-configuration> + + <resource-configuration> + + <!-- HA Configuration --> + <c:simple-property name="masterPerLoadBalancingGroup" type="boolean" required="false" description="Enable current node to be master in the load balancing group." /> + + <!-- Handler Configuration --> + <c:simple-property name="advertise" type="boolean" required="false" default="false" description="Enable autodiscovery of httpd servers." /> + <c:simple-property name="advertiseGroupAddress" type="string" description="Multicast address on which to listen for advertisements." /> + <c:simple-property name="advertisePort" type="string" required="false" description="Multicast port for discovery" /> + <c:simple-property name="advertiseInterface" type="string" required="false" description="Multicast interface for discovery" /> + <c:simple-property name="advertiseSecurityKey" type="string" required="false" description="Security key for discovery." /> + <c:simple-property name="proxyList" type="string" required="false" description="Comma separated list of address:port listing the httpd servers where mod_cluster is running." /> + <c:simple-property name="proxyURL" type="string" required="false" description="URL prefix to send with commands to mod_cluster. Default is no prefix." /> + <c:simple-property name="socketTimeout" type="integer" required="false" description="Connection timeout for communication with the proxy." /> + <c:simple-property name="ssl" type="boolean" description="Whether to use SSL to communicate with mod_cluster. Note this has nothing to do with handling of https requests by JBoss Web" /> + <c:simple-property name="excludedContexts" type="string" required="false" description="Comma delimited list of contexts that should *not* be auto-registered with httpd. Contexts may be qualified by host using a colon, e.g. host1:context1. If no host is defined, localhost is assumed." /> + <c:simple-property name="autoEnableContexts" type="boolean" required="false" default="true" description="Toggle for context auto-enable during mod_cluster startup." /> + + <!-- Node Configuration --> + <c:simple-property name="loadBalancingGroup" type="string" required="false" description="Load balancing group." /> + <c:simple-property name="flushPackets" type="boolean" required="false" description="Allows controlling flusing of packets." /> + <c:simple-property name="flushWait" type="integer" required="false" description="Time in ms to wait before flushing packets." /> + <c:simple-property name="ping" type="integer" required="false" description="Time in s to wait for a pong answer to a ping." /> + <c:simple-property name="smax" type="integer" required="false" description="Maximum time on seconds for idle connections above smax." /> + <c:simple-property name="ttl" type="integer" required="false" description="TTL" /> + <c:simple-property name="nodeTimeout" type="integer" required="false" description="Node timeout" /> + <c:simple-property name="balancer" type="string" required="false" description="Name of the balancer" /> + + <!-- Balancer Configuration --> + <c:simple-property name="stickySession" type="boolean" description="Enables sticky session for the node." /> + <c:simple-property name="stickySessionRemove" type="boolean" description="Remove session when the request cannot be routed to the right node for this cluster." /> + <c:simple-property name="stickySessionForce" type="boolean" description="Return an error when the request cannot be routed to the right node." /> + <c:simple-property name="workerTimeout" type="integer" description="Timeout to wait for an available worker (default is no wait)." /> + <c:simple-property name="maxAttempts" type="integer" description="Maximum number of attempts to send the request to the backend server." /> + </resource-configuration> + </service> + <!-- End - Configuration for HAModClusterService --> + + <!-- Start - Configuration for ModClusterService --> + <service name="Service" discovery="ClassNameMBeanDiscoveryComponent" class="PolyPingMBeanResourceComponent" supportsManualAdd="true" description="HA Service Listener" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" /> + <c:simple-property name="nameTemplate" default="HA Service" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.ModClusterService" /> + <c:simple-property name="proxyInfoProperty" readOnly="true" default="ProxyInfo" /> + </plugin-configuration> + + <operation name="pingHTTPD" displayName="Ping httpd" description="Ping httpd and determine whether each proxy is accessible and healthy. Returns the PING_RSP grouped by proxy address."> + <results> + <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + </results> + </operation> + <operation name="pingNodeByJVMRoute" displayName="Ping node by JVM Route" + description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Dtermines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> + <parameters> + <c:simple-property required="true" name="jvmRoute" type="string" displayName="JVM Route of node to ping." /> + </parameters> + <results> + <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + </results> + </operation> + <operation name="pingNodeByAddress" displayName="Ping node by address" + description="Ping a node from httpd and returns the PING_RSP grouped by proxy address. Determines whether the node configured with the specified jvm route is accessible from each proxy returning the PING_RSP grouped by proxy address."> + <parameters> + <c:simple-property required="true" name="scheme" type="string" displayName="Scheme (ajp, http, https)" /> + <c:simple-property required="true" name="hostname" type="string" displayName="Name or ip address of a node." /> + <c:simple-property required="true" name="port" type="string" displayName="Port" /> + </parameters> + <results> + <c:simple-property name="result" type="string" description="Map of PING_RPS response, grouped by proxy." /> + </results> + </operation> + + <operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> + <parameters> + <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout" /> + <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:property-options allowCustomValue="false"> + <c:option value="MICROSECONDS" name="MICROSECONDS" /> + <c:option value="MILLISECONDS" name="MILLISECONDS" /> + <c:option value="NANOSECONDS" name="NANOSECONDS" /> + <c:option value="SECONDS" name="SECONDS" /> + <c:option value="HOURS" name="HOURS" /> + <c:option value="DAYS" name="DAYS" /> + </c:property-options> + </c:simple-property> + </parameters> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + + <metric property="ProxyConfiguration" displayName="Proxy Configuration" displayType="summary" dataType="trait" /> + <metric property="ProxyInfo" displayName="Proxy Info" displayType="summary" dataType="trait" /> + </service> + + <service name="Service Configuration" discovery="ClassNameMBeanDiscoveryComponent" class="FileConfiguredMBeanResourceComponent" supportsManualAdd="true" description="HA Service Configuration" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:service=ModCluster" /> + <c:simple-property name="nameTemplate" default="HA Service Configuration" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.ModClusterService" /> + <c:simple-property name="dependencyClassName" readOnly="true" default="org.jboss.modcluster.config.ModClusterConfig" /> + <c:simple-property name="proxyInfoProperty" readOnly="true" default="ProxyInfo" /> + </plugin-configuration> + + <resource-configuration> + <!-- Handler Configuration --> + <c:simple-property name="advertise" type="boolean" required="false" default="false" description="Enable autodiscovery of httpd servers." /> + <c:simple-property name="advertiseGroupAddress" type="string" description="Multicast address on which to listen for advertisements." /> + <c:simple-property name="advertisePort" type="string" required="false" description="Multicast port for discovery" /> + <c:simple-property name="advertiseInterface" type="string" required="false" description="Multicast interface for discovery" /> + <c:simple-property name="advertiseSecurityKey" type="string" required="false" description="Security key for discovery." /> + <c:simple-property name="proxyList" type="string" required="false" description="Comma separated list of address:port listing the httpd servers where mod_cluster is running." /> + <c:simple-property name="proxyURL" type="string" required="false" description="URL prefix to send with commands to mod_cluster. Default is no prefix." /> + <c:simple-property name="socketTimeout" type="integer" required="false" description="Connection timeout for communication with the proxy." /> + <c:simple-property name="ssl" type="boolean" description="Whether to use SSL to communicate with mod_cluster. Note this has nothing to do with handling of https requests by JBoss Web" /> + <c:simple-property name="excludedContexts" type="string" required="false" + description="Comma delimited list of contexts that should *not* be auto-registered with httpd. Contexts may be qualified by host using a colon, e.g. host1:context1. If no host is defined, localhost is assumed." /> + <c:simple-property name="autoEnableContexts" type="boolean" required="false" default="true" description="Toggle for context auto-enable during mod_cluster startup." /> + + <!-- Node Configuration --> + <c:simple-property name="loadBalancingGroup" type="string" required="false" description="Load balancing group." /> + <c:simple-property name="flushPackets" type="boolean" required="false" description="Allows controlling flusing of packets." /> + <c:simple-property name="flushWait" type="integer" required="false" description="Time in ms to wait before flushing packets." /> + <c:simple-property name="ping" type="integer" required="false" description="Time in s to wait for a pong answer to a ping." /> + <c:simple-property name="smax" type="integer" required="false" description="Maximum time on seconds for idle connections above smax." /> + <c:simple-property name="ttl" type="integer" required="false" description="TTL" /> + <c:simple-property name="nodeTimeout" type="integer" required="false" description="Node timeout" /> + <c:simple-property name="balancer" type="string" required="false" description="Name of the balancer" /> + + <!-- Balancer Configuration --> + <c:simple-property name="stickySession" type="boolean" description="Enables sticky session for the node." /> + <c:simple-property name="stickySessionRemove" type="boolean" description="Remove session when the request cannot be routed to the right node for this cluster." /> + <c:simple-property name="stickySessionForce" type="boolean" description="Return an error when the request cannot be routed to the right node." /> + <c:simple-property name="workerTimeout" type="integer" description="Timeout to wait for an available worker (default is no wait)." /> + <c:simple-property name="maxAttempts" type="integer" description="Maximum number of attempts to send the request to the backend server." /> + </resource-configuration> + </service> + <!-- End - Configuration for ModClusterService --> + + <service name="Catalina Service" discovery="org.rhq.plugins.jmx.MBeanResourceDiscoveryComponent" class="ModclusterServerComponent" supportsManualAdd="true" description="Catalina Service Listener" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="Catalina:type=ModClusterListener,*" /> + <c:simple-property name="nameTemplate" default="mod_cluster Catalina Listener" /> + </plugin-configuration> + + <operation name="addProxy" displayName="Add a proxy" description="Add a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="removeProxy" displayName="Remove a proxy" description="Remove a proxy."> + <parameters> + <c:simple-property required="true" name="host" type="string" displayName="Proxy address" /> + <c:simple-property required="true" name="port" type="string" displayName="Proxy port" /> + </parameters> + </operation> + <operation name="disable" displayName="Disable all webpapps" description="Disable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="enable" displayName="Enable all webapps" description="Enable all webapps for all virtual hosts of this application server."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="stop" displayName="Stop all webapps" description="Gracefully stops all webapps for all virtual hosts of this application server."> + <parameters> + <c:simple-property required="true" name="timeout" type="string" displayName="Session draining timeout" /> + <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:property-options allowCustomValue="false"> + <c:option value="MICROSECONDS" name="MICROSECONDS" /> + <c:option value="MILLISECONDS" name="MILLISECONDS" /> + <c:option value="NANOSECONDS" name="NANOSECONDS" /> + <c:option value="SECONDS" name="SECONDS" /> + <c:option value="HOURS" name="HOURS" /> + <c:option value="DAYS" name="DAYS" /> + </c:property-options> + </c:simple-property> + </parameters> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + + <metric property="proxyConfiguration" displayName="Proxy Configuration" displayType="summary" dataType="trait" /> + <metric property="modelerType" displayName="Type of the modeled resource" displayType="summary" dataType="trait" /> + <metric property="className" displayName="Fully qualified class name of the managed object" displayType="summary" dataType="trait" /> + <metric property="advertise" displayName="Enable autodiscovery of httpd servers." displayType="summary" dataType="trait" /> + + <resource-configuration> + <c:simple-property name="workerTimeout" type="integer" description="Timeout to wait for an available worker (default is no wait)." /> + <c:simple-property name="stickySession" type="boolean" description="Enables sticky session for the cluster." /> + <c:simple-property name="stickySessionRemove" type="boolean" description="Remove session when the request cannot be routed to the right node for this cluster." /> + <c:simple-property name="smax" type="integer" description="Maximum time on seconds for idle connections above smax." /> + <c:simple-property name="maxAttempts" type="integer" description="Maximum number of attempts to send the request to the backend server." /> + <c:simple-property name="advertiseSecurityKey" type="string" required="false" description="Security key for discovery." /> + <c:simple-property name="stickySessionForce" type="boolean" description="Return an error when the request cannot be routed to the right node." /> + <c:simple-property name="balancer" type="string" required="false" description="Name of the balancer." /> + <c:simple-property name="flushPackets" type="boolean" description="Allows controlling flusing of packets." /> + <c:simple-property name="socketTimeout" type="integer" description="Connection timeout for communication with the proxy." /> + <c:simple-property name="advertisePort" type="integer" required="false" description="Multicast port for discovery" /> + <c:simple-property name="advertiseGroupAddress" type="string" required="false" description="Multicast address for discovery." /> + <c:simple-property name="flushWait" type="integer" description="Time in ms to wait before flushing packets." /> + <c:simple-property name="ping" type="integer" description="Time in s to wait for a pong answer to a ping." /> + </resource-configuration> + </service> + + <service name="Dynamic Load Balancer Factor" discovery="ClassNameMBeanDiscoveryComponent" class="FileConfiguredMBeanResourceComponent" supportsManualAdd="true" description="Dynamic Load balancer factor for mod_cluster" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:provider=LoadBalanceFactor,service=ModCluster,*" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.load.impl.DynamicLoadBalanceFactorProvider" /> + <c:simple-property name="nameTemplate" default="Dynamic Load Balancer Factor" /> + </plugin-configuration> + + <metric property="Metrics" displayName="Collected Metrics" displayType="summary" dataType="trait" /> + + <resource-configuration> + <c:simple-property name="DecayFactor" type="integer" description="The number of historical load values used to determine load factor." /> + <c:simple-property name="History" type="integer" description="The exponential decay factor for historical load values." /> + </resource-configuration> + </service> + + <service name="Simple Load Balancer Factor" discovery="ClassNameMBeanDiscoveryComponent" class="FileConfiguredMBeanResourceComponent" supportsManualAdd="true" description="Simple load balancer factor for mod_cluster" singleton="true"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:provider=LoadBalanceFactor,service=ModCluster,*" /> + <c:simple-property name="className" readOnly="true" default="org.jboss.modcluster.load.impl.SimpleLoadBalanceFactorProvider" /> + <c:simple-property name="nameTemplate" default="Simple Load Balancer Factor" /> + </plugin-configuration> + + <resource-configuration> + <c:simple-property name="loadBalanceFactor" type="integer" description="The load balance factor." /> + </resource-configuration> + </service> + + <service name="Load Metric" discovery="LoadMetricDiscoveryComponent" class="org.rhq.plugins.jmx.MBeanResourceComponent" description="Load Metric"> + + <plugin-configuration> + <c:simple-property name="objectName" readOnly="true" default="jboss.web:provider=LoadBalanceFactor,service=ModCluster,metric=*,*" /> + <c:simple-property name="nameTemplate" default="Load Metric" /> + </plugin-configuration> + + <metric property="Load" displayName="Load" category="utilization" description="The current load of this metric as a percent of the metric's capacity." dataType="measurement" /> + + <resource-configuration> + <c:simple-property name="Weight" type="integer" description="The significance of this load metric compared to the other metrics." /> + <c:simple-property name="Capacity" type="double" description="Used to normalize the value returned by load expressed as a percentage of the capacity, such that: 0 < (load/capacity) < 1" /> + </resource-configuration> + </service> + + <service name="Webapp Context" discovery="ContextDiscoveryComponent" class="ContextComponent" description="Webapp Context"> + + <operation name="disableContext" displayName="Disable webapp" description="Disable this webapp."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation." /> + </results> + </operation> + <operation name="stopContext" displayName="Stop webapp" description="Gracefully stops this webapp."> <parameters> - <c:simple-property required="true" name="timeout" type="integer" displayName="Session draining timeout"/> - <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> - <c:property-options allowCustomValue="false"> - <c:option value="MICROSECONDS" name="MICROSECONDS"/> - <c:option value="MILLISECONDS" name="MILLISECONDS"/> - <c:option value="NANOSECONDS" name="NANOSECONDS"/> - <c:option value="SECONDS" name="SECONDS"/> - <c:option value="HOURS" name="HOURS"/> - <c:option value="DAYS" name="DAYS"/> - </c:property-options> - </c:simple-property> + <c:simple-property required="true" name="timeout" type="integer" displayName="Session draining timeout" /> + <c:simple-property required="true" name="unit" default="MILLISECONDS" displayName="Time unit of the timeout parameter"> + <c:property-options allowCustomValue="false"> + <c:option value="MICROSECONDS" name="MICROSECONDS" /> + <c:option value="MILLISECONDS" name="MILLISECONDS" /> + <c:option value="NANOSECONDS" name="NANOSECONDS" /> + <c:option value="SECONDS" name="SECONDS" /> + <c:option value="HOURS" name="HOURS" /> + <c:option value="DAYS" name="DAYS" /> + </c:property-options> + </c:simple-property> </parameters> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> - </results> - </operation> - <operation name="enableContext" displayName="Enable webapp" description="Enable this webapp."> - <results> - <c:simple-property name="result" type="boolean" description="The result of the operation" /> - </results> - </operation> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation> + <operation name="enableContext" displayName="Enable webapp" description="Enable this webapp."> + <results> + <c:simple-property name="result" type="boolean" description="The result of the operation" /> + </results> + </operation>
</service> </service> diff --git a/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java new file mode 100644 index 0000000..4e4aac1 --- /dev/null +++ b/modules/plugins/mod-cluster/src/test/java/org/rhq/plugins/modcluster/test/ServerConfigTest.java @@ -0,0 +1,58 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 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.plugins.modcluster.test; + +import org.testng.annotations.Test; + +import org.rhq.plugins.modcluster.config.ModClusterBeanFile; + +public class ServerConfigTest { + + @Test + public void TestConfig() { + + try { + ModClusterBeanFile config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService"); + config.setPropertyValue("processStatusFrequency", "4"); + config.setPropertyValue("test", "5"); + config.setPropertyValue("test", "123"); + + System.out.println(config.getPropertyValue("test")); + + config.saveConfigFile(); + + config = new ModClusterBeanFile("org.jboss.modcluster.ha.HAModClusterService", + "org.jboss.modcluster.config.ha.HAModClusterConfig"); + config.setPropertyValue("processStatusFrequency", "4"); + config.setPropertyValue("test", "5"); + config.setPropertyValue("test", "123"); + + System.out.println(config.getPropertyValue("test")); + + config.saveConfigFile(); + + config.setPropertyValue("test", null); + config.saveConfigFile(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +}
commit 9b57c3ef1e1bc0ee5f88968f4ee32693be048eb3 Author: Stefan Negrea snegrea@redhat.com Date: Sun Aug 14 12:03:44 2011 -0500
With JBoss 5, the timeout is blocking the operation call for the period set. Reduce this period for these integration tests.
diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java index dc98d78..0a39eab 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java +++ b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java @@ -168,7 +168,7 @@ public class ModclusterPluginTest { log.info("Result of operation " + "enableContext" + " was: " + result.getSimpleResult());
Configuration config = new Configuration(); - config.put(new PropertySimple("timeout", "1000")); + config.put(new PropertySimple("timeout", "1")); config.put(new PropertySimple("unit", java.util.concurrent.TimeUnit.SECONDS)); result = ((OperationFacet) resourceComponent).invokeOperation("stopContext", config); log.info("Result of operation stopContext was: " + result.getSimpleResult());
commit 273a8701e0e62f907a3c92fbf9bc47aa5d02c51d Author: Stefan Negrea snegrea@redhat.com Date: Sun Aug 14 12:02:34 2011 -0500
Add jar dependencies for testing with JBoss 5&6.
diff --git a/modules/integration-tests/mod_cluster-plugin-test/pom.xml b/modules/integration-tests/mod_cluster-plugin-test/pom.xml index 0cc3f4f..77a81b2 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/pom.xml +++ b/modules/integration-tests/mod_cluster-plugin-test/pom.xml @@ -17,9 +17,37 @@
<properties> <scm.module.path>modules/integration-tests/mod_cluster-plugin-test</scm.module.path> + <!-- jbossas.version>6.0.0.20100429-M3</jbossas.version--> + <jbossas.version>6.0.0.M1</jbossas.version> + </properties> + + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-parent</artifactId> + <version>${jbossas.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-component-matrix</artifactId> + <version>${jbossas.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement>
<dependencies> + + <dependency> + <groupId>org.jboss.integration</groupId> + <artifactId>jboss-profileservice-spi</artifactId> + <scope>provided</scope> + </dependency>
<dependency> <groupId>${rhq.groupId}</groupId> @@ -41,6 +69,213 @@ <version>1.2.14</version> <scope>provided</scope> </dependency> + + <dependency> + <groupId>org.jboss.naming</groupId> + <artifactId>jnp-client</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.microcontainer</groupId> + <artifactId>jboss-kernel</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-aspects</artifactId> + <version>5.1.0.CR1</version> + <classifier>jboss-aspect-jdk50-client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>trove</groupId> + <artifactId>trove</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>javassist</groupId> + <artifactId>javassist</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.security</groupId> + <artifactId>jboss-security-spi</artifactId> + <scope>test</scope> + </dependency> + + <!-- dependency> + <groupId>org.jboss.javaee</groupId> + <artifactId>jboss-javaee</artifactId> + <scope>test</scope> + </dependency--> + + <dependency> + <groupId>oswego-concurrent</groupId> + <artifactId>concurrent</artifactId> + <version>1.3.4-jboss</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-server</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss</groupId> + <artifactId>jboss-mdr</artifactId> + <scope>test</scope> + </dependency> + + <!-- dependency> + <groupId>org.jboss.logging</groupId> + <artifactId>jboss-logging-spi</artifactId> + <scope>test</scope> + </dependency--> + + <!-- dependency> + <groupId>org.jboss.logging</groupId> + <artifactId>jboss-logging-log4j</artifactId> + <scope>test</scope> + </dependency--> + + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-security</artifactId> + <version>5.1.0.CR1</version> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.integration</groupId> + <artifactId>jboss-transaction-spi</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-common</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-core</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-ext-api</artifactId> + <version>1.0.0</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-proxy-spi</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-proxy-impl</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.ejb3</groupId> + <artifactId>jboss-ejb3-security</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <!-- dependency> + <groupId>org.jboss.microcontainer</groupId> + <artifactId>jboss-dependency</artifactId> + <scope>test</scope> + </dependency--> + + <!-- dependency> + <groupId>org.jboss.security</groupId> + <artifactId>jbosssx-client</artifactId> + <scope>test</scope> + </dependency--> + + <dependency> + <groupId>org.jboss.aspects</groupId> + <artifactId>jboss-security-aspects</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.aop</groupId> + <artifactId>jboss-aop</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss</groupId> + <artifactId>jboss-common-core</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss</groupId> + <artifactId>jboss-reflect</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>jboss</groupId> + <artifactId>jboss-serialization</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.deployers</groupId> + <artifactId>jboss-deployers-core-spi</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.deployers</groupId> + <artifactId>jboss-deployers-client-spi</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-profileservice</artifactId> + <classifier>client</classifier> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.jboss.jbossas</groupId> + <artifactId>jboss-as-server</artifactId> + <classifier>jmx-invoker-adaptor-client</classifier> + <scope>test</scope> + </dependency> + + <!-- dependency> + <groupId>jboss.messaging</groupId> + <artifactId>jboss-messaging-client</artifactId> + <scope>test</scope> + </dependency-->
</dependencies>
commit 324454e90750968aeaee52480f10cef156ac3178 Author: Stefan Negrea snegrea@redhat.com Date: Wed Aug 10 18:04:02 2011 -0500
Get the integration tests to compile and run again by creating the maven module and deploying the correct resources to target folder.
diff --git a/.classpath b/.classpath index cb9d57f..93a80cc 100644 --- a/.classpath +++ b/.classpath @@ -282,5 +282,6 @@ <classpathentry kind="src" path="modules/plugins/jboss-as-7/src/main/java"/> <classpathentry kind="src" path="modules/plugins/jboss-as-7/src/test/java"/> <classpathentry kind="src" path="modules/integration-tests/jboss-as-7-plugin-test/src/test/java"/> + <classpathentry kind="src" path="modules/integration-tests/mod_cluster-plugin-test/src/test/java"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath> diff --git a/modules/integration-tests/mod_cluster-plugin-test/pom.xml b/modules/integration-tests/mod_cluster-plugin-test/pom.xml new file mode 100644 index 0000000..0cc3f4f --- /dev/null +++ b/modules/integration-tests/mod_cluster-plugin-test/pom.xml @@ -0,0 +1,155 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.rhq</groupId> + <artifactId>rhq-plugins-parent</artifactId> + <version>4.1.0-SNAPSHOT</version> + </parent> + + <groupId>org.rhq</groupId> + <artifactId>modcluster-plugin-test</artifactId> + <packaging>jar</packaging> + + <name>RHQ mod_cluster Plugin Integration Test</name> + <description>Integration tests for mod_cluster RHQ Agent plugin</description> + + <properties> + <scm.module.path>modules/integration-tests/mod_cluster-plugin-test</scm.module.path> + </properties> + + <dependencies> + + <dependency> + <groupId>${rhq.groupId}</groupId> + <artifactId>rhq-jmx-plugin</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>${rhq.groupId}</groupId> + <artifactId>modcluster-plugin</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <version>1.2.14</version> + <scope>provided</scope> + </dependency> + + </dependencies> + + <profiles> + + <profile> + <id>integration-tests</id> + <activation> + <property> + <name>maven.test.skip</name> + <value>!true</value> + </property> + </activation> + + <properties> + <rhq.rootDir>../../..</rhq.rootDir> + <rhq.containerDir>${rhq.rootDir}/${rhq.defaultDevContainerPath}</rhq.containerDir> + <rhq.deploymentDir>${rhq.containerDir}/jbossas/server/default/deploy/${rhq.earName}/rhq-downloads/rhq-plugins</rhq.deploymentDir> + </properties> + + <build> + <plugins> + + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <executions> + <execution> + <phase>process-test-resources</phase> + <configuration> + <tasks> + <echo>Setting up plugin dependencies...</echo> + <property name="settings.localRepository" location="${user.home}/.m2/repository" /> + <mkdir dir="target/testsetup" /> + + <mkdir dir="target/testsetup/plugins" /> + <copy toDir="target/testsetup/plugins" flatten="true"> + <fileset dir="${settings.localRepository}/"> + <include name="org/rhq/rhq-platform-plugin/${project.version}/rhq-platform-plugin-${project.version}.jar" /> + <include name="org/rhq/rhq-jmx-plugin/${project.version}/rhq-jmx-plugin-${project.version}.jar" /> + <include name="org/jboss/on/jopr-jboss-as-plugin/${project.version}/jopr-jboss-as-plugin-${project.version}.jar" /> + <include name="org/jboss/on/jopr-jboss-as-5-plugin/${project.version}/jopr-jboss-as-5-plugin-${project.version}.jar" /> + <include name="org/rhq/modcluster-plugin/${project.version}/modcluster-plugin-${project.version}.jar" /> + </fileset> + <fileset dir="${rhq.deploymentDir}"> + <include name="${project.artifactId}-${project.version}.jar" /> + </fileset> + </copy> + + <mkdir dir="target/testsetup/lib" /> + <unzip dest="target/testsetup/lib"> + <fileset dir="${settings.localRepository}/org/hyperic/sigar-dist/${sigar.version}" includes="*.zip" /> + <patternset> + <include name="**/lib/sigar.jar" /> + <include name="**/lib/bcel*.jar" /> + <include name="**/lib/*.so" /> + <include name="**/lib/*.sl" /> + <include name="**/lib/*.dll" /> + <include name="**/lib/*.dylib" /> + </patternset> + </unzip> + <move todir="target/testsetup/lib" flatten="true"> + <fileset dir="target/testsetup/lib"> + <include name="**/lib/*" /> + </fileset> + </move> + <delete dir="target/testsetup/lib/hyperic-sigar-${sigar.version}" /> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <configuration> + <skip>true</skip> + </configuration> + <executions> + <execution> + <id>surefire-it</id> + <phase>integration-test</phase> + <goals> + <goal>test</goal> + </goals> + <configuration> + <skip>${maven.test.skip}</skip> + <excludedGroups>${rhq.testng.excludedGroups}</excludedGroups> + <useSystemClassLoader>false</useSystemClassLoader> + <argLine>-Dorg.hyperic.sigar.path=${basedir}/target/testsetup/lib</argLine> + <systemProperties> + <property> + <name>project.artifactId</name> + <value>${project.artifactId}</value> + </property> + <property> + <name>project.version</name> + <value>${project.version}</value> + </property> + </systemProperties> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> + +</project> diff --git a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java index 0f644fc..dc98d78 100644 --- a/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java +++ b/modules/integration-tests/mod_cluster-plugin-test/src/test/java/org/rhq/plugins/modcluster/test/ModclusterPluginTest.java @@ -148,10 +148,12 @@ public class ModclusterPluginTest { }
if (resourceComponent instanceof OperationFacet) { - OperationResult result = ((OperationFacet) resourceComponent).invokeOperation("reset", null); + OperationResult result = null; + + result = ((OperationFacet) resourceComponent).invokeOperation("reset", new Configuration()); log.info("Result of operation test was: " + result);
- result = ((OperationFacet) resourceComponent).invokeOperation("disable", null); + result = ((OperationFacet) resourceComponent).invokeOperation("disable", new Configuration()); log.info("Result of operation test was: " + result.getSimpleResult()); } } diff --git a/modules/plugins/mod-cluster/pom.xml b/modules/plugins/mod-cluster/pom.xml index ab52e84..fdc4f37 100644 --- a/modules/plugins/mod-cluster/pom.xml +++ b/modules/plugins/mod-cluster/pom.xml @@ -56,51 +56,6 @@ <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> - <execution> - <phase>process-test-resources</phase> - <configuration> - <tasks> - <echo>Setting up plugin dependencies...</echo> - <property name="settings.localRepository" location="${user.home}/.m2/repository" /> - <mkdir dir="target/testsetup" /> - - <mkdir dir="target/testsetup/plugins" /> - <copy toDir="target/testsetup/plugins" flatten="true"> - <fileset dir="${settings.localRepository}/"> - <include name="org/rhq/rhq-platform-plugin/${project.version}/rhq-platform-plugin-${project.version}.jar" /> - <include name="org/rhq/rhq-jmx-plugin/${project.version}/rhq-jmx-plugin-${project.version}.jar" /> - <include name="org/jboss/on/jopr-jboss-as-plugin/${project.version}/jopr-jboss-as-plugin-${project.version}.jar" /> - <include name="org/jboss/on/jopr-jboss-as-5-plugin/${project.version}/jopr-jboss-as-5-plugin-${project.version}.jar" /> - </fileset> - <fileset dir="${rhq.deploymentDir}"> - <include name="${project.artifactId}-${project.version}.jar" /> - </fileset> - </copy> - - <mkdir dir="target/testsetup/lib" /> - <unzip dest="target/testsetup/lib"> - <fileset dir="${settings.localRepository}/org/hyperic/sigar-dist/${sigar.version}" includes="*.zip" /> - <patternset> - <include name="**/lib/sigar.jar" /> - <include name="**/lib/bcel*.jar" /> - <include name="**/lib/*.so" /> - <include name="**/lib/*.sl" /> - <include name="**/lib/*.dll" /> - <include name="**/lib/*.dylib" /> - </patternset> - </unzip> - <move todir="target/testsetup/lib" flatten="true"> - <fileset dir="target/testsetup/lib"> - <include name="**/lib/*" /> - </fileset> - </move> - <delete dir="target/testsetup/lib/hyperic-sigar-${sigar.version}" /> - </tasks> - </configuration> - <goals> - <goal>run</goal> - </goals> - </execution>
<execution> <id>deploy</id> @@ -203,12 +158,10 @@
<build> <plugins> - <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.1</version> <executions> - <execution> <id>deploy</id> <phase>compile</phase> @@ -258,14 +211,10 @@ <goal>run</goal> </goals> </execution> - </executions> </plugin> - </plugins> </build> </profile> - </profiles> - </project>
commit 867eb2edccefc24d4730fdf4e0494dc1dddc94aa Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 25 13:51:35 2011 -0400
add drift to timeline
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventDriftJSON.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventDriftJSON.jsp new file mode 100644 index 0000000..b2f42fb --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventDriftJSON.jsp @@ -0,0 +1,59 @@ +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="java.util.Locale" %> +<%@ page import="org.rhq.core.domain.auth.Subject" %> +<%@ page import="org.rhq.core.domain.util.PageControl" %> +<%@ page import="org.rhq.core.domain.util.PageList" %> +<%@ page import="org.rhq.enterprise.gui.legacy.ParamConstants" %> +<%@ page import="org.rhq.enterprise.gui.legacy.WebUser" %> +<%@ page import="org.rhq.enterprise.gui.legacy.util.SessionUtils" %> +<%@ page import="org.rhq.enterprise.gui.util.WebUtility" %> +<%@ page import="org.rhq.enterprise.server.util.LookupUtil" %> +<%@ page import="org.rhq.core.domain.resource.Resource" %> +<%@ page import="org.rhq.enterprise.server.drift.DriftManagerLocal"%> +<%@ page import="org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria"%> +<%@ page import="org.rhq.core.domain.drift.DriftChangeSet"%> + +<% + int resourceId = WebUtility.getOptionalIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM, -1); + + WebUser user = SessionUtils.getWebUser(request.getSession()); + Subject subject = user.getSubject(); + + long end = Long.parseLong(WebUtility.getRequiredRequestParameter(request, "end")); + long begin = Long.parseLong(WebUtility.getRequiredRequestParameter(request, "begin")); + + DriftManagerLocal driftManager = LookupUtil.getDriftManager(); + GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria(); + criteria.addFilterResourceId(resourceId); + criteria.addFilterCreatedAfter(begin); + criteria.addFilterCreatedBefore(end); + PageList<? extends DriftChangeSet<?>> results = driftManager.findDriftChangeSetsByCriteria(subject, criteria); +%> + +{ "events": [ + +<% + SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.US); + String link = "/coregui/CoreGUI.html#Resource/" + resourceId + "/Drift/ChangeSets"; + String icon = "/images/icons/Drift_16.png"; + boolean first = true; + for (DriftChangeSet entry : results) { + if (!first) { + out.write(",\n"); + } + first = false; +%> + +{ "start" : "<%=sdf.format(entry.getCtime())%>", + "title" : "Drift Detected", + "link" : "<%=link%>", + "description" : "Drift was detected! A change set was created to document the changes.", + "icon" : "<%=icon%>", + "color" : "#3333FF" +} + +<% + } +%> + +]} diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp index 1bbdb2f..1ac93c7 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp @@ -236,6 +236,15 @@ function onLoad() { }); }
+ if (document.forms['show'].drift.checked) { + link = "/resource/common/monitor/events/EventDriftJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + } + if (document.forms['show']['content'].checked) { link = "/resource/common/monitor/events/EventContentJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; Timeline.loadJSON(link, function(json, url) {
commit 4ed859a59e6cb20d417ae7bc4940169bf0194f7c Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 25 13:11:51 2011 -0400
add inventory data to timeline (when resource was discovered and when it was inventoried) clean up the content json jsp a bit get ready for the drift timeline data (still need to create the json jsp)
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icons/Drift_16.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icons/Drift_16.png new file mode 100644 index 0000000..a368ad4 Binary files /dev/null and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icons/Drift_16.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventContentJSON.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventContentJSON.jsp index 673d08e..8edeebe 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventContentJSON.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventContentJSON.jsp @@ -26,7 +26,7 @@
ContentUIManagerLocal contentManager = LookupUtil.getContentUIManager();
- PageList<InstalledPackageHistory> history = contentManager.getInstalledPackageHistoryForResource(resourceId, new PageControl(0,100, new OrderingField("iph.timestamp",PageOrdering.DESC))); + PageList<InstalledPackageHistory> history = contentManager.getInstalledPackageHistoryForResource(resourceId, new PageControl(0,20, new OrderingField("iph.timestamp",PageOrdering.DESC)));
%>
@@ -65,13 +65,18 @@ String link = "#Resource/" + resourceId + "/Content/Deployed"; // "/rhq/resource/content/installed_package_details.xhtml?id=" + resourceId + "¤tPackageId=" + installedPackage.getId();
+ String version = installedPackage.getPackageVersion().getDisplayVersion(); + String username = "-Autodetected-"; + if (installedPackage.getContentServiceRequest() != null) { + username = installedPackage.getContentServiceRequest().getSubjectName(); + } %> { "start" : "<%=sdf.format(new Date(installedPackage.getTimestamp()))%>", "title" : "<% out.write( (installedPackage.getPackageVersion().getDisplayName()==null ? null : installedPackage.getPackageVersion().getDisplayName().replaceAll("["']","")) + " " + (installedPackage.getPackageVersion().getDisplayVersion() ==null ? null : installedPackage.getPackageVersion().getDisplayVersion().replaceAll("["']","")));%>", "link" : "<%=link%>", - "description" : "<b>User:</b> <% out.write((installedPackage.getContentServiceRequest() == null ? "-Detected- " : installedPackage.getContentServiceRequest().getSubjectName().replaceAll("["']","").trim())+"<br/> <b>Version: "+(installedPackage.getPackageVersion().getDisplayVersion() ==null ? null :installedPackage.getPackageVersion().getDisplayVersion().replaceAll("["']","").trim())+" </b> <br/><b>Status:</b> "+installedPackage.getStatus());%>", + "description" : "<b>User:</b> <% out.write(username.replaceAll("["']","").trim()+"<br/> <b>Version:</b> "+(version.replaceAll("["']","").trim())+"<br/><b>Status:</b> "+installedPackage.getStatus());%>", "icon" : "<%=icon%>", "color" : "<%=(installedPackage.getStatus() != InstalledPackageHistoryStatus.FAILED ? "#4EB84E" : "#DD5656")%>" } diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventInventoryJSON.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventInventoryJSON.jsp new file mode 100644 index 0000000..9a3fa9c --- /dev/null +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventInventoryJSON.jsp @@ -0,0 +1,52 @@ +<%@ page import="java.text.SimpleDateFormat" %> +<%@ page import="java.util.Locale" %> +<%@ page import="org.rhq.core.domain.auth.Subject" %> +<%@ page import="org.rhq.core.domain.util.PageControl" %> +<%@ page import="org.rhq.core.domain.util.PageList" %> +<%@ page import="org.rhq.enterprise.gui.legacy.ParamConstants" %> +<%@ page import="org.rhq.enterprise.gui.legacy.WebUser" %> +<%@ page import="org.rhq.enterprise.gui.legacy.util.SessionUtils" %> +<%@ page import="org.rhq.enterprise.gui.util.WebUtility" %> +<%@ page import="org.rhq.enterprise.server.resource.ResourceManagerLocal" %> +<%@ page import="org.rhq.enterprise.server.util.LookupUtil" %> +<%@ page import="org.rhq.core.domain.resource.Resource" %> + +<% + int resourceId = WebUtility.getOptionalIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM, -1); + + WebUser user = SessionUtils.getWebUser(request.getSession()); + Subject subject = user.getSubject(); + + long end = Long.parseLong(WebUtility.getRequiredRequestParameter(request, "end")); + long begin = Long.parseLong(WebUtility.getRequiredRequestParameter(request, "begin")); + + ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); + Resource resource = resourceManager.getResource(subject, resourceId); +%> + +{ "events": [ + + <% + SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.US); + String link = "/coregui/CoreGUI.html#Resource/" + resourceId; + String iconDiscovered = "/images/icons/Inventory_grey_16.png"; + String iconCommitted = "/images/icons/Inventory_16.png"; + %> + +{ "start" : "<%=sdf.format(resource.getCtime())%>", + "title" : "Initial Discovery", + "link" : "<%=link%>", + "description" : "Time when the resource was initially discovered by its managing agent.", + "icon" : "<%=iconDiscovered%>", + "color" : "#A0A0A0" +}, + +{ "start" : "<%=sdf.format(resource.getItime())%>", + "title" : "Committed to Inventory", + "link" : "<%=link%>", + "description" : "Time when the resource was committed to inventory.", + "icon" : "<%=iconCommitted%>", + "color" : "#3333FF" +} + +]} diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp index 6ed2510..1bbdb2f 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp @@ -200,6 +200,15 @@ function onLoad() { }); }
+ if (document.forms['show'].inventory.checked) { + link = "/resource/common/monitor/events/EventInventoryJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + } + if (document.forms['show'].alerts.checked) { link = "/resource/common/monitor/events/EventAlertJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; Timeline.loadJSON(link, function(json, url) { @@ -254,23 +263,30 @@ function onResize() { <span id="event-count" style="display:none;"></span> <div class="controls" id="controls"></div> <form action="#" onsubmit="onLoad()" name="show"> +<table><tr> +<td> <input type="checkbox" name="inventory" checked="checked" onchange="onLoad()" id="inventoryField"/> <label for="inventoryField"><img src="/images/icons/Inventory_grey_16.png"/> Inventory Changes</label> - +</td><td> <input type="checkbox" name="alerts" checked="checked" onchange="onLoad()" id="alertsField"/> <label for="alertsField"><img src="/images/icons/Alert_grey_16.png"/> Alerts</label> - +</td><td> <input type="checkbox" name="events" checked="checked" onchange="onLoad()" id="eventsField"/> <label for="eventsField"><img src="/images/icons/Events_grey_16.png"/> Events</label> - +</td><td> <input type="checkbox" name="configurations" checked="checked" onchange="onLoad()" id="configurationsField"/> <label for="configurationsField"><img src="/images/icons/Configure_grey_16.png"/> Configuration Changes</label> - +</td></tr><tr><td> <input type="checkbox" name="operations" checked="checked" onchange="onLoad()" id="operationsField"/> <label for="operationsField"><img src="/images/icons/Operation_grey_16.png"/> Operations</label> - +</td><td> + <input type="checkbox" name="drift" checked="checked" onchange="onLoad()" id="driftField"/> + <label for="driftField"><img src="/images/icons/Drift_16.png"/> Drift</label> +</td><td> <input type="checkbox" name="content" checked="checked" onchange="onLoad()" id="contentField"/> <label for="contentField"><img src="/images/icons/Content_grey_16.png"/> Content Changes</label> +</td> +</tr></table> </form> -<div id="t1" style='height: 475px; border: 1px solid #aaa'></div> +<div id="t1" style='height: 450px; border: 1px solid #aaa'></div> </body></html> \ No newline at end of file
commit 8c87bf63686df822bec93ad2fdf6183571392412 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 25 12:20:11 2011 -0400
create/delete child history has its own inventory filter - will add more timeline markers for inventory shortly make the timeline icons match the rest of the ui
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java index 4c1c429..5c7a385 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/ImageManager.java @@ -8,6 +8,8 @@ import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.measurement.ResourceAvailability; import org.rhq.core.domain.operation.OperationRequestStatus; +import org.rhq.core.domain.resource.CreateResourceStatus; +import org.rhq.core.domain.resource.DeleteResourceStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceType; @@ -527,4 +529,50 @@ public class ImageManager { public static String getConfigureIcon() { return "subsystems/configure/Configure_16.png"; } + + public static String getChildCreateIcon() { + return "subsystems/inventory/CreateChild_16.png"; + } + + public static String getChildCreateIcon(CreateResourceStatus createStatus) { + if (createStatus == null) { + return getChildCreateIcon(); + } else { + switch (createStatus) { + case SUCCESS: { + return "subsystems/inventory/CreateChild_success_16.png"; + } + case IN_PROGRESS: { + return getChildCreateIcon(); + } + default: { + // all others will use the failure icon + return "subsystems/inventory/CreateChild_failed_16.png"; + } + } + } + } + + public static String getChildDeleteIcon() { + return "subsystems/inventory/DeleteChild_16.png"; + } + + public static String getChildDeleteIcon(DeleteResourceStatus deleteStatus) { + if (deleteStatus == null) { + return getChildDeleteIcon(); + } else { + switch (deleteStatus) { + case SUCCESS: { + return "subsystems/inventory/DeleteChild_success_16.png"; + } + case IN_PROGRESS: { + return getChildDeleteIcon(); + } + default: { + // all others will use the failure icon + return "subsystems/inventory/DeleteChild_failed_16.png"; + } + } + } + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ChildHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ChildHistoryView.java index d5c1ec4..dc835fa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ChildHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ChildHistoryView.java @@ -52,6 +52,7 @@ import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.util.PageControl; 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.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; @@ -65,8 +66,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow; public class ChildHistoryView extends Table<ChildHistoryView.DataSource> {
public static final ViewName VIEW_ID = new ViewName("ChildHistory", MSG.view_tabs_common_child_history()); - public static final String CHILD_CREATED_ICON = "[skin]/images/MultiUploadItem/icon_add_files.png"; - public static final String CHILD_DELETED_ICON = "[skin]/images/MultiUploadItem/icon_remove_files.png"; + public static final String CHILD_CREATED_ICON = ImageManager.getChildCreateIcon(); + public static final String CHILD_DELETED_ICON = ImageManager.getChildDeleteIcon();
private final ResourceComposite resourceComposite; private FormItem dateRangeItem; diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_16.png new file mode 100644 index 0000000..6db0919 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_failed_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_failed_16.png new file mode 100644 index 0000000..5db8573 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_failed_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_success_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_success_16.png new file mode 100644 index 0000000..d9eb649 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/CreateChild_success_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_16.png new file mode 100644 index 0000000..bd45928 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_failed_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_failed_16.png new file mode 100644 index 0000000..33770d2 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_failed_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_success_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_success_16.png new file mode 100644 index 0000000..9948df0 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/inventory/DeleteChild_success_16.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child.png index 5403358..6db0919 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_failed.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_failed.png index 7807270..5db8573 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_failed.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_failed.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_success.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_success.png index 2b475f1..d9eb649 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_success.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_create_child_success.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child.png index 49333cd..bd45928 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_failed.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_failed.png index 570b905..33770d2 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_failed.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_failed.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_success.png b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_success.png index 7e60281..9948df0 100644 Binary files a/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_success.png and b/modules/enterprise/gui/portal-war/src/main/webapp/images/icn_delete_child_success.png differ diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp index e33abdf..6ed2510 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp @@ -191,7 +191,7 @@ function onLoad() { }); }
- if (document.forms['show'].configurations.checked) { + if (document.forms['show'].inventory.checked) { link = "/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; Timeline.loadJSON(link, function(json, url) { eventSource.loadJSON(json, url); @@ -254,6 +254,9 @@ function onResize() { <span id="event-count" style="display:none;"></span> <div class="controls" id="controls"></div> <form action="#" onsubmit="onLoad()" name="show"> + <input type="checkbox" name="inventory" checked="checked" onchange="onLoad()" id="inventoryField"/> + <label for="inventoryField"><img src="/images/icons/Inventory_grey_16.png"/> Inventory Changes</label> + <input type="checkbox" name="alerts" checked="checked" onchange="onLoad()" id="alertsField"/> <label for="alertsField"><img src="/images/icons/Alert_grey_16.png"/> Alerts</label>
commit bdc6f5e72b99f9dcffd6ab4395a6529fa32339e6 Author: John Sanda jsanda@redhat.com Date: Wed Aug 24 22:19:16 2011 -0400
Check to see if a schedule has been removed before sending change set to server
In my previous commit I added support for deleting a drift detection schedule and purging the change set directory. If the deletion occurs while the schedule is still active, DriftDetector finishes its run and the agent could still wind up sending a change set report to the server for a configuration that has been deleted.
This commit adds a check in DriftManager.sendChangeSetToServer to make sure that the schedule has not been deleted before sending the change set to the server.
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 b162149..a3512dc 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 @@ -150,12 +150,15 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri @Override public void sendChangeSetToServer(int resourceId, DriftConfiguration driftConfiguration, DriftChangeSetCategory type) { try { + if (!schedulesQueue.contains(resourceId, driftConfiguration)) { + return; + } + File changeSetFile = changeSetMgr.findChangeSet(resourceId, driftConfiguration.getName(), type); if (changeSetFile == null) { - log - .warn("changeset[resourceId: " + resourceId + ", driftConfiguration: " - + driftConfiguration.getName() - + "] was not found. Cancelling request to send change set to server"); + log.warn("changeset[resourceId: " + resourceId + ", driftConfiguration: " + + driftConfiguration.getName() + "] was not found. Cancelling request to send change set " + + "to server"); return; }
commit ce28e8689a4ec9be87aa6cad3205d8bc7d467e95 Author: John Sanda jsanda@redhat.com Date: Wed Aug 24 20:59:22 2011 -0400
Implmenting DriftManager.unscheduleDriftDetection
This method is called by the server when a drift configuration is deleted on the server. It performs two functions:
1) Deletes the schedule from the queue 2) Deletes the change set directory corresponding to the drift config
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 c550f2d..b162149 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 @@ -53,6 +53,7 @@ import org.rhq.core.pc.measurement.MeasurementManager; import org.rhq.core.util.stream.StreamUtil;
import static org.rhq.core.util.ZipUtil.zipFileOrDirectory; +import static org.rhq.core.util.file.FileUtil.purge;
public class DriftManager extends AgentService implements DriftAgentService, DriftClient, ContainerService {
@@ -127,6 +128,14 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri } }
+ /** + * This method is provided as a test hook. + * @return The schedule queue + */ + ScheduleQueue getSchedulesQueue() { + return schedulesQueue; + } + @Override public void shutdown() { driftThreadPool.shutdown(); @@ -211,7 +220,7 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri
DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId, driftConfiguration); if (schedule == null) { - log.warn("No schedule found in the queue for [resourceId:" + resourceId + ", driftConfigurationId:" + log.warn("No schedule found in the queue for [resourceId: " + resourceId + ", driftConfigurationId: " + driftConfiguration.getId() + ", driftConfigurationName: " + driftConfiguration.getName() + "]. No " + " work will be scheduled."); return; @@ -241,7 +250,24 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri }
@Override - public void unscheduleDriftDetection(int resourceId, DriftConfiguration driftConfiguration) { + public void unscheduleDriftDetection(final int resourceId, final DriftConfiguration driftConfiguration) { + log.debug("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()); + } + }); + + log.debug("Removed " + schedule + " from the schedule queue."); }
@Override 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 374e27e..36fc081 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 @@ -43,6 +43,17 @@ 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. + * + * @param resourceId The resource id of the schedule + * @param config The drift configuration 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. + */ + boolean contains(int resourceId, DriftConfiguration config); + + /** * 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 @@ -72,6 +83,33 @@ public interface ScheduleQueue { DriftDetectionSchedule remove(int resourceId, DriftConfiguration config);
/** + * 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 + * schedule is removed from the queue. If the schedule is active, then <code>task</code> + * will be executed when the schedule is deactivated. If the schedule is not in the + * queue, that is it is neither the active schedule nor waiting in the queue, then + * <code>task</code>is never invoked and is discarded. + * <br/><br/> + * <code>task</code> will only be invoked once regardless of whether or the schedule is + * active or waiting in the queue. + * <br/><br/> + * The reason for accepting a task to execute upon removal of the schedule has to do + * with the active schedule. If a schedule is active, that means it is being processed + * by {@link DriftDetector}. The task may very well involve some clean up work that + * could interfere with {@link DriftDetector}. This approach ensures that the schedule + * 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 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); + + /** * 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 26e2b1a..f944299 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 @@ -8,12 +8,20 @@ import org.rhq.core.domain.drift.DriftConfiguration;
public class ScheduleQueueImpl implements ScheduleQueue {
+ private static final Runnable NO_OP = new Runnable() { + @Override + public void run() { + } + }; + private PriorityQueue<DriftDetectionSchedule> queue = new PriorityQueue<DriftDetectionSchedule>();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private DriftDetectionSchedule activeSchedule;
+ private Runnable deactivationTask; + @Override public DriftDetectionSchedule getNextSchedule() { try { @@ -44,6 +52,9 @@ public class ScheduleQueueImpl implements ScheduleQueue { public void deactivateSchedule() { try { lock.writeLock().lock(); + if (deactivationTask != null) { + deactivationTask.run(); + } if (activeSchedule == null) { return; } @@ -51,6 +62,7 @@ public class ScheduleQueueImpl implements ScheduleQueue { queue.offer(activeSchedule); activeSchedule = null; } finally { + deactivationTask = null; lock.writeLock().unlock(); } } @@ -68,10 +80,35 @@ public class ScheduleQueueImpl implements ScheduleQueue { }
@Override + public boolean contains(int resourceId, DriftConfiguration config) { + if (isActiveSchedule(resourceId, config)) { + return true; + } + try { + lock.readLock().lock(); + for (DriftDetectionSchedule schedule : queue) { + if (schedule.getResourceId() == resourceId && + schedule.getDriftConfiguration().getName().equals(config.getName())) { + return true; + } + } + return false; + } finally { + lock.readLock().unlock(); + } + } + + @Override public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) { + return removeAndExecute(resourceId, config, NO_OP); + } + + @Override + public DriftDetectionSchedule removeAndExecute(int resourceId, DriftConfiguration config, Runnable task) { try { lock.writeLock().lock(); if (isActiveSchedule(resourceId, config)) { + deactivationTask = task; DriftDetectionSchedule removedSchedule = activeSchedule; activeSchedule = null; return removedSchedule; @@ -83,6 +120,7 @@ public class ScheduleQueueImpl implements ScheduleQueue { if (schedule.getResourceId() == resourceId && schedule.getDriftConfiguration().getName().equals(config.getName())) { iterator.remove(); + task.run(); return schedule; } } 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 13fe5ed..5a53ee6 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 @@ -27,11 +27,13 @@ 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.pc.PluginContainerConfiguration; import org.rhq.core.pc.ServerServices;
import static org.rhq.core.util.ZipUtil.unzipFile; 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; @@ -62,6 +64,11 @@ public class DriftManagerTest extends DriftTest { driftMgr.setConfiguration(pcConfig); }
+// @AfterMethod +// public void shutDownDriftManager() { +// driftMgr.shutdown(); +// } + @Test public void writeContentZipFileToChangeSetContentDirectory() throws Exception { String configName = "send-content-in-zip"; @@ -116,6 +123,54 @@ public class DriftManagerTest extends DriftTest { assertThatDirectoryIsEmpty(contentDir); }
+ @Test + public void unschedulingDetectionRemovesScheduleFromQueue() throws Exception { + DriftConfiguration config = driftConfiguration("remove-from-queue", resourceDir.getAbsolutePath()); + + driftMgr.scheduleDriftDetection(resourceId(), config); + driftMgr.scheduleDriftDetection(resourceId() + 5, driftConfiguration("another-config", ".")); + driftMgr.unscheduleDriftDetection(resourceId(), config); + + assertFalse(driftMgr.getSchedulesQueue().contains(resourceId(), config), + new DriftDetectionSchedule(resourceId(), config) + " should have been removed from the schedule queue"); + } + + @Test + public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsNotActive() throws Exception { + DriftConfiguration config = driftConfiguration("delete-changeset-dir", resourceDir.getAbsolutePath()); + File changeSetDir = changeSetDir(config.getName()); + File contentDir = mkdir(changeSetDir, "content"); + + createRandomFile(contentDir, "my_content"); + createRandomFile(changeSetDir, "changeset.txt"); + + driftMgr.scheduleDriftDetection(resourceId(), config); + driftMgr.unscheduleDriftDetection(resourceId(), config); + + assertFalse(changeSetDir.exists(), "The change set directory should have been deleted."); + } + + @Test + public void unschedulingDetectionDeletesChangeSetDirectoryWhenScheduleIsDeactivated() throws Exception { + DriftConfiguration config = driftConfiguration("delete-changeset-dir", resourceDir.getAbsolutePath()); + File changeSetDir = changeSetDir(config.getName()); + File contentDir = mkdir(changeSetDir, "content"); + + createRandomFile(contentDir, "my_content"); + createRandomFile(changeSetDir, "changeset.txt"); + + driftMgr.scheduleDriftDetection(resourceId(), config); + driftMgr.getSchedulesQueue().getNextSchedule(); + driftMgr.unscheduleDriftDetection(resourceId(), config); + + 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."); + } + /** * 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
commit 2c2b08d85b713ad9ff1ff19bf7d689fc8e0b5552 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 24 18:37:56 2011 -0400
Remove dead class for old resource [group] search bar
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java deleted file mode 100644 index 6b6c703..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/menu/SearchBarPane.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2010 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.menu; - -import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.CATEGORY; -import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.DESCRIPTION; -import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.NAME; -import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.PLUGIN; -import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.TYPE; - -import com.google.gwt.user.client.History; -import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.types.TextMatchStyle; -import com.smartgwt.client.widgets.Window; -import com.smartgwt.client.widgets.form.DynamicForm; -import com.smartgwt.client.widgets.form.FormItemIfFunction; -import com.smartgwt.client.widgets.form.fields.ButtonItem; -import com.smartgwt.client.widgets.form.fields.ComboBoxItem; -import com.smartgwt.client.widgets.form.fields.FormItem; -import com.smartgwt.client.widgets.form.fields.SelectItem; -import com.smartgwt.client.widgets.form.fields.SpacerItem; -import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; -import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; -import com.smartgwt.client.widgets.grid.ListGridField; - -import org.rhq.enterprise.gui.coregui.client.LinkManager; -import org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupsDataSource; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDatasource; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; - -/** - * The search bar, which provides the ability to search for Resources or Resource groups. - * - * @author Greg Hinkle - * @author Joseph Marques - */ -public class SearchBarPane extends LocatableHLayout { - - public SearchBarPane(String locatorId) { - super(locatorId); - - setWidth100(); - setHeight(30); - } - - public enum SearchType { - RESOURCE(MSG.view_searchBar_resources()), // - GROUP(MSG.view_searchBar_resourceGroups()); - - private String displayName; - - private SearchType(String displayName) { - this.displayName = displayName; - } - - public String getDisplayName() { - return displayName; - } - - public static String[] getValueMap() { - SearchType[] searchTypes = SearchType.values(); - String[] results = new String[searchTypes.length]; - int i = 0; - for (SearchType nextType : searchTypes) { - results[i++] = nextType.getDisplayName(); - } - return results; - } - } - - @Override - protected void onDraw() { - super.onDraw(); - - final DynamicForm form = new LocatableDynamicForm(this.getLocatorId()); - form.setNumCols(6); - form.setColWidths("120", "140", "400"); - - final SelectItem searchType = new SelectItem("searchType", MSG.common_title_search()); - String[] valueMap = SearchType.getValueMap(); - searchType.setValueMap(valueMap); - searchType.setValue(valueMap[0]); - searchType.setWidth(120); - searchType.addChangedHandler(new ChangedHandler() { - @Override - public void onChanged(ChangedEvent event) { - markForRedraw(); - } - }); - - ComboBoxItem resourceSearch = getResourceComboBox(); - ComboBoxItem groupSearch = getGroupComboBox(); - - ButtonItem search = new ButtonItem("Search", MSG.common_button_search()); - search.setStartRow(false); - search.setEndRow(false); - search.setShowTitle(false); - search.setIcon(Window.getImgURL("[SKIN]/actions/view.png")); - - form.setItems(searchType, resourceSearch, groupSearch, search, new SpacerItem()); - - addMember(form); - } - - private ComboBoxItem getResourceComboBox() { - final ComboBoxItem comboBox = getBaseComboBox(SearchType.RESOURCE); - - ListGridField nameField = ResourceDataSourceField.NAME.getListGridField(250); - ListGridField descriptionField = ResourceDataSourceField.DESCRIPTION.getListGridField(); - ListGridField typeNameField = ResourceDataSourceField.TYPE.getListGridField(130); - ListGridField pluginNameField = ResourceDataSourceField.PLUGIN.getListGridField(100); - ListGridField categoryField = ResourceDataSourceField.CATEGORY.getListGridField(60); - ListGridField availabilityField = ResourceDataSourceField.AVAILABILITY.getListGridField(55); - availabilityField.setAlign(Alignment.CENTER); - - comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField, - availabilityField); - - comboBox.setValueField("id"); - comboBox.setDisplayField(ResourceDataSourceField.NAME.propertyName()); - comboBox.setOptionDataSource(new ResourceDatasource()); - - return comboBox; - } - - private ComboBoxItem getGroupComboBox() { - final ComboBoxItem comboBox = getBaseComboBox(SearchType.GROUP); - - ListGridField nameField = NAME.getListGridField(250); - ListGridField descriptionField = DESCRIPTION.getListGridField(); - ListGridField typeNameField = TYPE.getListGridField(130); - ListGridField pluginNameField = PLUGIN.getListGridField(100); - ListGridField categoryField = CATEGORY.getListGridField(105); - - comboBox.setPickListFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField); - - comboBox.setValueField("id"); - comboBox.setDisplayField(NAME.propertyName()); - comboBox.setOptionDataSource(new ResourceGroupsDataSource()); - - return comboBox; - } - - private ComboBoxItem getBaseComboBox(final SearchType searchType) { - final ComboBoxItem comboBox = new ComboBoxItem("query", MSG.view_searchBar_query()); - comboBox.setWidth(400); - comboBox.setShowTitle(false); - comboBox.setHint(MSG.common_title_search().toLowerCase()); - comboBox.setShowHintInField(true); - - comboBox.setPickListWidth(800); - comboBox.setTextMatchStyle(TextMatchStyle.SUBSTRING); - comboBox.setCompleteOnTab(true); - - comboBox.addChangedHandler(new ChangedHandler() { - public void onChanged(ChangedEvent changedEvent) { - com.allen_sauer.gwt.log.client.Log.debug("ChangedEvent: " + changedEvent.getValue()); - - Object intermediate = changedEvent.getValue(); - if (!(intermediate instanceof Integer)) { - return; - } - - Integer id = (Integer) changedEvent.getValue(); - comboBox.setValue(""); - - String link; - if (searchType == SearchType.RESOURCE) { - link = LinkManager.getResourceLink(id); - } else if (searchType == SearchType.GROUP) { - link = LinkManager.getResourceGroupLink(id); - } else { - throw new IllegalArgumentException("There is no global search type for " + searchType); - } - - if (!link.contains("#")) { - com.google.gwt.user.client.Window.Location.assign(link); - } else { - History.newItem(link.substring(1)); - } - } - }); - - comboBox.setShowIfCondition(new FormItemIfFunction() { - public boolean execute(FormItem formItem, Object o, DynamicForm dynamicForm) { - String value = dynamicForm.getValueAsString("searchType"); - return (null != value && value.equals(searchType.getDisplayName())); - } - }); - - return comboBox; - } - -}
commit 2074f8fdd5ae0310cc171552a4d0a82a56ddef7c Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 24 18:37:19 2011 -0400
Search Bar work [BZ 695889] More to do but the search bar is getting more usable: - A lot of css tweaks to get sizings such that the saved search name text box and label are shown correctly. - Fixes to saved search CRUD, simplify certain things - Add I18N, this stuff still used string literals - remove some unused widgets still being built/used but not useful
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java index 7ec3956..12df81d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/FlexSearchBar.java @@ -103,7 +103,6 @@ public class FlexSearchBar extends AbstractSearchBar { HorizontalPanel sbc_sbbgc_sbcc_sbcrhs_aic; HorizontalPanel sbc_sbbgc_sbcc_sbcrhs_sic; HorizontalPanel sbc_sbbgc_sbcc_sbcrhs_pnfc; - HorizontalPanel sbc_sbbgc_sbcc_sbcrhs; HorizontalPanel sbc_sbbgc_sbcc_sbcrhs_pnlc; HorizontalPanel sbc_sbbc; HorizontalPanel sbc_pfsc; @@ -142,18 +141,16 @@ public class FlexSearchBar extends AbstractSearchBar { sbc_sbbgc_sbcc_sbclhs_pfc = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentLHS", "patternFieldContainer"); sbc_sbbgc_sbcc_sbcrhs_aic = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", "arrowImageContainer"); sbc_sbbgc_sbcc_sbcrhs_sic = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", "starImageContainer"); - sbc_sbbgc_sbcc_sbcrhs_pnfc = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", "starImageContainer"); - sbc_sbbgc_sbcc_sbcrhs = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", null); - sbc_sbbgc_sbcc_sbcrhs_pnlc = createHPanel(sbc_sbbgc_sbcc_sbcrhs, "rounded", "patternNameLabelContainer"); - sbc_sbbc = createHPanel(sbc, "searchBarButtonContainer", "searchButtonContainer"); + sbc_sbbgc_sbcc_sbcrhs_pnfc = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", "patternNameFieldContainer"); + sbc_sbbgc_sbcc_sbcrhs_pnlc = createHPanel(sbc_sbbgc_sbcc, "searchBarComponentRHS", "patternNameLabelContainer"); sbc_pfsc = createHPanel(sbc, null, "patternFieldSuggestionsContainer"); sbc_ssc = createHPanel(sbc, null, "savedSearchesContainer");
sbc_sbbgc_sbcc_sbclhs_pfc.add(autoCompletePatternField); - sbc_sbbgc_sbcc_sbcrhs_pnfc.add(patternNameField); - sbc_sbbgc_sbcc_sbcrhs_pnlc.add(patternNameLabel); sbc_sbbgc_sbcc_sbcrhs_sic.add(starImage); sbc_sbbgc_sbcc_sbcrhs_aic.add(arrowImage); + sbc_sbbgc_sbcc_sbcrhs_pnfc.add(patternNameField); + sbc_sbbgc_sbcc_sbcrhs_pnlc.add(patternNameLabel); sbc_ssc.add(savedSearchesPanel);
initWidget(sbc); @@ -173,7 +170,8 @@ public class FlexSearchBar extends AbstractSearchBar { Integer savedSearchId = Integer.valueOf(getDefaultSavedSearchPatternId()); activateSavedSearch(savedSearchId); } catch (Exception e) { - this.autoCompletePatternField.setText(MSG.view_searchBar_error_selectSavedSearch()); + this.autoCompletePatternField.setText(MSG + .view_searchBar_savedSearch_failFind(getDefaultSavedSearchPatternId())); } } } @@ -252,7 +250,7 @@ public class FlexSearchBar extends AbstractSearchBar { savedSearchesGrid.addStyleName("savedSearchesPanel");
// panel position will be re-calculated on down-arrow click - savedSearchesPanel.show(); + //savedSearchesPanel.show(); savedSearchesPanel.hide();
SavedSearchesEventHandler handler = new SavedSearchesEventHandler(); @@ -270,20 +268,7 @@ public class FlexSearchBar extends AbstractSearchBar { arrowImage.setVisible(true); patternNameField.setVisible(false);
- if (name.equals("")) { - GWTServiceLookup.getSearchService().deleteSavedSearch(currentSearchId, new AsyncCallback<Void>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Saved search removal failed", caught); - } - - @Override - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Removed saved search successfully", Severity.Info)); - currentSearchId = 0; - } - }); - + if ("".equals(name)) { starImage.setUrl(STAR_OFF_URL); } else { // NOTE: currently do not support updated a saved search pattern @@ -293,9 +278,11 @@ public class FlexSearchBar extends AbstractSearchBar { } else if (nameJustUpdated) { updateSavedSearchName(currentSearchId, name); } + + starImage.setUrl(STAR_ON_URL); patternNameLabel.setText(elipse(name)); patternNameLabel.setVisible(true); - starImage.setUrl(STAR_ON_URL); + autoCompletePatternField.setFocus(true); } }
@@ -308,7 +295,7 @@ public class FlexSearchBar extends AbstractSearchBar {
private String elipse(String data) { if (data.length() > 14) { - return data.substring(0, 14) + "..."; + return data.substring(0, 20) + "..."; } return data; } @@ -319,13 +306,14 @@ public class FlexSearchBar extends AbstractSearchBar { GWTServiceLookup.getSearchService().createSavedSearch(newSavedSearch, new AsyncCallback<Integer>() { @Override public void onSuccess(Integer newSavedSearchId) { - CoreGUI.getMessageCenter().notify(new Message("Saved search created successfully", Severity.Info)); + CoreGUI.getMessageCenter() + .notify(new Message(MSG.view_searchBar_savedSearch_save(name), Severity.Info)); currentSearchId = newSavedSearchId; }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Saved search creation failed", caught); + CoreGUI.getErrorHandler().handleError(MSG.view_searchBar_savedSearch_failSave(name), caught); } }); } @@ -335,13 +323,14 @@ public class FlexSearchBar extends AbstractSearchBar { @Override public void onSuccess(Boolean hadUpdates) { if (hadUpdates) { - CoreGUI.getMessageCenter().notify(new Message("Saved search successfully renamed", Severity.Info)); + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_searchBar_savedSearch_rename(newName), Severity.Info)); } }
@Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Saved search rename failed", caught); + CoreGUI.getErrorHandler().handleError(MSG.view_searchBar_savedSearch_failRename(newName), caught); } }); } @@ -423,35 +412,30 @@ public class FlexSearchBar extends AbstractSearchBar { return; }
+ // note - since hover changes off to active, we never have the star off case here if (starImage.getUrl().endsWith(STAR_ACTIVE_URL)) { - patternNameField.setText(DEFAULT_PATTERN_NAME); - patternNameField.setVisible(true); - patternNameField.selectAll(); - patternNameField.setFocus(true); - patternNameLabel.setVisible(false); + if (patternNameField.isVisible()) { + patternNameField.setVisible(false); + + } else { + patternNameField.setText(DEFAULT_PATTERN_NAME); + patternNameField.setVisible(true); + patternNameField.selectAll(); + patternNameField.setFocus(true); + patternNameLabel.setVisible(false); + + } } else if (starImage.getUrl().endsWith(STAR_ON_URL)) { starImage.setUrl(STAR_ACTIVE_URL); patternNameField.setVisible(false); patternNameLabel.setVisible(false); - GWTServiceLookup.getSearchService().deleteSavedSearch(currentSearchId, new AsyncCallback<Void>() { - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Saved search deletion failure", caught); - } - - @Override - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Saved search deletion success", Severity.Info)); - currentSearchId = 0; - } - }); } }
public void onMouseOver(MouseOverEvent event) { - if (starImage.getUrl().endsWith(STAR_OFF_URL)) { - starImage.setUrl(STAR_ACTIVE_URL); + if (starImage.getUrl().endsWith(STAR_OFF_URL) && !"".equals(getValue().trim())) {
+ starImage.setUrl(STAR_ACTIVE_URL); } }
@@ -494,11 +478,13 @@ public class FlexSearchBar extends AbstractSearchBar { GWTServiceLookup.getSearchService().deleteSavedSearch(savedSearch.getId(), new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Saved search deletion failure", caught); + CoreGUI.getErrorHandler().handleError( + MSG.view_searchBar_savedSearch_failDelete(savedSearch.getName()), caught); }
@Override public void onSuccess(Void result) { + // handle deletion of current saved search if (currentSearchId == savedSearch.getId()) { currentSearchId = 0; patternNameField.setValue("", true); @@ -510,11 +496,15 @@ public class FlexSearchBar extends AbstractSearchBar { savedSearchesPanel.hide(); }
- // is user deleting the one and only element in the list? + // handle deletion of the one and only element in the list if (savedSearchesGrid.size() == 1) { savedSearchesPanel.hide(); } + savedSearchesGrid.removeRow(rowIndex); + + CoreGUI.getMessageCenter().notify( + new Message(MSG.view_searchBar_savedSearch_delete(savedSearch.getName()), Severity.Info)); } }); } else { @@ -543,21 +533,16 @@ public class FlexSearchBar extends AbstractSearchBar { new AsyncCallback<List<SavedSearch>>() { @Override public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failure to select saved search", caught); + CoreGUI.getErrorHandler().handleError(MSG.view_searchBar_savedSearch_failFind(savedSearchName), + caught); }
@Override public void onSuccess(List<SavedSearch> results) { if (results.size() == 0) { CoreGUI.getMessageCenter().notify( - new Message("Could not find saved search with name [" + savedSearchName + "]", - Severity.Error)); + new Message(MSG.view_searchBar_savedSearch_failFind(savedSearchName), Severity.Error)); } else { - if (results.size() > 1) { - CoreGUI.getMessageCenter().notify( - new Message("Found multiple saves searched with name [" + savedSearchName - + "], loaded the first one", Severity.Warning)); - } SavedSearch savedSearch = results.get(0); activateSavedSearch(savedSearch); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java index 007f908..8e9b7b3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/SearchBar.java @@ -194,7 +194,8 @@ public class SearchBar extends AbstractSearchBar { Integer savedSearchId = Integer.valueOf(defaultSavedSearchPatternId); activateSavedSearch(savedSearchId); } catch (Exception e) { - this.autoCompletePatternField.setText(MSG.view_searchBar_error_selectSavedSearch()); + this.autoCompletePatternField.setText(MSG + .view_searchBar_savedSearch_failFind(defaultSavedSearchPatternId)); click(searchButton); // execute the search, which will help to further highlight the error } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java index fac1c35..6c8ce1b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SearchGWTServiceImpl.java @@ -24,7 +24,6 @@ import org.rhq.core.domain.criteria.SavedSearchCriteria; import org.rhq.core.domain.search.SavedSearch; import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.core.domain.search.SearchSuggestion; -import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.SearchGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.search.SavedSearchManagerLocal; 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 2c97890..4362b8f 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 @@ -1623,11 +1623,13 @@ view_resource_monitor_table_min = Minimum view_resource_title_component_errors_tooltip = Shows managed component errors. Click for details view_resource_title_tagUpdateFailed = Failed to update resource tags view_searchBar_defaultPattern = name your pattern -view_searchBar_error_selectSavedSearch = ''Error selecting saved search'' -view_searchBar_query = Query -view_searchBar_resourceGroups = Resource Groups -view_searchBar_resources = Resources -view_searchBar_welcomeMessage = search for {0}s +view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}] +view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}] +view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}] +view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}] +view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}] +view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}] +view_searchBar_savedSearch_save = Successfully created saved search [{0}] view_searchGUI_loginStatus = Unable to determine login status, check server status view_selector_assigned = Assigned {0} view_selector_available = Available {0} 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 8710e11..581c8cb 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 @@ -1349,11 +1349,13 @@ view_resource_monitor_table_min = Minimum view_resource_title_component_errors_tooltip = Zeigt Fehler der gemanagten Ressource. Klicken fÃŒr Details view_resource_title_tagUpdateFailed = Fehler beim Aktualisieren der Ressourcen-Tags view_searchBar_defaultPattern = name your pattern~ -view_searchBar_error_selectSavedSearch = ''Error selecting saved search''~ -view_searchBar_query = Query~ -view_searchBar_resourceGroups = Ressource-Gruppen -view_searchBar_resources = Ressourcen -view_searchBar_welcomeMessage = search for {0}s~ +##view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}] +##view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}] +##view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}] +##view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}] +##view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}] +##view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}] +##view_searchBar_savedSearch_save = Successfully created saved search [{0}] view_searchGUI_loginStatus = Unable to determine login status, check server status~ view_selector_assigned = Zugewiesen {0} view_selector_available = VerfÃŒgbar {0} 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 907f6f2..67762d3 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 @@ -1590,11 +1590,13 @@ view_resource_monitor_table_min = æå° view_resource_title_component_errors_tooltip = 管çã³ã³ããŒãã³ããšã©ãŒã®è¡šç€ºã詳现ã¯ã¯ãªãã¯ããŠãã ãã view_resource_title_tagUpdateFailed = ãªãœãŒã¹ã¿ã°ã®æŽæ°ã«å€±æããŸãã view_searchBar_defaultPattern = ãã¿ãŒã³ãååãä»ããŠãã ãã -view_searchBar_error_selectSavedSearch = ''ä¿åãããæ€çŽ¢ã®éžæäžã®ãšã©ãŒ'' -view_searchBar_query = åãåãã -view_searchBar_resourceGroups = ãªãœãŒã¹ã°ã«ãŒã -view_searchBar_resources = ãªãœãŒã¹ -view_searchBar_welcomeMessage = {0} ã®ããã®æ€çŽ¢ +##view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}] +##view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}] +##view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}] +##view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}] +##view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}] +##view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}] +##view_searchBar_savedSearch_save = Successfully created saved search [{0}] view_searchGUI_loginStatus = ãã°ã€ã³ã¹ããŒã¿ã¹ã確å®ã§ããŸããããµãŒããŒã®ç¶æ ã調ã¹ãŠãã ãã view_selector_assigned = å²ãåœãŠããã {0} view_selector_available = å©çšå¯èœãª {0} 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 f8e28da..27312f7 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 @@ -1728,11 +1728,13 @@ view_resource_monitor_table_min = Minimum view_resource_title_component_errors_tooltip = Shows managed component errors. Click for details view_resource_title_tagUpdateFailed = Failed to update resource tags view_searchBar_defaultPattern = definir nome para o padr\u00E3o -view_searchBar_error_selectSavedSearch = ''Erro ao selecionar a pesquisa'' -view_searchBar_query = Pesquisa -view_searchBar_resourceGroups = Grupos de Recursos -view_searchBar_resources = Recursos -view_searchBar_welcomeMessage = procurar por {0}s +##view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}] +##view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}] +##view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}] +##view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}] +##view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}] +##view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}] +##view_searchBar_savedSearch_save = Successfully created saved search [{0}] view_searchGUI_loginStatus = Imposs\u00EDvel determinar o status do login, verifique o status do servidor view_selector_assigned = Associado {0} view_selector_available = Dispon\u00EDvel {0} 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 afd099e..9b9fab0 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 @@ -1598,11 +1598,13 @@ view_resource_monitor_table_min = \u6700\u5c0f view_resource_title_component_errors_tooltip = \u663e\u793a\u88ab\u7ba1\u7ec4\u4ef6\u9519\u8bef.\u5355\u51fb\u67e5\u770b\u8be6\u60c5 view_resource_title_tagUpdateFailed = \u66f4\u65b0\u8d44\u6e90\u6807\u7b7e\u5931\u8d25 view_searchBar_defaultPattern = \u5b9a\u4e49\u81ea\u5df1\u7684\u6837\u5f0f -view_searchBar_error_selectSavedSearch = ''\u9009\u62e9\u4fdd\u5b58\u7684\u641c\u7d22\u65f6\u51fa\u9519'' -view_searchBar_query = \u67e5\u8be2 -view_searchBar_resourceGroups = \u8d44\u6e90\u7ec4 -view_searchBar_resources = \u8d44\u6e90 -view_searchBar_welcomeMessage = \u641c\u7d22\u4e86{0}\u79d2 +##view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}] +##view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}] +##view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}] +##view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}] +##view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}] +##view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}] +##view_searchBar_savedSearch_save = Successfully created saved search [{0}] view_searchGUI_loginStatus = \u65e0\u6cd5\u786e\u5b9a\u767b\u5f55\u72b6\u6001\uff0c\u8bf7\u68c0\u67e5\u670d\u52a1 view_selector_assigned = \u6307\u5b9a\u7684 {0} view_selector_available = \u53ef\u7528\u7684 {0} diff --git a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css index 45b13f3..f4c8390 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/css/search.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/css/search.css @@ -8,58 +8,12 @@ div { margin-left: auto; }
-.searchButton { - display: block; - font-size: 13px; - white-space: nowrap; -} - - -/* - * - * pattern field items - * - */ - -.patternField { - font-size: 13px; - font-family: arial, sans-serif; - width: 675px; - padding: 0; - margin: 0; - border-color: white; - border-style: none; - outline: none; - z-index: 999999; -} - -.patternNameLabel { - background-color: rgb(192, 236, 207); - color: rgb(51, 106, 63); - font-weight: bold; - white-space: nowrap; - text-align: center; - border-style: none; - font-size: 11px; - width: 125px; - z-index: 999999; -} - -.patternNameField { - font-size: 11px; - color: green; - width: 125px; - white-space: no-wrap; - border-color: gray; - border-style: dotted; - border-width: thin; - outline: none; - z-index: 999999; -} - - /* + * * search container elements + * searchBarContainer width is the total width of the search bar. + * searchBarBackgroundContainer is the available width for the components inside (takes into consideration RHS padding) + * */
.searchBarContainer { @@ -93,22 +47,68 @@ div { .searchBarComponentLHS { background-color: white; float: left; - width: 200px; + /* width: 200px; */ }
.searchBarComponentRHS { background-color: white; float: right; - padding-right: 5px; + padding-right: 4px; padding-top: 2px; }
-.searchBarButtonContainer { - float: right; - padding: 5px 5px 0 0; + +/* + * + * pattern field items + * patternField is the current pattern, its width is the max visible portion + * patternNameField is the the edit box when naming a saved search, its width is the max visible portion (less the border) + * patternNameLabel is for displaying the saved search name when a saved search is selected + * + * - the combined width of patternField + patternNameField + all other RHS components (the star and + * arrow images) must equal the width of searchBarBackgroundContainer in order for everything to be seen when + * patternNameField (or patternNameLabel) are being shown. + * - the width of patternNameField and patternNameLabel must be the same. + * + */ + +.patternField { + font-size: 13px; + font-family: arial, sans-serif; + width: 600px; + padding: 0; margin: 0; + border-color: white; + border-style: none; + outline: none; + z-index: 999999; +} + +.patternNameField { + font-size: 11px; + color: green; + width: 150px; + white-space: no-wrap; + border-color: gray; + border-style: dotted; + border-width: thin; + outline: none; + z-index: 999999; +} + +.patternNameLabel { + background-color: rgb(192, 236, 207); + color: rgb(51, 106, 63); + font-weight: bold; + white-space: nowrap; + text-align: left; + border-style: none; + font-size: 11px; + width: 150px; + z-index: 999999; }
+ /* * * saved search items @@ -153,7 +153,7 @@ div { }
.savedSearchesPanel-top { - color: green; + font-size: 12px; position: relative; padding: 0; margin: 0; @@ -161,7 +161,7 @@ div { }
.savedSearchesPanel-bottom { - font-size: 16px; + color: green; position: relative; padding: 0; margin: 0; @@ -172,6 +172,7 @@ div { /* * * suggest items + * suggestPanel spans the width of the container, all of the relevant widths must equal that of .searchBarBackgroundContainer * */
@@ -216,13 +217,15 @@ div { /* * Rounded Corners * http://articles.sitepoint.com/article/rounded-corners-css-javascript + * + * Applied to the patternNameLabel, so the width should be set the same */
div.rounded { /* just a container for rounded2 div replacement algorithm */ } div.rounded2 { - width: 125px; + width: 150px; z-index: 999999; background: rgb(192, 236, 207) url(/coregui/images/search/corner-upper-right-8.png) no-repeat top right; }
commit 0d9d7a77a9fd4d492e6868011f047e17241b7840 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 24 17:36:22 2011 -0400
go to the child history page when link is clicked
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp index c72cc59..c1d3df5 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp @@ -58,7 +58,7 @@ icon = "/images/icn_create_child.png"; // TODO }
- String link = "/coregui/CoreGUI.html#Resource/" + resourceId ; + String link = "/coregui/CoreGUI.html#Resource/" + resourceId + "/Inventory/ChildHistory";
%>
@@ -95,7 +95,7 @@ icon = "/images/icn_delete_child.png"; // TODO }
- String link = "/coregui/CoreGUI.html#Resource/" + resourceId ; + String link = "/coregui/CoreGUI.html#Resource/" + resourceId + "/Inventory/ChildHistory";
%> { "start" : "<%=sdf.format(entry.getCreatedTime())%>",
commit 4f844d0b711924e5be7fe438a64146317efc3e3d Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 24 17:27:40 2011 -0400
remove the extra Condition line. we need a better utility to string-i-fy the alert, but for now, just use name and value
diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventAlertJSON.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventAlertJSON.jsp index f4b9194..978c62e 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventAlertJSON.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventAlertJSON.jsp @@ -58,7 +58,6 @@ StringBuilder buf = new StringBuilder(); for (AlertConditionLog log : alert.getConditionLogs()) { buf.append("<b>Condition:</b>" + log.getCondition().getName() + "<br/>"); - buf.append("<b>Condition:</b>" + log.getCondition().getThreshold() + "<br/>"); buf.append("<b>Value:</b>" + log.getValue() + "</b>"); }
commit 53da278317ccf5c148286ad2ab7db903684c0ad2 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 24 16:28:06 2011 -0400
while working on BZ 713750 - put the controls at the top and use the GWT time range editor. fix the bug where clicking a check box in a control duplicates the filters (that's what the jsp's removeAllChildren is about)
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 f97d6a8..b6aa0fb 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 @@ -71,6 +71,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitorin import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.history.ResourceOperationHistoryListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleListView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary.ActivityView; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary.TimelineView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.message.Message;
@@ -315,8 +316,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo updateSubTab(this.summaryTab, this.summaryTimeline, true, true, new ViewFactory() { @Override public Canvas createView() { - return new FullHTMLPane(summaryTimeline.extendLocatorId("View"), - "/rhq/resource/summary/timeline-plain.xhtml?id=" + resource.getId()); + return new TimelineView(summaryTimeline.extendLocatorId("View"), resourceComposite); } }); } @@ -606,7 +606,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo new AsyncCallback<PageList<ResourceComposite>>() { public void onFailure(Throwable caught) { Message message = new Message(MSG.view_inventory_resource_loadFailed(String.valueOf(resourceId)), - Message.Severity.Warning); + Message.Severity.Warning); CoreGUI.goToView(InventoryView.VIEW_ID.getName(), message); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/TimelineView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/TimelineView.java new file mode 100644 index 0000000..eff1281 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/TimelineView.java @@ -0,0 +1,66 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 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.inventory.resource.detail.summary; + +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.components.FullHTMLPane; +import org.rhq.enterprise.gui.coregui.client.components.measurement.UserPreferencesMeasurementRangeEditor; +import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * @author John Mazzitelli + */ +public class TimelineView extends LocatableVLayout { + public static final ViewName VIEW_ID = new ViewName("ResourceTimeline", MSG.view_tabs_common_timeline()); + + private final ResourceComposite resourceComposite; + + public TimelineView(String locatorId, ResourceComposite resourceComposite) { + super(locatorId); + this.resourceComposite = resourceComposite; + + setMargin(10); + setMembersMargin(1); + } + + @Override + protected void onDraw() { + final FullHTMLPane timelinePane = new FullHTMLPane(extendLocatorId("Timeline"), + "/resource/common/monitor/events/EventsView.jsp?id=" + resourceComposite.getResource().getId()); + + // we create a simple subclass because we need to know when a new range has been set in order to refresh the timeline + class RangeEditor extends UserPreferencesMeasurementRangeEditor { + RangeEditor(String editorLocatorId) { + super(editorLocatorId); + } + + @Override + public void setMetricRangeProperties(MetricRangePreferences prefs) { + super.setMetricRangeProperties(prefs); + timelinePane.redraw(); + } + } + + RangeEditor range = new RangeEditor(extendLocatorId("TimeRangeEditor")); + addMember(range); // put it at the top above the timeline's filters + addMember(timelinePane); + } +} diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp index e964274..e33abdf 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/resource/common/monitor/events/EventsView.jsp @@ -18,25 +18,24 @@ --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> - <head> - <base target="_top"/> - - <script type="text/javascript"> - SimileAjax_urlPrefix = "/js/timeline/ajax/api/"; - </script> - <script src="/js/timeline/ajax/api/simile-ajax-api.js" type="text/javascript"></script> - <script src="/js/timeline/api/timeline-api.js" type="text/javascript"></script> - <script src="/js/timeline/examples/examples.js" type="text/javascript"></script> - <title>Simple jsp page</title> - - <style type="text/css"> - .timeline-band-layer-inner { font-size: smaller; } - .table-start-label { font-size: smaller; } - </style> - <link rel="stylesheet" type="text/css" media="screen" href="/css/win.css"/> - <link rel="stylesheet" type="text/css" media="screen" href="/css/form-style.css"/> - </head> - <% +<head> + <base target="_top"/> + <script type="text/javascript"> + SimileAjax_urlPrefix = "/js/timeline/ajax/api/"; + </script> + <script src="/js/timeline/ajax/api/simile-ajax-api.js" type="text/javascript"></script> + <script src="/js/timeline/api/timeline-api.js" type="text/javascript"></script> + <script src="/js/timeline/examples/examples.js" type="text/javascript"></script> + <title></title> + + <style type="text/css"> + .timeline-band-layer-inner { font-size: smaller; } + .table-start-label { font-size: smaller; } + </style> + <link rel="stylesheet" type="text/css" media="screen" href="/css/win.css"/> + <link rel="stylesheet" type="text/css" media="screen" href="/css/form-style.css"/> +</head> +<% int eventId = WebUtility.getOptionalIntRequestParameter(request, "eventId", -1); int resourceId = WebUtility.getOptionalIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM, -1);
@@ -47,47 +46,28 @@ MetricRangePreferences rangePreferences = preferences.getMetricRangePreferences(); long begin = rangePreferences.begin; long end = rangePreferences.end; - - // System.out.println("Displaying from " + new Date(begin) + " to " + new Date(end)); -// long end = System.currentTimeMillis(); -// long begin = end - (1000L * 60 * 60 * 24); - - + // System.out.println("Displaying timeline from " + new Date(begin) + " to " + new Date(end));
AvailabilityManagerLocal availabilityManager = LookupUtil.getAvailabilityManager(); - List<Availability> availabilities = availabilityManager.findAvailabilityWithinInterval(resourceId, new Date(begin), new Date(end)); - - %>
- <body onload="onLoad();" onresize="onResize();"> +<div id="loading" style="position: absolute; left:40%; top: 40%;z-index: 10"><img src="/images/LoadingEvents.png" alt="Loading..."/></div>
-<div id="loading" style="position: absolute; left:40%; top: 40%;z-index: 10"><img src="/images/LoadingEvents.png" alt="Loading events"/></div> - -<form action="#" onsubmit="onLoad()" name="show"> -<input type="checkbox" name="alerts" checked="checked" onchange="onLoad()" id="alertsField"/> - <label for="alertsField"><img src="/images/icons/Alert_grey_16.png"/> Alerts</label> - -<input type="checkbox" name="events" checked="checked" onchange="onLoad()" id="eventsField"/> - <label for="eventsField"><img src="/images/icons/Events_grey_16.png"/> Events</label> - -<input type="checkbox" name="configurations" checked="checked" onchange="onLoad()" id="configurationsField"/> - <label for="configurationsField"><img src="/images/icons/Configure_grey_16.png"/> Configuration Changes</label> - -<input type="checkbox" name="operations" checked="checked" onchange="onLoad()" id="operationsField"/> - <label for="operationsField"><img src="/images/icons/Operation_grey_16.png"/> Operations</label> - -<input type="checkbox" name="content" checked="checked" onchange="onLoad()" id="contentField"/> - <label for="contentField"><img src="/images/icons/Content_grey_16.png"/> Content Changes</label> -</form> <script type="text/javascript">
+function removeAllChildren(ele) { + if ( ele.hasChildNodes() ) { + while ( ele.childNodes.length >= 1 ) { + ele.removeChild( ele.firstChild ); + } + } +} + var tl;
function onLoad() { -
var begin = <%= begin%>; var end = <%= end%>; @@ -96,29 +76,29 @@ function onLoad() { var dateAndOne = "<%= new SimpleDateFormat("MMM dd yyyy HH:mm:ss z").format(new Date(System.currentTimeMillis() + (1000L * 60))) %>"; var timeZoneOffset = <%= (-new Date().getTimezoneOffset()) / 60 %>;
- var resourceId = <%= WebUtility.getOptionalIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM, -1) %>; + var resourceId = <%= WebUtility.getOptionalIntRequestParameter(request, ParamConstants.RESOURCE_ID_PARAM, -1) %>;
- var eventSource = new Timeline.DefaultEventSource(); + var eventSource = new Timeline.DefaultEventSource();
- var theme = Timeline.ClassicTheme.create(); + var theme = Timeline.ClassicTheme.create(); theme.event.bubble.width = 650; theme.event.bubble.height = 320; theme.event.label.width = 200; theme.event.label.lineColor = "black"; theme.event.highlightColors = ["red", "orange"];
- var bandInfos = [ + var bandInfos = [ Timeline.createBandInfo({ eventSource: eventSource, - date: "<%= new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z",Locale.US).format(new Date()) %>", + date: "<%= new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z",Locale.US).format(new Date()) %>", width: "80%", intervalUnit: Timeline.DateTime.MINUTE, - multiple: 5, - magnify: 10, + multiple: 5, + magnify: 10, intervalPixels: 20, trackGap: 0.4, - timeZone: timeZoneOffset, - theme: theme + timeZone: timeZoneOffset, + theme: theme }), Timeline.createBandInfo({ eventSource: eventSource, @@ -128,10 +108,10 @@ function onLoad() { trackGap: 0.2, intervalUnit: Timeline.DateTime.HOUR, intervalPixels: 100, - magnify: 5, - overview: true, - timeZone: timeZoneOffset, - theme: theme + magnify: 5, + overview: true, + timeZone: timeZoneOffset, + theme: theme }), Timeline.createBandInfo({ eventSource: eventSource, @@ -141,145 +121,153 @@ function onLoad() { trackGap: 0.2, intervalUnit: Timeline.DateTime.DAY, intervalPixels: 300, - overview: true, - timeZone: timeZoneOffset, - theme: theme + overview: true, + timeZone: timeZoneOffset, + theme: theme }) - ]; - bandInfos[1].syncWith = 0; - bandInfos[1].highlight = true; - bandInfos[2].syncWith = 1; - bandInfos[2].highlight = true; + ]; + bandInfos[1].syncWith = 0; + bandInfos[1].highlight = true; + bandInfos[2].syncWith = 1; + bandInfos[2].highlight = true;
for (var i = 0; i < bandInfos.length; i++) { bandInfos[i].decorators = [ new Timeline.PointHighlightDecorator({ - date: "<%= new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z",Locale.US).format(new Date()) %>", + date: "<%= new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z",Locale.US).format(new Date()) %>", color: "#0000CC", opacity: 30, startLabel: "Now", - endLabel: "" + endLabel: "" })
<% SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z",Locale.US);
-for (Availability avail : availabilities) { + for (Availability avail : availabilities) {
- out.write(", new Timeline.SpanHighlightDecorator({\n" + + out.write(", new Timeline.SpanHighlightDecorator({\n" + " startDate: "" + sdf.format(avail.getStartTime()) + "",\n" + -" endDate: "" + sdf.format(avail.getEndTime() == null ? new Date() : avail.getEndTime()) + "",\n" + +" endDate: "" + sdf.format(avail.getEndTime() == null ? new Date() : avail.getEndTime()) + "",\n" + " color: "" + (avail.getAvailabilityType() == AvailabilityType.UP ? "#B0FFC5":"#F7A6A8") + "",\n" + " opacity: 20,\n" + " startLabel: "",\n" + -" endLabel: ""\n" + +" endLabel: ""\n" + " })"); -} - + } %> - - ]; }
- - tl = Timeline.create(document.getElementById("t1"), bandInfos); + tl = Timeline.create(document.getElementById("t1"), bandInfos);
var toLoad = 7; - function done() { - toLoad--; - if (toLoad == 0) { - if (eventSource.getCount() == 0) { - document.getElementById("loading").innerHTML = '<img src="/images/NoEvents.png" alt="Loading events"/>'; - } else { - document.getElementById("loading").style.display = "none"; - } - } - } - - if (document.forms['show'].configurations.checked) { - var link = "/resource/common/monitor/events/EventConfigJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + function done() { + toLoad--; + if (toLoad == 0) { + if (eventSource.getCount() == 0) { + document.getElementById("loading").innerHTML = '<img src="/images/NoEvents.png" alt="Loading events"/>'; + } else { + document.getElementById("loading").style.display = "none"; + } + } + }
- if (document.forms['show'].configurations.checked) { - link = "/resource/common/monitor/events/EventPluginConfigJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + if (document.forms['show'].configurations.checked) { + var link = "/resource/common/monitor/events/EventConfigJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
- if (document.forms['show'].configurations.checked) { - link = "/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + if (document.forms['show'].configurations.checked) { + link = "/resource/common/monitor/events/EventPluginConfigJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
- if (document.forms['show'].alerts.checked) { - link = "/resource/common/monitor/events/EventAlertJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + if (document.forms['show'].configurations.checked) { + link = "/resource/common/monitor/events/EventCreateDeleteChildJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
+ if (document.forms['show'].alerts.checked) { + link = "/resource/common/monitor/events/EventAlertJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
- if (document.forms['show'].operations.checked) { - link = "/resource/common/monitor/events/EventOperationsJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + if (document.forms['show'].operations.checked) { + link = "/resource/common/monitor/events/EventOperationsJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
- if (document.forms['show']['events'].checked) { - link = "/resource/common/monitor/events/EventEventsJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + if (document.forms['show']['events'].checked) { + link = "/resource/common/monitor/events/EventEventsJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
if (document.forms['show']['content'].checked) { - link = "/resource/common/monitor/events/EventContentJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; - Timeline.loadJSON(link, function(json, url) { - eventSource.loadJSON(json, url); - document.getElementById("event-count").innerHTML = eventSource.getCount(); - done(); - }); - } + link = "/resource/common/monitor/events/EventContentJSON.jsp?id=" + resourceId + "&begin=" + begin + "&end=" + end; + Timeline.loadJSON(link, function(json, url) { + eventSource.loadJSON(json, url); + document.getElementById("event-count").innerHTML = eventSource.getCount(); + done(); + }); + }
+ removeAllChildren(document.getElementById("controls")); setupFilterHighlightControls(document.getElementById("controls"), tl, [0,1], theme); } - var resizeTimerID = null; - function onResize() { - if (resizeTimerID == null) { - resizeTimerID = window.setTimeout(function() { - resizeTimerID = null; - tl.layout(); - }, 500); - } - } -</script> - - <div id="t1" style="height: 450px; border: 1px solid #aaa"></div> - - <!-- not accurate with grouping <div>Events: --> - <span id="event-count" style="display:none;"></span> - <div class="controls" id="controls"></div>
+var resizeTimerID = null; +function onResize() { + if (resizeTimerID == null) { + resizeTimerID = window.setTimeout(function() { + resizeTimerID = null; + tl.layout(); + }, 500); + } +} +</script>
- </body> -</html> \ No newline at end of file +<span id="event-count" style="display:none;"></span> +<div class="controls" id="controls"></div> +<form action="#" onsubmit="onLoad()" name="show"> + <input type="checkbox" name="alerts" checked="checked" onchange="onLoad()" id="alertsField"/> + <label for="alertsField"><img src="/images/icons/Alert_grey_16.png"/> Alerts</label> + + <input type="checkbox" name="events" checked="checked" onchange="onLoad()" id="eventsField"/> + <label for="eventsField"><img src="/images/icons/Events_grey_16.png"/> Events</label> + + <input type="checkbox" name="configurations" checked="checked" onchange="onLoad()" id="configurationsField"/> + <label for="configurationsField"><img src="/images/icons/Configure_grey_16.png"/> Configuration Changes</label> + + <input type="checkbox" name="operations" checked="checked" onchange="onLoad()" id="operationsField"/> + <label for="operationsField"><img src="/images/icons/Operation_grey_16.png"/> Operations</label> + + <input type="checkbox" name="content" checked="checked" onchange="onLoad()" id="contentField"/> + <label for="contentField"><img src="/images/icons/Content_grey_16.png"/> Content Changes</label> +</form> +<div id="t1" style='height: 475px; border: 1px solid #aaa'></div> +</body></html> \ No newline at end of file
commit ad611c88d9d1fd60a223b209d98a7fde88969e07 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 24 12:05:40 2011 -0400
[BZ 676761] display a friendly error, rather than an ugly stack trace, if the user enters an invalid search expression on the Resource or group list views (https://bugzilla.redhat.com/show_bug.cgi?id=676761)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java index ab30354..584e652 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java @@ -47,6 +47,7 @@ import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGroupGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; +import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * @author Joseph Marques @@ -105,7 +106,12 @@ public class ResourceGroupCompositeDataSource extends RPCDataSource<ResourceGrou groupService.findResourceGroupCompositesByCriteria(criteria, new AsyncCallback<PageList<ResourceGroupComposite>>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_inventory_groups_loadFailed(), caught); + if (caught.getMessage().contains("SearchExpressionException")) { + Message message = new Message("Invalid search expression.", Message.Severity.Error); + CoreGUI.getMessageCenter().notify(message); + } else { + CoreGUI.getErrorHandler().handleError(MSG.view_inventory_groups_loadFailed(), caught); + } response.setStatus(RPCResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java index 801e8fa..6c6c673 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceDatasource.java @@ -60,6 +60,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.TypesLoadedCallback; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; +import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * @author Greg Hinkle @@ -164,7 +165,12 @@ public class ResourceDatasource extends RPCDataSource<Resource, ResourceCriteria public void executeFetch(final DSRequest request, final DSResponse response, final ResourceCriteria criteria) { resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_inventory_resources_loadFailed(), caught); + if (caught.getMessage().contains("SearchExpressionException")) { + Message message = new Message("Invalid search expression.", Message.Severity.Error); + CoreGUI.getMessageCenter().notify(message); + } else { + CoreGUI.getErrorHandler().handleError(MSG.view_inventory_resources_loadFailed(), caught); + } response.setStatus(RPCResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); }
commit 1fac1f54c438561b1c1907719d55b03f88e8aa43 Author: John Sanda jsanda@redhat.com Date: Wed Aug 24 11:22:35 2011 -0400
Do not have the change set reader automatically close stream when reading change set file
The reader was automatically closing the stream which caused an exception in ZipUtil.walkZipFile. This didn't cause a loss in functionality since the zip file only has one file; however this fix is needed to avoid noise in the logs and also to handle the future possibility of the change set zip containing multiple files.
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 a935e66..21d72f5 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 @@ -55,6 +55,8 @@ public class ChangeSetReaderImpl implements ChangeSetReader {
private Headers headers;
+ private boolean closeStream; + public ChangeSetReaderImpl(File metaDataFile) throws ChangeSetReaderException { try { this.metaDataFile = metaDataFile; @@ -70,8 +72,23 @@ public class ChangeSetReaderImpl implements ChangeSetReader { }
public ChangeSetReaderImpl(Reader metaDataFile) throws Exception { + this(metaDataFile, false); + } + + /** + * Creates a new change set reader. This constructor takes a boolean argument that can + * be used to prevent the reader from closing the stream when using its iterator. Note + * that calling {@link #close()} will close the stream regardless of the value of + * closeStream. + * + * @param metaDataFile + * @param closeStream + * @throws Exception + */ + public ChangeSetReaderImpl(Reader metaDataFile, boolean closeStream) throws Exception { reader = new BufferedReader(metaDataFile); readHeaders(); + this.closeStream = closeStream; }
private void readHeaders() throws IOException { @@ -158,7 +175,7 @@ public class ChangeSetReaderImpl implements ChangeSetReader { try { FileEntry previous = next; next = read(); - if (next == null) { + if (next == null && closeStream) { close(); } return previous; 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 dd4c6c9..c3a34bf 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 @@ -238,7 +238,7 @@ public class JPADriftServerBean implements JPADriftServerLocal {
try { ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader( - stream))); + stream)), false);
// store the new change set info (not the actual blob) DriftConfiguration config = findDriftConfiguration(resource, reader.getHeaders());
commit 1138b48738fa014a8f017c248ac5c75606115a51 Author: John Sanda jsanda@redhat.com Date: Wed Aug 24 10:33:28 2011 -0400
Ensure only content files are stored in the content zip file
In my previous commit, I changed the location of content.zip to be <agent_home>/data/changesets<resource_id>/<drift_config_id>/content/content.zip. This ensures that DriftManager doesn't overwrite content files. That change resulted in content.zip before stored in itself. This commit makes sure that it is filtered out.
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 e640c7e..c550f2d 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 @@ -24,6 +24,7 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.FilenameFilter; import java.io.IOException; import java.util.List; import java.util.Set; @@ -165,12 +166,19 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri }
@Override - public void sendChangeSetContentToServer(int resourceId, String driftConfigurationName, File contentDir) { + public void sendChangeSetContentToServer(int resourceId, String driftConfigurationName, final File contentDir) { try { File zipFile = new File(contentDir, "content.zip"); ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
- for (File file : contentDir.listFiles()) { + FilenameFilter contentZipFilter = new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return dir.equals(contentDir) && !name.equals("content.zip"); + } + }; + + for (File file : contentDir.listFiles(contentZipFilter)) { FileInputStream fis = new FileInputStream(file); stream.putNextEntry(new ZipEntry(file.getName())); StreamUtil.copy(fis, stream, false); 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 b9c576d..13fe5ed 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 @@ -20,11 +20,8 @@ package org.rhq.core.pc.drift;
import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream;
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -32,7 +29,6 @@ import org.testng.annotations.Test; import org.rhq.core.clientapi.server.drift.DriftServerService; import org.rhq.core.pc.PluginContainerConfiguration; import org.rhq.core.pc.ServerServices; -import org.rhq.core.util.stream.StreamUtil;
import static org.rhq.core.util.ZipUtil.unzipFile; import static org.testng.Assert.assertEquals; @@ -137,6 +133,8 @@ public class DriftManagerTest extends DriftTest { fail("Failed to unzip zip file from intput stream into " + zipDir.getPath(), e); }
+ assertEquals(zipDir.listFiles().length, expectedFiles.length, "The zip file has the wrong number of files"); + for (File expectedFile : expectedFiles) {
File actualFile = findFile(zipDir, expectedFile); @@ -163,13 +161,6 @@ public class DriftManagerTest extends DriftTest { return null; }
- private void addToZipFile(File file, ZipOutputStream stream) throws Exception { - FileInputStream fis = new FileInputStream(file); - stream.putNextEntry(new ZipEntry(file.getName())); - StreamUtil.copy(fis, stream, false); - fis.close(); - } - /** * Sets a callback that will be invoked immediately after DriftManager calls * {@link DriftServerService#sendChangesetZip(int, long, java.io.InputStream)} or
commit f5318369a4f710cfc6d24c2c18f13f0b910418d8 Author: John Sanda jsanda@redhat.com Date: Wed Aug 24 10:08:27 2011 -0400
Purge change set content directory after sending content to server
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 0f4f7cf..8398b82 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 @@ -13,6 +13,15 @@ public interface DriftClient {
void sendChangeSetToServer(int resourceId, DriftConfiguration driftConfiguration, DriftChangeSetCategory type);
+ /** + * Sends requested content to the server. All of the files in the content directory are + * zipped up, and the zip file is sent to the server. After the zip file is sent to the + * server, the content directory is purged. + * + * @param resourceId + * @param driftConfigurationName + * @param contentDir + */ void sendChangeSetContentToServer(int resourceId, String driftConfigurationName, File contentDir);
File getAbsoluteBaseDirectory(int resourceId, DriftConfiguration driftConfiguration); 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 8b782ce..e640c7e 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 @@ -167,7 +167,7 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri @Override public void sendChangeSetContentToServer(int resourceId, String driftConfigurationName, File contentDir) { try { - File zipFile = new File(pluginContainerConfiguration.getTemporaryDirectory(), "content.zip"); + File zipFile = new File(contentDir, "content.zip"); ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
for (File file : contentDir.listFiles()) { @@ -185,6 +185,12 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri log.error("An error occurred while trying to send content for changeset[resourceId: " + resourceId + ", driftConfiguration: " + driftConfigurationName + "]", e); } + + for (File file : contentDir.listFiles()) { + if (!file.delete()) { + log.warn("Unable to clean up content directory. Failed to delete " + file.getPath()); + } + } }
@Override 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 bd49c20..b9c576d 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 @@ -37,6 +37,8 @@ import org.rhq.core.util.stream.StreamUtil; import static org.rhq.core.util.ZipUtil.unzipFile; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail;
public class DriftManagerTest extends DriftTest {
@@ -46,7 +48,7 @@ public class DriftManagerTest extends DriftTest {
private PluginContainerConfiguration pcConfig;
-// private DriftManager driftMgr; + private DriftManager driftMgr;
@BeforeMethod public void initTest() throws Exception { @@ -59,6 +61,30 @@ public class DriftManagerTest extends DriftTest { pcConfig.setServerServices(serverServices); pcConfig.setDataDirectory(basedir()); pcConfig.setTemporaryDirectory(tmpDir); + + driftMgr = new DriftManager(); + driftMgr.setConfiguration(pcConfig); + } + + @Test + public void writeContentZipFileToChangeSetContentDirectory() throws Exception { + String configName = "send-content-in-zip"; + File changeSetDir = changeSetDir(configName); + final File contentDir = mkdir(changeSetDir, "content"); + + createRandomFile(contentDir, "content-1"); + createRandomFile(contentDir, "content-2"); + + setDriftServiceCallback(new DriftServiceCallback() { + @Override + public void execute() { + File contentZip = new File(contentDir, "content.zip"); + assertTrue(contentZip.exists(), "Expected content zip file to be written to the change set content " + + "directory: " + contentDir.getPath()); + } + }); + + driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir); }
@Test @@ -67,40 +93,52 @@ public class DriftManagerTest extends DriftTest { File changeSetDir = changeSetDir(configName); File contentDir = mkdir(changeSetDir, "content");
- File content1 = createRandomFile(contentDir, "content-1"); - File content2 = createRandomFile(contentDir, "content-2"); + final File content1 = createRandomFile(contentDir, "content-1"); + final File content2 = createRandomFile(contentDir, "content-2");
- DriftManager driftMgr = new DriftManager(); - driftMgr.setConfiguration(pcConfig); + setDriftServiceCallback(new DriftServiceCallback() { + @Override + public void execute() { + assertZipFileMatches(driftServerService.filesZipStream, content1, content2); + } + });
driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir); + }
- File outputDir = new File(tmpDir, "output"); - outputDir.mkdir(); - unzipFile(driftServerService.filesZipStream, outputDir); + @Test + public void cleanUpAfterSendingContentToServer() throws Exception { + String configName = "clean-up-after-sending-content"; + File changeSetDir = changeSetDir(configName); + File contentDir = mkdir(changeSetDir, "content");
- assertEquals(outputDir.listFiles().length, 2, "Expected the zip file to contain two entries"); - assertZipFileMatches(outputDir, content1, content2); - } + createRandomFile(contentDir, "content-1"); + createRandomFile(contentDir, "content-2");
-// @Test -// public void cleanUpAfterSendingContentToServer() throws Exception { -// String configName = "clean-up-after-sending-content"; -// File changeSetDir = changeSetDir(configName); -// File contentDir = mkdir(changeSetDir, "content"); -// } + driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir); + + assertThatDirectoryIsEmpty(contentDir); + }
/** * 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 * the expected files by comparing their SHA-256 hashes. * - * @param zipDir + * @param zipStream * @param expectedFiles * @throws IOException */ - private void assertZipFileMatches(File zipDir, File... expectedFiles) throws IOException { + private void assertZipFileMatches(InputStream zipStream, File... expectedFiles) { + File zipDir = new File(tmpDir, "output"); + try { + unzipFile(zipStream, zipDir); + } catch (IOException e) { + fail("Failed to unzip zip file from intput stream into " + zipDir.getPath(), e); + } + for (File expectedFile : expectedFiles) { + File actualFile = findFile(zipDir, expectedFile); assertNotNull(actualFile, "Expected zip file to contain " + expectedFile.getName());
@@ -112,6 +150,10 @@ public class DriftManagerTest extends DriftTest { } }
+ private void assertThatDirectoryIsEmpty(File dir) { + assertEquals(dir.listFiles().length, 0, "Expected " + dir.getPath() + " to be empty"); + } + private File findFile(File dir, File file) { for (File f : dir.listFiles()) { if (f.getName().equals(file.getName())) { @@ -128,12 +170,27 @@ public class DriftManagerTest extends DriftTest { fis.close(); }
+ /** + * Sets a callback that will be invoked immediately after DriftManager calls + * {@link DriftServerService#sendChangesetZip(int, long, java.io.InputStream)} or + * {@link DriftServerService#sendFilesZip(int, long, java.io.InputStream)}. The callback + * can perform any verification as necessary, and that will happen before the call to + * to DriftServerService returns. + * + * @param callback + */ + private void setDriftServiceCallback(DriftServiceCallback callback) { + driftServerService.callback = callback; + } + private static class TestDriftServerService implements DriftServerService {
public int filesZipResourceId; public long filesZipSize; public InputStream filesZipStream;
+ public DriftServiceCallback callback; + @Override public void sendChangesetZip(int resourceId, long zipSize, InputStream zipStream) { } @@ -143,7 +200,19 @@ public class DriftManagerTest extends DriftTest { filesZipResourceId = resourceId; filesZipSize = zipSize; filesZipStream = zipStream; + + if (callback != null) { + callback.execute(); + } } }
+ /** + * This callback interface provides a hook for doing any verification immediately after + * DriftManager calls DriftServerService. + */ + private static interface DriftServiceCallback { + void execute(); + } + } 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 b1ab9ec..a22b26f 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 @@ -202,8 +202,12 @@ public class DriftTest { * @return The SHA-256 hash as a string * @throws IOException */ - protected String sha256(File file) throws IOException { - return digestGenerator.calcDigestString(file); + protected String sha256(File file) { + try { + return digestGenerator.calcDigestString(file); + } catch (IOException e) { + throw new RuntimeException("Failed to calculate SHA-256 hash for " + file.getPath(), e); + } }
protected File createRandomFile(File dir, String fileName) throws Exception {
commit d686a211d51682884c38f87deaf2faea2f78f6c9 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 23 20:54:36 2011 -0400
Work on Search Bar [BZ 695889] NPE protection for some saved search actions
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/search/SavedSearchManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/search/SavedSearchManagerBean.java index 759658e..5ebf6c8 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/search/SavedSearchManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/search/SavedSearchManagerBean.java @@ -63,7 +63,7 @@ public class SavedSearchManagerBean implements SavedSearchManagerLocal /* local // this needs to prevent certains types of updates, be more sophisticated, etc validateManipulatePermission(subject, savedSearch); SavedSearch oldSavedSearch = entityManager.find(SavedSearch.class, savedSearch.getId()); - if (oldSavedSearch.equals(savedSearch)) { + if (null == oldSavedSearch || oldSavedSearch.equals(savedSearch)) { return false; } else { entityManager.merge(savedSearch); @@ -76,8 +76,10 @@ public class SavedSearchManagerBean implements SavedSearchManagerLocal /* local */ public void deleteSavedSearch(Subject subject, int savedSearchId) { SavedSearch savedSearch = entityManager.find(SavedSearch.class, savedSearchId); - validateManipulatePermission(subject, savedSearch); - entityManager.remove(savedSearch); + if (null != savedSearch) { + validateManipulatePermission(subject, savedSearch); + entityManager.remove(savedSearch); + } }
/**
commit 876517e012d468e9841f3a15432cd801df0d404d Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 23 20:54:02 2011 -0400
Work on Search Bar [BZ 695889] Keep focus in the text box as much as possible. This allows more natural editing of the pattern, and avoids causing unanticipated browser when just trying to perform text box delete.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java index 28aabb6..a2e2d5d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/search/suggest/SuggestTextBox_v3.java @@ -101,6 +101,8 @@ public class SuggestTextBox_v3 extends Composite implements HasText, HasAllFocus // suggestionMenu must be created before suggestionPopup, because // suggestionMenu is suggestionPopup's widget suggestionMenu = new SuggestionMenu(true); + // let the text box maintain focus when navigating the menu + suggestionMenu.setFocusOnHoverEnabled(false); suggestionPopup = createPopup();
// need to fork PopupPanel to access the animation type @@ -189,6 +191,8 @@ public class SuggestTextBox_v3 extends Composite implements HasText, HasAllFocus } else { suggestionPopup.hide(); } + + setFocus(true); }
private void addEventsToTextBox() {
commit 101f9542e726a2a3b68fa74f83422110d4be5f61 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 23 20:42:53 2011 -0400
[BZ 729329 - if RHQ server is down, UI shows globally uncaught exception] Catch certain gttp response codes and use them to inform the user that the server is not reachable. For Firefox, handle the fact that even trying to read the response code causes a javascript exception.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/TrackingRequestCallback.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/TrackingRequestCallback.java index 44264bb..734adda 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/TrackingRequestCallback.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/rpc/TrackingRequestCallback.java @@ -23,6 +23,7 @@ import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.UserSessionManager;
/** @@ -36,6 +37,8 @@ public class TrackingRequestCallback implements RequestCallback { private long start = System.currentTimeMillis();
private static final int STATUS_CODE_OK = 200; + private static final int STATUS_CODE_ERROR_INTERNET_CANNOT_CONNECT = 12029; + private static final int STATUS_CODE_ERROR_INTERNET_CONNECTION_ABORTED = 12030;
private RequestCallback callback;
@@ -58,17 +61,48 @@ public class TrackingRequestCallback implements RequestCallback { }
public void onResponseReceived(Request request, Response response) { + int statusCode; + String statusText; + + try { + statusCode = response.getStatusCode(); + statusText = response.getStatusText(); + } catch (Throwable t) { + // If the server is unreachable or has terminated firefox will generate a JavaScript exception + // when trying to read the response object. Let the user know the server is unreachable. + // (http://helpful.knobs-dials.com/index.php/0x80004005_%28NS_ERROR_FAILURE%29_a...)) + if (UserSessionManager.isLoggedIn()) { + CoreGUI.getErrorHandler().handleError(CoreGUI.getMessages().view_core_serverUnreachable(), t); + } + return; + } + if (Log.isTraceEnabled()) { - Log.trace(toString() + ": " + response.getStatusCode() + "/" + response.getStatusText()); + Log.trace(toString() + ": " + statusCode + "/" + statusText); }
RemoteServiceStatistics.record(getName(), getAge()); - if (STATUS_CODE_OK == response.getStatusCode()) { + + switch (statusCode) { + case STATUS_CODE_OK: RPCTracker.getInstance().succeedCall(this); callback.onResponseReceived(request, response); - } else { + break; + + case STATUS_CODE_ERROR_INTERNET_CANNOT_CONNECT: + case STATUS_CODE_ERROR_INTERNET_CONNECTION_ABORTED: + RPCTracker.getInstance().failCall(this); + // If the server is unreachable or has terminated, and the user is still logged in, + // let them know the server is now unreachable. + if (UserSessionManager.isLoggedIn()) { + CoreGUI.getErrorHandler().handleError("Server unreachable and may be down"); + } + break; + + default: RPCTracker.getInstance().failCall(this); - if (UserSessionManager.isLoggedIn()) { // only handle failures if user still logged in + // process the failure only if the user still logged in + if (UserSessionManager.isLoggedIn()) { callback.onResponseReceived(request, response); } } 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 93e38ab..2c97890 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 @@ -1102,6 +1102,7 @@ view_connectionSettingsDetails_somePropertiesInvalid = The following connection view_core_loggedOut = Logged out view_core_noRecentAlerts = There are no recent alerts to report view_core_recentAlerts = There are [{0}] recent alerts - click to go to the recent alerts report +view_core_serverUnreachable = The server is unreachable and may be down view_core_uncaught = Globally uncaught exception view_dashboardManager_deleteFail = Failed to delete dashboard. view_dashboardManager_deleted = Successfully deleted dashboard {0} 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 19d264b..8710e11 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 @@ -927,6 +927,7 @@ view_connectionSettingsDetails_somePropertiesInvalid = The following connection view_core_loggedOut = Ausgeloggt view_core_noRecentAlerts = Es liegen keine frischen Alarme vor view_core_recentAlerts = [{0}] frische Alarme +##view_core_serverUnreachable = The server is unreachable and may be down view_core_uncaught = Es ist eine nicht abgefangene Ausnahme aufgetreten. view_dashboardManager_deleteFail = Konnte das Dashboard nicht löschen. view_dashboardManager_deleted = Successfully deleted dashboard {0}~ 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 2cc6d6b..907f6f2 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 @@ -1089,6 +1089,7 @@ view_connectionSettingsDetails_somePropertiesInvalid = 次ã®ã³ãã¯ã·ã§ã³ view_core_loggedOut = ãã°ã¢ãŠã view_core_noRecentAlerts = ã¬ããŒããã¹ãæè¿ã®ã¢ã©ãŒãã¯ååšããŸãã view_core_recentAlerts = [{0}] åã®æè¿ã®ã¢ã©ãŒãããããŸãã - æè¿ã®ã¢ã©ãŒãã¬ããŒããžã¯ãªãã¯ããŠãã ãã +##view_core_serverUnreachable = The server is unreachable and may be down view_core_uncaught = ã°ããŒãã«ã«ãã£ãããããªãäŸå€ view_dashboardManager_deleteFail = ããã·ã¥ããŒãã®åé€ã«å€±æããŸãã view_dashboardManager_deleted = ããã·ã¥ããŒã {0} ã®åé€ã«æåããŸãã 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 ecc380d..f8e28da 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 @@ -1121,6 +1121,7 @@ view_core_loggedInAs = Logado como {0} view_core_loggedOut = Desconectado view_core_noRecentAlerts = Nï¿œo existem alertas recentes view_core_recentAlerts = [{0}] alertas recentes +##view_core_serverUnreachable = The server is unreachable and may be down view_core_uncaught = Exce\u00E7\u00E3o n\u00E3o capturada view_dashboardManager_deleteFail = Falha ao excluir o dashboard. view_dashboardManager_deleted = Dashboard {0} exclu\u00EDdo com sucesso! 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 ff0bca8..afd099e 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 @@ -1098,6 +1098,7 @@ view_connectionSettingsDetails_somePropertiesInvalid = \u4e0b\u9762\u7684\u8fde\ view_core_loggedOut = \u9000\u51fa\u767b\u5f55 view_core_noRecentAlerts = \u6ca1\u6709\u65b0\u4ea7\u751f\u7684\u544a\u8b66\u4fe1\u606f view_core_recentAlerts = \u65b0\u4ea7\u751f [{0}] \u6761\u544a\u8b66 - \u70b9\u51fb\u8df3\u8f6c\u5230\u65b0\u544a\u8b66\u62a5\u8868\u754c\u9762 +##view_core_serverUnreachable = The server is unreachable and may be down view_core_uncaught = \u5168\u5c40\u672a\u6355\u6349\u7684\u5f02\u5e38 view_dashboardManager_deleteFail = \u5220\u9664\u7edf\u8ba1\u8868\u76d8\u5931\u8d25. view_dashboardManager_deleted = \u6210\u529f\u5220\u9664\u7edf\u8ba1\u8868\u76d8{0}
commit 17aeff283b1518e9c70d37431a4cc3def801e145 Author: John Sanda jsanda@redhat.com Date: Tue Aug 23 17:01:55 2011 -0400
Initial commit for DriftManagerTest
Starting to add tests for sending content to the server. Tests for DriftManager are overdue and the timing is perfect because code needs to be added to clean up after sending content to the server. Cleaning up entails deleting the content that the agent made copies of.
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 62e1e39..8b782ce 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,8 +19,6 @@
package org.rhq.core.pc.drift;
-import static org.rhq.core.util.ZipUtil.zipFileOrDirectory; - import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -53,6 +51,8 @@ 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.core.util.ZipUtil.zipFileOrDirectory; + public class DriftManager extends AgentService implements DriftAgentService, DriftClient, ContainerService {
private final Log log = LogFactory.getLog(DriftManager.class); @@ -169,7 +169,6 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri try { File zipFile = new File(pluginContainerConfiguration.getTemporaryDirectory(), "content.zip"); ZipOutputStream stream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); - //zipFileOrDirectory(contentDir, zipFile);
for (File file : contentDir.listFiles()) { FileInputStream fis = new FileInputStream(file); 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 new file mode 100644 index 0000000..bd49c20 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftManagerTest.java @@ -0,0 +1,149 @@ +/* + * 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.pc.drift; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.rhq.core.clientapi.server.drift.DriftServerService; +import org.rhq.core.pc.PluginContainerConfiguration; +import org.rhq.core.pc.ServerServices; +import org.rhq.core.util.stream.StreamUtil; + +import static org.rhq.core.util.ZipUtil.unzipFile; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +public class DriftManagerTest extends DriftTest { + + private File tmpDir; + + private TestDriftServerService driftServerService; + + private PluginContainerConfiguration pcConfig; + +// private DriftManager driftMgr; + + @BeforeMethod + public void initTest() throws Exception { + tmpDir = mkdir(basedir(), "tmp"); + + pcConfig = new PluginContainerConfiguration(); + ServerServices serverServices = new ServerServices(); + driftServerService = new TestDriftServerService(); + serverServices.setDriftServerService(driftServerService); + pcConfig.setServerServices(serverServices); + pcConfig.setDataDirectory(basedir()); + pcConfig.setTemporaryDirectory(tmpDir); + } + + @Test + public void sendContentToServerInZipFile() throws Exception { + String configName = "send-content-in-zip"; + File changeSetDir = changeSetDir(configName); + File contentDir = mkdir(changeSetDir, "content"); + + File content1 = createRandomFile(contentDir, "content-1"); + File content2 = createRandomFile(contentDir, "content-2"); + + DriftManager driftMgr = new DriftManager(); + driftMgr.setConfiguration(pcConfig); + + driftMgr.sendChangeSetContentToServer(resourceId(), configName, contentDir); + + File outputDir = new File(tmpDir, "output"); + outputDir.mkdir(); + unzipFile(driftServerService.filesZipStream, outputDir); + + assertEquals(outputDir.listFiles().length, 2, "Expected the zip file to contain two entries"); + assertZipFileMatches(outputDir, content1, content2); + } + +// @Test +// public void cleanUpAfterSendingContentToServer() throws Exception { +// String configName = "clean-up-after-sending-content"; +// File changeSetDir = changeSetDir(configName); +// File contentDir = mkdir(changeSetDir, "content"); +// } + + /** + * 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 + * the expected files by comparing their SHA-256 hashes. + * + * @param zipDir + * @param expectedFiles + * @throws IOException + */ + private void assertZipFileMatches(File zipDir, File... expectedFiles) throws IOException { + for (File expectedFile : expectedFiles) { + File actualFile = findFile(zipDir, expectedFile); + assertNotNull(actualFile, "Expected zip file to contain " + expectedFile.getName()); + + 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()); + } + } + + private File findFile(File dir, File file) { + for (File f : dir.listFiles()) { + if (f.getName().equals(file.getName())) { + return f; + } + } + return null; + } + + private void addToZipFile(File file, ZipOutputStream stream) throws Exception { + FileInputStream fis = new FileInputStream(file); + stream.putNextEntry(new ZipEntry(file.getName())); + StreamUtil.copy(fis, stream, false); + fis.close(); + } + + private static class TestDriftServerService implements DriftServerService { + + public int filesZipResourceId; + public long filesZipSize; + public InputStream filesZipStream; + + @Override + public void sendChangesetZip(int resourceId, long zipSize, InputStream zipStream) { + } + + @Override + public void sendFilesZip(int resourceId, long zipSize, InputStream zipStream) { + filesZipResourceId = resourceId; + filesZipSize = zipSize; + filesZipStream = zipStream; + } + } + +} 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 1c02b3f..b1ab9ec 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 @@ -124,7 +124,7 @@ public class DriftTest { */ @BeforeClass public void initResourcesAndChangeSetsDirs() throws Exception { - File basedir = new File("target", getClass().getSimpleName()); + File basedir = basedir(); deleteDirectory(basedir); basedir.mkdir();
@@ -148,6 +148,10 @@ public class DriftTest { changeSetMgr = new ChangeSetManagerImpl(changeSetsDir); }
+ protected File basedir() { + return new File("target", getClass().getSimpleName()); + } + /** @return The current or last resource id generated */ protected int resourceId() { return resourceId;
commit 0c020afb287d34d49472b48c27029437fc562920 Author: Ian Springer ian.springer@redhat.com Date: Tue Aug 23 16:07:25 2011 -0400
[BZ 696664] remove NotNull annotations for the 'name' field, since it is not a required field according the DB schema for RHQ_RESOURCE (https://bugzilla.redhat.com/show_bug.cgi?id=696664)
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 40afa2f..de415f4 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 @@ -80,7 +80,7 @@ import org.rhq.core.domain.tagging.Tag; import org.rhq.core.domain.util.Summary;
/** - * Represents a JON managed resource (i.e. a platform, server, or service). + * Represents an RHQ managed resource (i.e. a platform, server, or service). */ @Entity @NamedQueries( { @@ -1085,7 +1085,7 @@ public class Resource implements Comparable<Resource>, Serializable { * Primarily for deserialization and cases where the resource object is just a reference to the real one in the db. * (Key is this avoids the irrelevant UUID generation that has contention problems. * - * @param id + * @param id the Resource's id */ public Resource(int id) { this.id = id; @@ -1093,7 +1093,7 @@ public class Resource implements Comparable<Resource>, Serializable {
public Resource( // @NotNull String resourceKey, // - @NotNull String name, // + String name, // @NotNull ResourceType type) { this.resourceKey = resourceKey; this.name = name; @@ -1133,12 +1133,11 @@ public class Resource implements Comparable<Resource>, Serializable { this.uuid = uuid; }
- @NotNull public String getName() { return this.name; }
- public void setName(@NotNull String name) { + public void setName(String name) { this.name = name; }
@@ -1147,8 +1146,8 @@ public class Resource implements Comparable<Resource>, Serializable { }
/** - * In general this method should not be called by application code. At least not for any Resource that will be - * persisted or merged. The ancestry string is maintained internally. {@link #updateAncestryForResource()}. + * In general this method should not be called by application code, at least not for any Resource that will be + * persisted or merged. The ancestry string is maintained internally (see {@link #updateAncestryForResource()}). * * @param ancestry */
commit 00637543a1757f1d3547206b6e3e02581f48716c Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 23 16:03:09 2011 -0400
[BZ 695880] refactor the way the user-delete functionality works. now works without getting that ugly exception
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java index 9136e35..55b0281 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersDataSource.java @@ -43,7 +43,6 @@ import org.rhq.enterprise.gui.coregui.client.admin.roles.RolesDataSource; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; -import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * A DataSource for RHQ {@link Subject user}s. @@ -252,26 +251,6 @@ public class UsersDataSource extends RPCDataSource<Subject, SubjectCriteria> { }); }
- @Override - protected void executeRemove(final Record userRecordToRemove, final DSRequest request, final DSResponse response) { - final Subject subjectToRemove = copyValues(userRecordToRemove); - - final String username = subjectToRemove.getName(); - subjectService.deleteSubjects(new int[] { subjectToRemove.getId() }, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - String message = MSG.dataSource_users_deleteFailed(username); - sendFailureResponse(request, response, message, caught); - } - - public void onSuccess(Void result) { - Message message = new Message(MSG.dataSource_users_delete(username)); - sendSuccessResponse(request, response, subjectToRemove, message, UsersView.VIEW_PATH); - } - }); - - } - - @SuppressWarnings("unchecked") public Subject copyValues(Record from) { Subject to = new Subject();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java index 4fdd6e5..58c0912 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/users/UsersView.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Set;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.ListGridField; @@ -30,6 +31,7 @@ import com.smartgwt.client.widgets.grid.events.CellClickEvent; import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import org.rhq.core.domain.authz.Permission; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener; import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.admin.AdministrationView; @@ -37,6 +39,9 @@ import org.rhq.enterprise.gui.coregui.client.components.table.EscapedHtmlCellFor import org.rhq.enterprise.gui.coregui.client.components.table.TableAction; 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.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * A table that lists all users and provides the ability to view or edit details of users, delete users, or create new @@ -206,7 +211,32 @@ public class UsersView extends TableSection<UsersDataSource> { }
public void executeAction(ListGridRecord[] selection, Object actionValue) { - deleteSelectedRecords(); + if (selection == null || selection.length == 0) { + return; + } + + final ArrayList<String> doomedNames = new ArrayList<String>(selection.length); + final int[] doomedIds = new int[selection.length]; + int i = 0; + for (ListGridRecord record : selection) { + doomedNames.add(record.getAttribute(UsersDataSource.Field.NAME)); + doomedIds[i++] = record.getAttributeAsInt(UsersDataSource.Field.ID); + } + + SubjectGWTServiceAsync subjectService = GWTServiceLookup.getSubjectService(); + subjectService.deleteSubjects(doomedIds, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + String message = MSG.dataSource_users_deleteFailed(doomedNames.toString()); + CoreGUI.getErrorHandler().handleError(message, caught); + UsersView.this.refresh(); + } + + public void onSuccess(Void result) { + Message message = new Message(MSG.dataSource_users_delete(doomedNames.toString())); + CoreGUI.getMessageCenter().notify(message); + UsersView.this.refresh(); + } + }); } }; }
commit 0bb55c1b461a27ff009958d825b68e24ad07f6c1 Author: John Sanda jsanda@redhat.com Date: Tue Aug 23 13:40:46 2011 -0400
Add return statement in if block
The if block that is executed when the diff function is called with three arguments was missing a return statement. This caused both file and snapshot diffs to be generated.
diff --git a/etc/cli-scripts/drift.js b/etc/cli-scripts/drift.js index c52c72d..5a1e6e0a 100644 --- a/etc/cli-scripts/drift.js +++ b/etc/cli-scripts/drift.js @@ -55,6 +55,7 @@ function diff(s1, s2) {
var fileDiff = DriftManager.generateUnifiedDiff(e1, e2); foreach(fileDiff.diff, println); + return ""; }
function printEntry(entry) {
commit 544acabdbacec088de0bb2ed46471c2fb79b4055 Author: John Sanda jsanda@redhat.com Date: Tue Aug 23 12:13:27 2011 -0400
Adding javadocs
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java index 8afbeb6..72e9353 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java @@ -22,6 +22,10 @@ package org.rhq.core.domain.drift; import java.io.Serializable; import java.util.List;
+/** + * This is a data structure that encapsulates a file diff and is suitable for use in the + * GWT UI as well as in remote clients. + */ public class FileDiffReport implements Serializable { private static final long serialVersionUID = 1L;
@@ -37,10 +41,17 @@ public class FileDiffReport implements Serializable { this.diff = diff; }
+ /** @return The number of changes in the diff */ public int getNumberOfChanges() { return changes; }
+ /** + * Returns the actual diff as a list of strings where each line corresponds to an + * element in the list. + * + * @return The diff as a list of strings. + */ public List<String> getDiff() { return diff; } 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 23eb0e7..3f8ffa7 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 @@ -379,11 +379,6 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public PageList<Drift> findHistory(Drift drift) { - return null; - } - - @Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) {
// before we do anything, make sure the drift config name is valid 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 290fb81..c6fc043 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 @@ -119,7 +119,14 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR */ String getDriftFileBits(String hash);
+ /** + * Generates a unified diff of the two files references by drift. In the case of a + * modified file, a Drift object references the current and previous versions of the + * file. This method generates a diff of the two versions. + * + * @param drift Specifies the two files that will be compared + * @return A report containing a unified diff of the two versions of the file + * referenced by drift + */ FileDiffReport generateUnifiedDiff(Drift drift); - - PageList<Drift> findHistory(Drift drift); } 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 ab75921..c181e51 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 @@ -59,8 +59,26 @@ public interface DriftManagerRemote { */ String getDriftFileBits(String hash);
+ /** + * Generates a unified diff of the two files references by drift. In the case of a + * modified file, a Drift object references the current and previous versions of the + * file. This method generates a diff of the two versions. + * + * @param drift Specifies the two files that will be compared + * @return A report containing a unified diff of the two versions of the file + * referenced by drift + */ FileDiffReport generateUnifiedDiff(Drift drift);
+ /** + * Generates a unified diff of the two files referenced by drift1 and drift2. More + * specifically, the files referenced by {@link org.rhq.core.domain.drift.Drift#getNewDriftFile()} + * are compared. + * + * @param drift1 References the first file to be compared + * @param drift2 References the second file to be compared + * @return A report containing a unified diff of the two files compared + */ FileDiffReport generateUnifiedDiff(Drift drift1, Drift drift2);
}
commit 8dadee911fe148763f7e5eb48446dd83b4d812ea Author: Ian Springer ian.springer@redhat.com Date: Tue Aug 23 13:02:59 2011 -0400
in the resource creation wizard, if the resource type does not define multiple resource config templates, still show the "info" step since that step also prompts for the resource name, but do not show the template input field, since there is only one possible template (I missed this file in my previous commit)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java index 3bb3456..aeb53ce 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.factory;
import java.util.ArrayList; +import java.util.Collections; import java.util.EnumSet; import java.util.Map;
@@ -80,16 +81,13 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard { ConfigurationDefinition resourceConfigDef = getChildType().getResourceConfigurationDefinition(); this.setNewResourceConfigurationDefinition(resourceConfigDef);
- // Skip the choose-template step if the type does not define a resource config or does not define more than - // one resource config template. - if (resourceConfigDef != null) { - Map<String, ConfigurationTemplate> templates = resourceConfigDef.getTemplates(); - if (templates.size() > 1) { - steps.add(new ResourceFactoryInfoStep(ResourceFactoryCreateWizard.this, MSG - .widget_resourceFactoryWizard_namePrompt(), - MSG.widget_resourceFactoryWizard_configTemplatePrompt(), templates)); - } - } + // Even if the type doesn't define multiple resource config templates, we still need to include the info + // step, since it also prompts for the Resource name. + Map<String, ConfigurationTemplate> templates = (resourceConfigDef != null) ? + resourceConfigDef.getTemplates() : Collections.<String, ConfigurationTemplate>emptyMap(); + steps.add(new ResourceFactoryInfoStep(ResourceFactoryCreateWizard.this, MSG + .widget_resourceFactoryWizard_namePrompt(), + MSG.widget_resourceFactoryWizard_configTemplatePrompt(), templates));
steps.add(new ResourceFactoryConfigurationStep(ResourceFactoryCreateWizard.this));
commit 9a8f17589a51c988f1cd61a7cf7b94b5c3e3e3e5 Author: Ian Springer ian.springer@redhat.com Date: Tue Aug 23 13:02:13 2011 -0400
in the resource creation wizard, if the resource type does not define multiple resource config templates, still show the "info" step since that step also prompts for the resource name, but do not show the template input field, since there is only one possible template; change the label for the template input field from "Templates" to "Template", since the user is selecting a single template
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryInfoStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryInfoStep.java index ad2e1d2..20ebf5f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryInfoStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryInfoStep.java @@ -152,7 +152,7 @@ public class ResourceFactoryInfoStep extends AbstractWizardStep { templateSelect.setAlign(Alignment.LEFT); templateSelect.setWidth(300);
- if (templates != null && !templates.isEmpty()) { + if (templates != null && templates.size() > 1) { templateSelect.setValueMap(templates.keySet().toArray(new String[templates.size()])); templateSelect.setValue("default"); wizard.setNewResourceStartingConfiguration(templates.get("default").createConfiguration()); @@ -166,7 +166,7 @@ public class ResourceFactoryInfoStep extends AbstractWizardStep { } }); } else { - templateSelect.setDisabled(true); + templateSelect.setVisible(false); }
formItems.add(templateSelect); 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 332396b..93e38ab 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 @@ -1815,8 +1815,8 @@ widget_recordEditor_title_new = Create New {0} widget_recordEditor_title_view = View {0} [{1}] widget_recordEditor_warn_validation = One or more fields have invalid values. This [{0}] cannot be saved until these values are corrected widget_resourceFactoryWizard_archPrompt = Package Architecture -widget_resourceFactoryWizard_configTemplatePrompt = Resource Configuration Templates -widget_resourceFactoryWizard_contentTemplatePrompt = Deployment Time Configuration Templates +widget_resourceFactoryWizard_configTemplatePrompt = Resource Configuration Template +widget_resourceFactoryWizard_contentTemplatePrompt = Deployment Configuration Template widget_resourceFactoryWizard_createSubmit = A request to create a resource with the name of [{0}] has been submitted successfully. widget_resourceFactoryWizard_createSubmitType = A request to create a resource of type [{0}] has been submitted successfully. widget_resourceFactoryWizard_createWizardTitle = Create New Resource of Type [{0}]
commit 8a536964575372d7b55b75173d478c367313a285 Author: Ian Springer ian.springer@redhat.com Date: Tue Aug 23 12:59:00 2011 -0400
[BZ 732804] don't show Previous button on the first step of a wizard (https://bugzilla.redhat.com/show_bug.cgi?id=732804)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/WizardView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/WizardView.java index 6b82ade..f8f173d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/WizardView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/wizard/WizardView.java @@ -174,6 +174,10 @@ public class WizardView extends LocatableVLayout { closeDialog(); } }); + buttonBar.addMember(cancelButton); + + buttonBar.addMember(new LayoutSpacer()); + previousButton = new LocatableIButton(extendLocatorId("Previous"), PREVIOUS); previousButton.setDisabled(true); previousButton.addClickHandler(new ClickHandler() { @@ -185,6 +189,11 @@ public class WizardView extends LocatableVLayout { } } }); + if (wizard.getSteps().size() <= 1) { + previousButton.setVisible(false); + } + buttonBar.addMember(previousButton); + nextButton = new LocatableIButton(extendLocatorId("Next"), NEXT); nextButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { @@ -195,17 +204,14 @@ public class WizardView extends LocatableVLayout { } } }); - - buttonBar.addMember(cancelButton); - buttonBar.addMember(new LayoutSpacer()); - buttonBar.addMember(previousButton); buttonBar.addMember(nextButton); - }
private void setStep(final int stepIndex) { + previousButton.setVisible(stepIndex >= 1); + if (stepIndex < 0) { - this.previousButton.setDisabled(true); + previousButton.setDisabled(true); return; }
@@ -235,9 +241,9 @@ public class WizardView extends LocatableVLayout { buttonBar.removeMember(button); } customButtons.clear(); - List<IButton> cbs = wizard.getCustomButtons(currentStep); - if (cbs != null) { - for (IButton button : cbs) { + List<IButton> newCustomButtons = wizard.getCustomButtons(currentStep); + if (newCustomButtons != null) { + for (IButton button : newCustomButtons) { button.setDisabled(true); buttonBar.addMember(button); customButtons.add(button);
commit 10cca68e4230bb141784f44d41eec497fc0e68c5 Author: John Sanda jsanda@redhat.com Date: Tue Aug 23 09:15:41 2011 -0400
Adding function for viewing previous version of file
diff --git a/etc/cli-scripts/drift.js b/etc/cli-scripts/drift.js index 1fa8147..c52c72d 100644 --- a/etc/cli-scripts/drift.js +++ b/etc/cli-scripts/drift.js @@ -78,6 +78,12 @@ function fetchHistory(rid, configName, path) {
this.echo = function(msg) {println(msg);}
+ function findDrift(version) { + return find(entries, function(drift) { + return drift.changeSet.version == version + }); + } +
var generate = function() { entries = []; @@ -99,7 +105,7 @@ function fetchHistory(rid, configName, path) { }); }
- this.display = function() { + this.list = function() { var format = java.text.DateFormat.getDateTimeInstance(); println(path + "\n-----------------------------------"); foreach(entries, function(drift) { @@ -107,14 +113,23 @@ function fetchHistory(rid, configName, path) { }); }
+ this.view = function(version) { + var drift = findDrift(version); + if (drift == null) { + return "Could not find version " + version; + } + return DriftManager.getDriftFileBits(drift.newDriftFile.hashId); + } + this.compare = function(v1, v2) { - var d1 = find(entries, function(drift) { - return drift.changeSet.version == v1; - }); - var d2 = find(entries, function(drift) { - return drift.changeSet.version == v2; - }); - + var d1 = findDrift(v1); + if (d1 == null) { + return "Could not find version " + v1; + } + var d2 = findDrift(v2); + if (d2 == null) { + return "Could not find version " + v2; + } var fileDiff = DriftManager.generateUnifiedDiff(d1, d2); foreach(fileDiff.diff, println); }
commit fb8add5e05d6e8e5a8a08d8bab07dd8cab0a47b4 Author: John Sanda jsanda@redhat.com Date: Tue Aug 23 08:39:43 2011 -0400
Adding more functions for file diffs and fetching file version history
diff --git a/etc/cli-scripts/drift.js b/etc/cli-scripts/drift.js index cddd7de..1fa8147 100644 --- a/etc/cli-scripts/drift.js +++ b/etc/cli-scripts/drift.js @@ -8,7 +8,7 @@ function createSnapshot(rid, cname) { var config = findDriftConfig(rid, function(c) { return cname.equals(c.name) });
- var criteria = BasicDriftChangeSetCriteria(); + var criteria = GenericDriftChangeSetCriteria(); criteria.addFilterResourceId(rid); criteria.addFilterDriftConfigurationId(config.id);
@@ -19,10 +19,10 @@ function createSnapshot(rid, cname) { } }
- return DriftServer.createSnapshot(criteria); + return DriftManager.createSnapshot(criteria); }
-function findDriftConfig(rid, fn) { +function findDriftConfig(rid, filter) { var criteria = ResourceCriteria(); criteria.addFilterId(rid); criteria.fetchDriftConfigurations(true); @@ -31,13 +31,32 @@ function findDriftConfig(rid, fn) { var resource = resources.get(0);
return find(resource.driftConfigurations, function(config) { - return fn(DriftConfiguration(config)); + return filter(DriftConfiguration(config)); }); }
function diff(s1, s2) { var theDiff = s1.diff(s2);
+ if (arguments.length > 2) { + var path = arguments[2]; + + if (theDiff.elementsInConflict.size() == 0) { + // If the snapshot diff reports no files in conflict, then there + // is no need to call the server to perform the file diff. We can + // instead return quickly. + println("There are no differences to report"); + return ""; + } + + var pathFilter = function(entry) { return entry.path == path; }; + var e1 = find(s1.entries, pathFilter); + var e2 = find(s2.entries, pathFilter); + + var fileDiff = DriftManager.generateUnifiedDiff(e1, e2); + foreach(fileDiff.diff, println); + } + function printEntry(entry) { println(entry.newDriftFile.hashId + '\t' + entry.path); } @@ -53,14 +72,77 @@ function diff(s1, s2) { report('elements not in right', theDiff.elementsNotInRight); }
-function filterEntry(props) { - return function(entry) { - var filteredEntry = {}; - foreach(props, function(prop) { - if (entry[prop]) { - filteredEntry[prop] = entry[prop]; - } - }); - return filteredEntry; +function fetchHistory(rid, configName, path) { + function History() { + var entries = []; + + this.echo = function(msg) {println(msg);} + + + var generate = function() { + entries = []; + var criteria = GenericDriftCriteria(); + criteria.addFilterResourceIds([rid]); + criteria.fetchChangeSet(true); + criteria.addFilterPath(path); + + var drifts = DriftManager.findDriftsByCriteria(criteria); + foreach(drifts, function(drift) { + if (drift.changeSet.driftConfiguration.name == configName && + drift.path == path) { + entries.push(drift); + } + }); + + entries.sort(function(d1, d2) { + return d1.changeSet.version <= d2.changeSet.version + }); + } + + this.display = function() { + var format = java.text.DateFormat.getDateTimeInstance(); + println(path + "\n-----------------------------------"); + foreach(entries, function(drift) { + println(drift.changeSet.version + "\t" + format.format(drift.ctime)); + }); + } + + this.compare = function(v1, v2) { + var d1 = find(entries, function(drift) { + return drift.changeSet.version == v1; + }); + var d2 = find(entries, function(drift) { + return drift.changeSet.version == v2; + }); + + var fileDiff = DriftManager.generateUnifiedDiff(d1, d2); + foreach(fileDiff.diff, println); + } + + generate(); } + + return new History(); + +/* + var criteria = GenericDriftCriteria(); + criteria.addFilterResourceIds([rid]); + criteria.fetchChangeSet(true); + criteria.addFilterPath(path); + + var drifts = DriftManager.findDriftsByCriteria(criteria); + var history = []; + foreach(drifts, function(drift) { + if (drift.changeSet.driftConfiguration.name == configName && + drift.path == path) { + history.push(drift); + } + }); + + history.sort(function(d1, d2) { + return d1.changeSet.version <= d2.changeSet.version + }); + + return history; +*/ }
commit 846a462e4b52222fe689330bcb7621028def0e06 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 22 20:09:43 2011 -0400
Folks claim the spinner still exists, so give back its space.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 72c3529..5e935ab 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -60,7 +60,7 @@ public class Footer extends LocatableHLayout { messageBar = new MessageBar();
// leave space for the RPC Activity Spinner (I think this has been removed, giving back the space) - // addMember(createHSpacer(16)); + addMember(createHSpacer(16));
addMember(messageBar);
commit c885793a7c649e94c60e2a0bf271bcfe83e4176c Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 18:12:04 2011 -0400
skip the template selection step in resource-create wizard if resource config def does not define more than one template; do not assume resource config defs or plugin config defs define a default template
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/AbstractResourceFactoryWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/AbstractResourceFactoryWizard.java index c94fae3..ef74a72 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/AbstractResourceFactoryWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/AbstractResourceFactoryWizard.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.factory;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizard; @@ -104,8 +105,9 @@ public abstract class AbstractResourceFactoryWizard extends AbstractWizard { || !this.newResourceConfigurationDefinition.equals(newResourceConfigurationDefinition)) { this.newResourceConfigurationDefinition = newResourceConfigurationDefinition; if (newResourceConfigurationDefinition != null) { - this.newResourceStartingConfiguration = this.newResourceConfigurationDefinition.getDefaultTemplate() - .createConfiguration(); + ConfigurationTemplate defaultTemplate = this.newResourceConfigurationDefinition.getDefaultTemplate(); + this.newResourceStartingConfiguration = (defaultTemplate != null) ? + defaultTemplate.createConfiguration() : new Configuration(); } } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java index ee48168..3bb3456 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java @@ -20,7 +20,6 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.factory;
import java.util.ArrayList; import java.util.EnumSet; -import java.util.LinkedHashMap; import java.util.Map;
import com.google.gwt.user.client.rpc.AsyncCallback; @@ -80,15 +79,17 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard {
ConfigurationDefinition resourceConfigDef = getChildType().getResourceConfigurationDefinition(); this.setNewResourceConfigurationDefinition(resourceConfigDef); - Map<String, ConfigurationTemplate> templates; - if (resourceConfigDef == null) { - templates = new LinkedHashMap<String, ConfigurationTemplate>(); - } else { - templates = resourceConfigDef.getTemplates(); + + // Skip the choose-template step if the type does not define a resource config or does not define more than + // one resource config template. + if (resourceConfigDef != null) { + Map<String, ConfigurationTemplate> templates = resourceConfigDef.getTemplates(); + if (templates.size() > 1) { + steps.add(new ResourceFactoryInfoStep(ResourceFactoryCreateWizard.this, MSG + .widget_resourceFactoryWizard_namePrompt(), + MSG.widget_resourceFactoryWizard_configTemplatePrompt(), templates)); + } } - steps.add(new ResourceFactoryInfoStep(ResourceFactoryCreateWizard.this, MSG - .widget_resourceFactoryWizard_namePrompt(), MSG.widget_resourceFactoryWizard_configTemplatePrompt(), - templates));
steps.add(new ResourceFactoryConfigurationStep(ResourceFactoryCreateWizard.this));
@@ -141,8 +142,6 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_createSubmitType(getChildType().getName()), Message.Severity.Info)); getView().closeDialog(); - // try a refresh now but the resource may not get created fast enough to show up. - CoreGUI.refresh(); } });
@@ -165,8 +164,6 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_createSubmit(newResourceName), Message.Severity.Info)); getView().closeDialog(); - // try a refresh now but the resource may not get created fast enough to show up. - CoreGUI.refresh(); } });
commit e3d08a550739f693aa760c3d3ea6b073650461d2 Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 18:10:11 2011 -0400
minor - add missing class-level javadoc, extract out a var for easier debugging, improve a comment
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java index f16a071..e2c242c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/BundleDeployWizard.java @@ -33,6 +33,10 @@ import org.rhq.enterprise.gui.coregui.client.components.wizard.WizardStep; import org.rhq.enterprise.gui.coregui.client.gwt.BundleGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+/** + * @author Jay Shaughnessy + * + */ public class BundleDeployWizard extends AbstractBundleDeployWizard {
// Initial Deployment, No Bundle Selected diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java index a7840f4..42d1c70 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentConfigStep.java @@ -29,6 +29,10 @@ import org.rhq.enterprise.gui.coregui.client.components.configuration.Configurat import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
+/** + * @author Jay Shaughnessy + * + */ public class GetDeploymentConfigStep extends AbstractWizardStep {
private final BundleDeployWizard wizard; @@ -62,11 +66,8 @@ public class GetDeploymentConfigStep extends AbstractWizardStep { Configuration startingConfig; if (wizard.getLiveDeployment() == null) { ConfigurationTemplate defaultTemplate = configDef.getDefaultTemplate(); - if (defaultTemplate == null) { - startingConfig = new Configuration(); - } else { - startingConfig = defaultTemplate.createConfiguration(); - } + startingConfig = (defaultTemplate != null) ? defaultTemplate.createConfiguration() : + new Configuration(); } else { startingConfig = getNormalizedLiveConfig(configDef); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentOptionsStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentOptionsStep.java index a29547b..171bcb1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentOptionsStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDeploymentOptionsStep.java @@ -30,6 +30,10 @@ import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardSte 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 GetDeploymentOptionsStep extends AbstractWizardStep {
static private final String DEPLOY_LATER = "later"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java index 7459562..871329b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/GetDestinationStep.java @@ -57,6 +57,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+/** + * @author Jay Shaughnessy + * + */ public class GetDestinationStep extends AbstractWizardStep {
private final BundleGWTServiceAsync bundleServer = GWTServiceLookup.getBundleService(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleStep.java index 1017215..3b59b3a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleStep.java @@ -30,6 +30,10 @@ import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelecto import org.rhq.enterprise.gui.coregui.client.components.wizard.AbstractWizardStep; import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable;
+/** + * @author Jay Shaughnessy + * + */ public class SelectBundleStep extends AbstractWizardStep {
private final BundleDeployWizard wizard; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleVersionStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleVersionStep.java index e1367e8..e68d159 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleVersionStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/deploy/SelectBundleVersionStep.java @@ -40,6 +40,10 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; 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 SelectBundleVersionStep extends AbstractWizardStep {
static private final String LATEST_VERSION = "latest"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java index 0f001e5..1c12b98 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java @@ -49,6 +49,7 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.JobTrigger; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -426,8 +427,8 @@ public abstract class AbstractOperationScheduleDetailsView extends this.operationParametersConfigurationHolder.addMember(horizontalSpacer);
if (isNewRecord()) { - this.operationParameters = (parametersDefinition.getDefaultTemplate() != null) ? parametersDefinition - .getDefaultTemplate().createConfiguration() + ConfigurationTemplate defaultTemplate = parametersDefinition.getDefaultTemplate(); + this.operationParameters = (defaultTemplate != null) ? defaultTemplate.createConfiguration() : new Configuration(); } else {
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java index 365c07c..721970b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java @@ -54,7 +54,8 @@ public class ResourceFactoryImportWizard extends AbstractResourceFactoryWizard {
ArrayList<WizardStep> steps = new ArrayList<WizardStep>();
- // skip the info step if the type has only the default template to offer for user selection or no plugin config + // Skip the choose-template step if the type does not define a plugin config or does not define more than one + // plugin config template. if (childTypePluginConfigDef != null) { Map<String, ConfigurationTemplate> templates = childTypePluginConfigDef.getTemplates(); if (templates.size() > 1) { @@ -97,8 +98,6 @@ public class ResourceFactoryImportWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_importSubmitted(getChildType().getName()), Message.Severity.Info)); getView().closeDialog(); - // try a refresh now but the resource may not get added fast enough to show up. - CoreGUI.refresh(); } }); }
commit ff5bb9e3f225e8430a4a4a749d1c2f937829ef2d Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 18:05:34 2011 -0400
[BZ 705713] always make all properties, even read-only ones, writable in the config editors in the create-resource and import-resource wizards (https://bugzilla.redhat.com/show_bug.cgi?id=705713)
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 cda038d..438f73b 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 @@ -171,6 +171,7 @@ public class ConfigurationEditor extends LocatableVLayout {
private String editorTitle = null; private boolean readOnly = false; + private boolean allPropertiesWritable = false; private Map<String, String> invalidPropertyNameToDisplayNameMap = new HashMap<String, String>(); private Set<PropertyValueChangeListener> propertyValueChangeListeners = new HashSet<PropertyValueChangeListener>();
@@ -238,6 +239,14 @@ public class ConfigurationEditor extends LocatableVLayout { this.readOnly = readOnly; }
+ public boolean isAllPropertiesWritable() { + return allPropertiesWritable; + } + + public void setAllPropertiesWritable(boolean allPropertiesWritable) { + this.allPropertiesWritable = allPropertiesWritable; + } + public String getEditorTitle() { return editorTitle; } @@ -971,7 +980,8 @@ public class ConfigurationEditor extends LocatableVLayout { }); fieldsList.add(editField);
- if (!(readOnly || propertyDefinitionList.isReadOnly())) { + boolean propertyReadOnly = (readOnly || (!allPropertiesWritable && propertyDefinitionList.isReadOnly())); + if (!propertyReadOnly) { ListGridField removeField = new ListGridField("remove", 20); removeField.setType(ListGridFieldType.ICON); removeField.setCellIcon(Window.getImgURL(ImageManager.getRemoveIcon())); @@ -1013,7 +1023,7 @@ public class ConfigurationEditor extends LocatableVLayout {
ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100(); - if (!(readOnly || propertyDefinitionList.isReadOnly())) { + if (!propertyReadOnly) { IButton addRowButton = new IButton(); addRowButton.setIcon(Window.getImgURL("[SKIN]/actions/add.png")); addRowButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { @@ -1469,6 +1479,9 @@ public class ConfigurationEditor extends LocatableVLayout { if (this.readOnly) { return true; } + if (this.allPropertiesWritable) { + return false; + } String errorMessage = property.getErrorMessage(); if ((errorMessage != null) && (!errorMessage.trim().equals(""))) { // special case 1: property has a plugin-set error message - allow user to edit it even if it's a read-only prop, diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java index a05974a..ddd821b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java @@ -37,6 +37,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.Locatable; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** + * This step displays a config editor for the user to enter the new Resource's initial Resource or plugin configuration. + * * @author Jay Shaughnessy * @author Greg Hinkle */ @@ -100,12 +102,14 @@ public class ResourceFactoryConfigurationStep extends AbstractWizardStep {
public void onFailure(Throwable throwable) { editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), def, startingConfig); + editor.setAllPropertiesWritable(true); vLayout.addMember(editor, 0);
}
public void onSuccess(ConfigurationDefinition result) { editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), result, startingConfig); + editor.setAllPropertiesWritable(true); vLayout.addMember(editor, 0); } }); diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstallationInfo.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstallationInfo.java index 3c43ac4..fe13a7a 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstallationInfo.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/helper/JBossInstallationInfo.java @@ -51,6 +51,10 @@ public class JBossInstallationInfo { public JBossInstallationInfo(File installationDir) throws IOException { File binDir = new File(installationDir, "bin"); File runJar = new File(binDir, "run.jar"); + if (!runJar.exists()) { + throw new RuntimeException(runJar + " does not exist - " + installationDir + + " does not appear to be a JBoss installation/home directory."); + } Attributes jarManifestAttributes = loadManifestAttributesFromJar(runJar); this.productType = JBossProductType.determineJBossProductType(jarManifestAttributes); this.version = getVersion(jarManifestAttributes); diff --git a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstallationInfo.java b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstallationInfo.java index 23e2fe2..39507ef 100644 --- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstallationInfo.java +++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/helper/JBossInstallationInfo.java @@ -47,7 +47,11 @@ public class JBossInstallationInfo {
public JBossInstallationInfo(File installationDir) throws IOException { File binDir = new File(installationDir, "bin"); - File runJar = new File(binDir, "run.jar"); + File runJar = new File(binDir, "run.jar"); + if (!runJar.exists()) { + throw new RuntimeException(runJar + " does not exist - " + installationDir + + " does not appear to be a JBoss installation/home directory."); + } Attributes jarManifestAttributes = loadManifestAttributesFromJar(runJar); this.productType = JBossProductType.determineJBossProductType(jarManifestAttributes); this.version = getVersion(jarManifestAttributes);
commit ded5c12883f1d64d57d01f8d8458c99d77956f18 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 22 17:30:10 2011 -0400
[BZ 729132 - New alerts lookup failed] People complained about the alert count widget (the flag at the far left of the message bar) because it didn't serve much purpose, took up message real estate, and was refreshed in a background job that would sometimes generate an exception if server comm was compromised. So, this commit rips it out. - also removes the reserved space for the rpc spinner. I think took that out, so let the message bar expand all the way to the left.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 24841e3..72c3529 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -18,24 +18,13 @@ */ package org.rhq.enterprise.gui.coregui.client;
-import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; -import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.widgets.events.ClickEvent; -import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
-import org.rhq.core.domain.alert.Alert; -import org.rhq.core.domain.alert.AlertPriority; -import org.rhq.core.domain.criteria.AlertCriteria; -import org.rhq.core.domain.criteria.Criteria.Restriction; -import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.gui.coregui.client.alert.AlertHistoryView; import org.rhq.enterprise.gui.coregui.client.footer.FavoritesButton; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; -import org.rhq.enterprise.gui.coregui.client.report.ReportTopView; import org.rhq.enterprise.gui.coregui.client.util.message.MessageBar; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenterView; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; @@ -68,16 +57,13 @@ public class Footer extends LocatableHLayout {
messageCenter = new MessageCenterView(extendLocatorId(MessageCenterView.LOCATOR_ID)); final FavoritesButton favoritesButton = new FavoritesButton(extendLocatorId("Favorites")); - final AlertsMessage alertsMessage = new AlertsMessage(extendLocatorId("Alerts")); messageBar = new MessageBar();
- // leave space for the RPC Activity Spinner - addMember(createHSpacer(16)); + // leave space for the RPC Activity Spinner (I think this has been removed, giving back the space) + // addMember(createHSpacer(16));
addMember(messageBar);
- addMember(alertsMessage); - VLayout favoritesLayout = new VLayout(); favoritesLayout.setHeight100(); favoritesLayout.setAutoWidth(); @@ -87,35 +73,7 @@ public class Footer extends LocatableHLayout {
addMember(getMessageCenterButton());
- // people don't like the refresh and CoreGUI.refresh() isn't refreshing everything I want - // if we ever want to reintroduce the refresh button to manually call CoreGUI.refresh(), just uncomment this line - // addMember(getRefreshButton()); - addMember(createHSpacer(0)); - - alertsMessage.schedule(60000); - } - - private LocatableVLayout getRefreshButton() { - LocatableVLayout layout = new LocatableVLayout(extendLocatorId("refreshLayout")); - layout.setHeight100(); - layout.setAlign(Alignment.CENTER); - layout.setAutoWidth(); - - LocatableIButton button = new LocatableIButton(extendLocatorId("refreshButton"), ""); - button.setAlign(Alignment.CENTER); - button.setAutoFit(true); - button.setIcon("[SKIN]/actions/refresh.png"); - button.setPrompt(CoreGUI.getMessages().common_button_refresh()); - button.addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - CoreGUI.refresh(); - } - }); - - layout.addMember(button); - return layout; }
private LocatableVLayout getMessageCenterButton() { @@ -139,6 +97,8 @@ public class Footer extends LocatableHLayout { return layout; }
+ // Leaving this although it's unused. It used to be the subclass for the alert count mechanism, which is now + // gone, but this may be useful in the future for something else. public abstract static class RefreshableLabel extends LocatableLabel { public RefreshableLabel(String locatorId) { super(locatorId); @@ -176,57 +136,6 @@ public class Footer extends LocatableHLayout { } }
- public static class AlertsMessage extends RefreshableLabel { - public AlertsMessage(String locatorId) { - super(locatorId); - setHeight100(); - setWidth(25); - setPadding(5); - setHoverWidth(200); - setIconSize(16); - setWrap(false); - changeIcon(0); - addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - History.newItem(ReportTopView.VIEW_ID.getName() + "/" + ReportTopView.SECTION_SUBSYSTEMS_VIEW_ID - + "/" + AlertHistoryView.SUBSYSTEM_VIEW_ID); - } - }); - } - - private void changeIcon(int alertCount) { - if (alertCount == 0) { - setPrompt(MSG.view_core_noRecentAlerts()); - setContents(imgHTML("subsystems/alert/Alerts_16.png", 16, 16) - + "<span style="display:inline-block; vertical-align:middle">0</span>"); - } else { - setPrompt(MSG.view_core_recentAlerts(String.valueOf(alertCount))); - String link = '#' + ReportTopView.VIEW_ID.getName() + "/" + ReportTopView.SECTION_SUBSYSTEMS_VIEW_ID - + "/" + AlertHistoryView.SUBSYSTEM_VIEW_ID; - setContents("<a href="" + link + "">" + imgHTML(ImageManager.getAlertIcon(AlertPriority.HIGH)) - + "<span style="display:inline-block; vertical-align:middle">" + String.valueOf(alertCount) - + "</span></a>"); - } - } - - public void refreshLoggedIn() { - AlertCriteria alertCriteria = new AlertCriteria(); - alertCriteria.addFilterStartTime(System.currentTimeMillis() - (1000L * 60 * 60 * 8)); // last 8 hrs - alertCriteria.setRestriction(Restriction.COUNT_ONLY); - - GWTServiceLookup.getAlertService().findAlertsByCriteria(alertCriteria, - new AsyncCallback<PageList<Alert>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_core_error_1(), caught); - } - - public void onSuccess(PageList<Alert> result) { - changeIcon(result.getTotalSize()); - } - }); - } - } - public MessageBar getMessageBar() { return messageBar; } 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 c4866f4..332396b 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 @@ -1099,7 +1099,6 @@ view_connectionSettingsDetails_messageConcise_updateSuccess = Connection setting view_connectionSettingsDetails_messageDetailed_updateSuccess = Connection settings update initiated for Resource [{0}]. view_connectionSettingsDetails_noPermission = You do not have permission to edit this Resource''s connection settings. view_connectionSettingsDetails_somePropertiesInvalid = The following connection settings have invalid values: {0}. The values must be corrected before the settings can be saved. -view_core_error_1 = New Alerts lookup failed view_core_loggedOut = Logged out view_core_noRecentAlerts = There are no recent alerts to report view_core_recentAlerts = There are [{0}] recent alerts - click to go to the recent alerts report 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 691a934..19d264b 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 @@ -924,7 +924,6 @@ view_connectionSettingsDetails_error_updateFailure = Failed to update connection ##view_connectionSettingsDetails_messageDetailed_updateSuccess = Connection settings update initiated for Resource [{0}].\n view_connectionSettingsDetails_noPermission = You do not have permission to edit this Resource''s connection settings.~ view_connectionSettingsDetails_somePropertiesInvalid = The following connection settings have invalid values: {0}. The values must be corrected before the settings can be saved.~ -view_core_error_1 = Konnte keine Alarminformationen laden view_core_loggedOut = Ausgeloggt view_core_noRecentAlerts = Es liegen keine frischen Alarme vor view_core_recentAlerts = [{0}] frische Alarme 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 5b6d34e..2cc6d6b 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 @@ -1085,7 +1085,6 @@ view_connectionSettingsDetails_messageConcise_updateSuccess = ã³ãã¯ã·ã§ã³ view_connectionSettingsDetails_messageDetailed_updateSuccess = ãªãœãŒã¹ [{0} ã®ããã®ã³ãã¯ã·ã§ã³èšå®ãæŽæ°ãããŸãã view_connectionSettingsDetails_noPermission = ãã®ãªãœãŒã¹ã®ã³ãã¯ã·ã§ã³èšå®ãç·šéããæš©éããããŸãã view_connectionSettingsDetails_somePropertiesInvalid = 次ã®ã³ãã¯ã·ã§ã³èšå®ã¯äžæ£ãªå€: {0} ã§ããèšå®ãä¿åããåã«èšæ£ããªããã°ãªããŸããã -view_core_error_1 = æ°èŠã¢ã©ãŒãã®åç §ã«å€±æããŸãã #view_core_loggedInAs = Logged in as {0} view_core_loggedOut = ãã°ã¢ãŠã view_core_noRecentAlerts = ã¬ããŒããã¹ãæè¿ã®ã¢ã©ãŒãã¯ååšããŸãã 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 ef72d35..ecc380d 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 @@ -1117,7 +1117,6 @@ view_connectionSettingsDetails_error_updateFailure = Falha ao atualizar as propr ##view_connectionSettingsDetails_messageDetailed_updateSuccess = Propriedades de conexï¿œo do Recurso [{0}] atualizadas view_connectionSettingsDetails_noPermission = Vocï¿œ nï¿œo possui permissï¿œo para editar as propriedades de conexï¿œo do Recurso. view_connectionSettingsDetails_somePropertiesInvalid = As seguintes propriedades de conexï¿œo estï¿œo incorretas: {0}. Os valores devem ser corrigidos antes de serem salvos. -view_core_error_1 = Falha ao perquisar novos alertas view_core_loggedInAs = Logado como {0} view_core_loggedOut = Desconectado view_core_noRecentAlerts = Nï¿œo existem alertas recentes 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 f0dd375..ff0bca8 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 @@ -1095,7 +1095,6 @@ view_connectionSettingsDetails_error_updateFailure = \u66f4\u65b0\u8fde\u63a5\u8 ##view_connectionSettingsDetails_messageDetailed_updateSuccess = \u8d44\u6e90 [{0}]\u7684\u8fde\u63a5\u8bbe\u7f6e\u5df2\u7ecf\u66f4\u65b0. view_connectionSettingsDetails_noPermission = \u60a8\u6ca1\u6709\u6743\u9650\u7f16\u8f91\u6b64\u8d44\u6e90\u7684\u8fde\u63a5\u8bbe\u7f6e. view_connectionSettingsDetails_somePropertiesInvalid = \u4e0b\u9762\u7684\u8fde\u63a5\u8bbe\u7f6e\u4fe1\u606f\u586b\u5199\u4e86\u975e\u6cd5\u7684\u503c: {0}. \u5fc5\u987b\u4fee\u6539\u6b64\u4fe1\u606f\u4ee5\u4fbf\u4fdd\u5b58\u6b64\u8bbe\u7f6e. -view_core_error_1 = \u67e5\u627e\u65b0\u544a\u8b66\u4fe1\u606f\u5931\u8d25 view_core_loggedOut = \u9000\u51fa\u767b\u5f55 view_core_noRecentAlerts = \u6ca1\u6709\u65b0\u4ea7\u751f\u7684\u544a\u8b66\u4fe1\u606f view_core_recentAlerts = \u65b0\u4ea7\u751f [{0}] \u6761\u544a\u8b66 - \u70b9\u51fb\u8df3\u8f6c\u5230\u65b0\u544a\u8b66\u62a5\u8868\u754c\u9762
commit 28ad282ea3d014f3fb4483e2a311958f7e425299 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 22 17:16:10 2011 -0400
[BZ 715380 - Uncaught exception defining Alert that triggers CLI script] The gui exception in this bz seems to have been fixed previously. But there was an additional issue that prevented scripts from running because it tried to run them without a session. This may have worked in the past, well back, before we fixed our session handling, because the sender may have been able to piggyback on an existing session. For example, if rhqadmin was logged into a gui session, and the script was beng run as rhqadmin, it would have worked. But no more. So, this fix from mazz gives the runner a proper session. Note that a very small portion of the script's timeout period is now devoted to generating a script engine with a valid session. Also, the session is now eagerly terminated in a finally. scrip
diff --git a/modules/enterprise/server/plugins/alert-cli/src/main/java/org/rhq/enterprise/server/plugins/alertCli/CliSender.java b/modules/enterprise/server/plugins/alert-cli/src/main/java/org/rhq/enterprise/server/plugins/alertCli/CliSender.java index 16c7644..3aab6a2 100644 --- a/modules/enterprise/server/plugins/alert-cli/src/main/java/org/rhq/enterprise/server/plugins/alertCli/CliSender.java +++ b/modules/enterprise/server/plugins/alert-cli/src/main/java/org/rhq/enterprise/server/plugins/alertCli/CliSender.java @@ -110,9 +110,16 @@ public class CliSender extends AlertSender<CliComponent> { SenderResult result = new SenderResult(); BufferedReader reader = null; ScriptEngine engine = null; + Subject subjectWithSession = null; + final SessionManager sessionManager = SessionManager.getInstance(); + try { final Config config = getConfig();
+ // simulate the login by getting a session ID + config.subject = sessionManager.put(config.subject, pluginComponent.getScriptTimeout() * 1000); + subjectWithSession = config.subject; + result.setSummary(createSummary(config, SUMMARY_TEMPLATE));
ByteArrayOutputStream scriptOutputStream = new ByteArrayOutputStream(); @@ -133,11 +140,7 @@ public class CliSender extends AlertSender<CliComponent> { Thread scriptRunner = new Thread(new Runnable() { public void run() { try { - //fake the login - config.subject = SessionManager.getInstance().put(config.subject, - pluginComponent.getScriptTimeout() * 1000); sandbox.eval(rdr); - SessionManager.getInstance().invalidate(config.subject.getSessionId()); } catch (ScriptException e) { exceptionHolder.scriptException = e; } @@ -187,6 +190,9 @@ public class CliSender extends AlertSender<CliComponent> { result.addFailureMessage(ThrowableUtil.getAllMessages(e, true, remainingResultSize(result))); return result; } finally { + if (subjectWithSession != null) { + sessionManager.invalidate(subjectWithSession.getSessionId()); + } if (engine != null) { returnEngine(engine); }
commit de96edb84ca67d3d3a227d5268adb3bb4c22a117 Author: John Sanda jsanda@redhat.com Date: Mon Aug 22 17:23:45 2011 -0400
Add method for generating diff between any two Drift objects
This version of generateUnifiedDiff takes two Drift objects and compares the files referenced by their newDriftFile properties.
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 3497520..23eb0e7 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 @@ -364,6 +364,21 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override + public FileDiffReport generateUnifiedDiff(Drift drift1, Drift drift2) { + String content1 = getDriftFileBits(drift1.getNewDriftFile().getHashId()); + List<String> content1List = asList(content1.split("\n")); + + String content2 = getDriftFileBits(drift2.getNewDriftFile().getHashId()); + List<String> content2List = asList(content2.split("\n")); + + Patch patch = DiffUtils.diff(content1List, content2List); + List<String> deltas = DiffUtils.generateUnifiedDiff(drift1.getPath(), drift2.getPath(), content1List, patch, + 10); + + return new FileDiffReport(patch.getDeltas().size(), deltas); + } + + @Override public PageList<Drift> findHistory(Drift drift) { return null; } 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 fd33467..ab75921 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 @@ -61,4 +61,6 @@ public interface DriftManagerRemote {
FileDiffReport generateUnifiedDiff(Drift drift);
+ FileDiffReport generateUnifiedDiff(Drift drift1, Drift drift2); + }
commit b1771757b971949dfe69cccfaa062c957bfc03ff Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 15:44:43 2011 -0400
[BZ 732090] fix so user can only select a single item at a time from the left-side navigation menus on the Inventory, Reports, Administration, Help, and Test top views (https://bugzilla.redhat.com/show_bug.cgi?id=732090)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/view/AbstractSectionedLeftNavigationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/view/AbstractSectionedLeftNavigationView.java index 3e0e169..c677777 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/view/AbstractSectionedLeftNavigationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/view/AbstractSectionedLeftNavigationView.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 @@ -26,6 +26,7 @@ import java.util.Map; import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; +import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.events.CellClickEvent; @@ -133,6 +134,7 @@ public abstract class AbstractSectionedLeftNavigationView extends LocatableHLayo final TreeGrid treeGrid = new LocatableTreeGrid(navigationSection.getName()); treeGrid.setLeaveScrollbarGap(false); treeGrid.setShowHeader(false); + treeGrid.setSelectionType(SelectionStyle.SINGLE);
List<NavigationItem> navigationItems = navigationSection.getNavigationItems(); TreeNode[] treeNodes = new TreeNode[navigationItems.size()];
commit 4c29315efa25abf0c2135c8b8397f3570c74bd94 Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 15:14:02 2011 -0400
[BZ 676756] fix a few corner case NPEs in original fix; log failure to select tab as warning rather than info and pass Exception to ensure log message includes the stack trace
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 3c7e33c..0caeb61 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 @@ -502,6 +502,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements this.refreshButton = new LocatableIButton(extendLocatorId("Refresh"), MSG.common_button_refresh()); refreshButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { + disableAllFooterControls(); refresh(); } }); @@ -530,8 +531,8 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements }
private void disableAllFooterControls() { - for (TableActionInfo tableActionToDisable : tableActions) { - tableActionToDisable.actionCanvas.disable(); + for (TableActionInfo tableAction : tableActions) { + tableAction.actionCanvas.disable(); } for (Canvas extraWidget : extraWidgetsAboveFooter) { extraWidget.disable(); @@ -539,7 +540,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements for (Canvas extraWidget : extraWidgetsInMainFooter) { extraWidget.disable(); } - if (isShowFooterRefresh()) { + if (isShowFooterRefresh() && this.refreshButton != null) { this.refreshButton.disable(); } } @@ -607,9 +608,6 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements */ public void refresh() { if (this.listGrid != null) { - if (isShowFooter()) { - disableAllFooterControls(); - } Criteria criteria = getCurrentCriteria(); this.listGrid.setCriteria(criteria); this.listGrid.invalidateCache(); @@ -911,7 +909,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements } } refreshRowCount(); - if (isShowFooterRefresh()) { + if (isShowFooterRefresh() && this.refreshButton != null) { this.refreshButton.enable(); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java index 5f1833f..e580b9c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java @@ -290,7 +290,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo
} catch (Exception e) { this.tabSet.enable(); - Log.info("Failed to select tab " + tabName + "/" + subtabName + ": " + e); + Log.warn("Failed to select tab " + tabName + "/" + subtabName + ".", e); } }
commit 04308a0367d5684ab89ab7e9589e47d2c1f2e89b Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 22 13:31:29 2011 -0400
[BZ 676756] when any action button in a table's footer is clicked, disable all buttons and other controls in the footer until that action completes; this fixes https://bugzilla.redhat.com/show_bug.cgi?id=676756 and should also prevent a bunch of other similar quick clicking issues
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 2ae4ee2..3c7e33c 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 @@ -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 @@ -95,7 +95,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * trivial, you must get it peer reviewed. Send out your proposed changes * to the dev mailing list and ask for comments. Any problems introduced to * this class are magnified because it is used in so many UI views and problems - * are hard to detect due to the varies ways it is used. + * are hard to detect due to the various ways it is used. * * @author Greg Hinkle * @author Ian Springer @@ -143,6 +143,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements protected List<Canvas> extraWidgetsInMainFooter = new ArrayList<Canvas>(); private LocatableToolStrip footer; private LocatableToolStrip footerExtraWidgets; + private LocatableIButton refreshButton;
public Table(String locatorId) { this(locatorId, null, null, null, null, true); @@ -441,8 +442,8 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements button.setOverflow(Overflow.VISIBLE); button.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { + disableAllFooterControls(); if (tableAction.confirmMessage != null) { - String message = tableAction.confirmMessage.replaceAll("\#", String.valueOf(listGrid .getSelection().length));
@@ -450,6 +451,8 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements public void execute(Boolean confirmed) { if (confirmed) { tableAction.action.executeAction(listGrid.getSelection(), null); + } else { + refreshTableInfo(); } } }); @@ -469,9 +472,8 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements for (final String key : menuEntries.keySet()) { MenuItem item = new MenuItem(key); item.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() { - - @Override public void onClick(MenuItemClickEvent event) { + disableAllFooterControls(); tableAction.getAction().executeAction(listGrid.getSelection(), menuEntries.get(key)); } }); @@ -497,7 +499,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements footer.addMember(new LayoutSpacer());
if (isShowFooterRefresh()) { - IButton refreshButton = new LocatableIButton(extendLocatorId("Refresh"), MSG.common_button_refresh()); + this.refreshButton = new LocatableIButton(extendLocatorId("Refresh"), MSG.common_button_refresh()); refreshButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { refresh(); @@ -527,6 +529,21 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements refreshTableInfo(); }
+ private void disableAllFooterControls() { + for (TableActionInfo tableActionToDisable : tableActions) { + tableActionToDisable.actionCanvas.disable(); + } + for (Canvas extraWidget : extraWidgetsAboveFooter) { + extraWidget.disable(); + } + for (Canvas extraWidget : extraWidgetsInMainFooter) { + extraWidget.disable(); + } + if (isShowFooterRefresh()) { + 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 table @@ -590,6 +607,9 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements */ public void refresh() { if (this.listGrid != null) { + if (isShowFooter()) { + disableAllFooterControls(); + } Criteria criteria = getCurrentCriteria(); this.listGrid.setCriteria(criteria); this.listGrid.invalidateCache(); @@ -863,7 +883,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements }
protected void refreshTableInfo() { - if (showFooter && null != this.listGrid) { + if (this.showFooter && (this.listGrid != null)) { if (this.tableActionDisableOverride) { this.listGrid.setSelectionType(SelectionStyle.NONE); } else { @@ -871,24 +891,29 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements }
//int selectionCount = this.listGrid.getSelection().length; - for (TableActionInfo tableAction : tableActions) { + for (TableActionInfo tableAction : this.tableActions) { if (tableAction.actionCanvas != null) { // if null, we haven't initialized our buttons yet, so skip this boolean enabled = (!this.tableActionDisableOverride && tableAction.action.isEnabled(this.listGrid .getSelection())); tableAction.actionCanvas.setDisabled(!enabled); } } - for (Canvas extraWidget : extraWidgetsAboveFooter) { + for (Canvas extraWidget : this.extraWidgetsAboveFooter) { + extraWidget.enable(); if (extraWidget instanceof TableWidget) { ((TableWidget) extraWidget).refresh(this.listGrid); } } - for (Canvas extraWidget : extraWidgetsInMainFooter) { + for (Canvas extraWidget : this.extraWidgetsInMainFooter) { + extraWidget.enable(); if (extraWidget instanceof TableWidget) { ((TableWidget) extraWidget).refresh(this.listGrid); } } refreshRowCount(); + if (isShowFooterRefresh()) { + this.refreshButton.enable(); + } } }
commit de0e2844e6588790e1f07842d41bdeb33ab5480a Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 22 14:54:14 2011 -0400
[BZ 730991 - Left nav tree does not refresh after resource creation] Two things done here: First, In the resource search views we now perform a CoreGUI refresh after uninv/delete/import/create. This updates the tree but in all cases other than uninventory (and maybe import), the action is actually async and depends on agent interaction, and possible a discovery run. If async stuff finishes very quickly it may get picked up by the refresh but it probably will not. So, second, The resource tree resource and autogroup nodes now offer 'Refresh' in the context menu. This will refresh the subtree below the node (for autogroups, below the parent resource node). So, a user can perform a point refresh of the tree as desired. Note that group trees do not offer refresh. Mixed groups show only the top node anyway, so it's not needed. Compat group trees really require a full CoreGUI refresh to build from the top down, and we already do that on membership change. So, a refresh in the context menu is not really needed/feasbible.
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 525f92c..6f552c8 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 @@ -40,6 +40,8 @@ import com.smartgwt.client.widgets.menu.MenuItem; import com.smartgwt.client.widgets.menu.MenuItemSeparator; import com.smartgwt.client.widgets.menu.events.ClickHandler; import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent; +import com.smartgwt.client.widgets.tree.Tree; +import com.smartgwt.client.widgets.tree.TreeNode;
import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.DashboardCriteria; @@ -58,11 +60,14 @@ import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.inventory.groups.graph.ResourceGroupGraphPortlet; 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.inventory.resource.detail.ResourceTreeDatasource.AutoGroupTreeNode; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.ResourceTreeNode; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu;
/** + * @author Jay Shaughnessy * @author Greg Hinkle */ public class ResourceGroupContextMenu extends LocatableMenu { @@ -78,7 +83,7 @@ public class ResourceGroupContextMenu extends LocatableMenu { super(locatorId); }
- public void showContextMenu(final ResourceGroup group) { + public void showContextMenu(final Tree tree, final TreeNode node, final ResourceGroup group) { // we need the group composite to access permissions for context menu authz, so get it now ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(group.getId()); @@ -107,13 +112,13 @@ public class ResourceGroupContextMenu extends LocatableMenu { CoreGUI.getErrorHandler().handleError( MSG.view_group_detail_failLoadComp(String.valueOf(group.getId()))); } else { - showContextMenu(result.get(0)); + showContextMenu(tree, node, result.get(0)); } } }); }
- public void showContextMenu(ResourceGroupComposite groupComposite) { + public void showContextMenu(final Tree tree, final TreeNode node, ResourceGroupComposite groupComposite) { this.groupComposite = groupComposite; group = groupComposite.getResourceGroup(); groupMemberType = group.getResourceType(); @@ -130,19 +135,45 @@ public class ResourceGroupContextMenu extends LocatableMenu { public void onTypesLoaded(ResourceType type) {
groupMemberType = type; - buildResourceGroupContextMenu(group, type); + buildResourceGroupContextMenu(tree, node, group, type); showContextMenu(); } }); }
- private void buildResourceGroupContextMenu(final ResourceGroup group, final ResourceType resourceType) { + private void buildResourceGroupContextMenu(final Tree tree, final TreeNode node, final ResourceGroup group, + final ResourceType resourceType) { // name setItems(new MenuItem(group.getName()));
// type name addItem(new MenuItem("Type: " + resourceType.getName()));
+ // Mixed group refresh is not needed as there is only a single top node. Compat group + // refresh makes sense after a group membership change but we already perform a CoreGUI refresh to + // reset the whole detail view after that user action. So, only suuport refresh for autogroup nodes + // in the resource tree. + if (node instanceof AutoGroupTreeNode) { + // separator + addItem(new MenuItemSeparator()); + + // refresh node + MenuItem refresh = new MenuItem(MSG.common_button_refresh()); + refresh.addClickHandler(new ClickHandler() { + + public void onClick(MenuItemClickEvent event) { + // autogroup nodes are in the resource tree and reloads are performed only on resource nodes. + // so find the actual resource parent node, traversing through subcategory nodes as needed. + TreeNode resourceNode = tree.getParent(node); + while (!(resourceNode instanceof ResourceTreeNode)) { + resourceNode = tree.getParent(resourceNode); + } + tree.reloadChildren(resourceNode); + } + }); + addItem(refresh); + } + // separator addItem(new MenuItemSeparator());
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java index 7ad3a74..7c8904d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeContextMenu.java @@ -23,6 +23,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.tree.Tree;
import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.resource.group.ClusterKey; @@ -33,6 +34,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupTreeView.ResourceGroupEnhancedTreeNode;
/** + * @author Jay Shaughnessy * @author Greg Hinkle */ public class ResourceGroupTreeContextMenu extends ResourceGroupContextMenu { @@ -41,7 +43,7 @@ public class ResourceGroupTreeContextMenu extends ResourceGroupContextMenu { super(locatorId); }
- public void showContextMenu(ResourceGroupEnhancedTreeNode node) { + public void showContextMenu(final Tree tree, final ResourceGroupEnhancedTreeNode node) {
if (node.isAutoClusterNode()) { final ClusterKey clusterKey = (ClusterKey) node.getAttributeAsObject("key"); @@ -55,7 +57,7 @@ public class ResourceGroupTreeContextMenu extends ResourceGroupContextMenu {
@Override public void onSuccess(ResourceGroup result) { - showContextMenu(result); + showContextMenu(tree, node, result); } });
@@ -72,7 +74,7 @@ public class ResourceGroupTreeContextMenu extends ResourceGroupContextMenu {
@Override public void onSuccess(PageList<ResourceGroup> result) { - showContextMenu(result.get(0)); + showContextMenu(tree, node, result.get(0)); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java index 0b2f45c..a26f382 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java @@ -190,7 +190,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka
// only show the context menu for cluster nodes and our top root node if (contextNode.isCompatibleGroupTopNode() || contextNode.isAutoClusterNode()) { - contextMenu.showContextMenu(contextNode); + contextMenu.showContextMenu(treeGrid.getTree(), contextNode); } } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceCompositeSearchView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceCompositeSearchView.java index de0dba6..15ab3dc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceCompositeSearchView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceCompositeSearchView.java @@ -48,6 +48,9 @@ import org.rhq.enterprise.gui.coregui.client.util.TableUtility; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
+/** + * @author Jay Shaughnessy + */ public class ResourceCompositeSearchView extends ResourceSearchView {
private final ResourceComposite parentResourceComposite; @@ -74,7 +77,6 @@ public class ResourceCompositeSearchView extends ResourceSearchView { return ResourceCompositeDataSource.getInstance(); }
- @SuppressWarnings("unchecked") @Override protected void configureTable() { addTableAction(extendLocatorId("Delete"), MSG.common_button_delete(), MSG @@ -115,7 +117,9 @@ public class ResourceCompositeSearchView extends ResourceSearchView { CoreGUI.getMessageCenter().notify( new Message(MSG.view_inventory_resources_deleteSuccessful(), Severity.Info));
- ResourceCompositeSearchView.this.refresh(); + // refresh the entire gui so it encompasses any relevant tree view. Don't call this.refresh() + // because CoreGUI.refresh is more comprehensive. + CoreGUI.refresh(); } }); } @@ -128,6 +132,7 @@ public class ResourceCompositeSearchView extends ResourceSearchView { super.configureTable(); }
+ @SuppressWarnings("unchecked") private void addImportButton() { ResourceType parentType = parentResourceComposite.getResource().getResourceType();
@@ -142,13 +147,13 @@ public class ResourceCompositeSearchView extends ResourceSearchView { } if (!importTypeValueMap.isEmpty()) { addTableAction(extendLocatorId("Import"), MSG.common_button_import(), null, importTypeValueMap, - new AbstractTableAction(TableActionEnablement.ALWAYS) { + new AbstractTableAction(TableActionEnablement.ALWAYS) {
- public void executeAction(ListGridRecord[] selection, Object actionValue) { - ResourceFactoryImportWizard.showImportWizard(parentResourceComposite.getResource(), - (ResourceType) actionValue); - } - }); + public void executeAction(ListGridRecord[] selection, Object actionValue) { + ResourceFactoryImportWizard.showImportWizard(parentResourceComposite.getResource(), + (ResourceType) actionValue); + } + }); }
// creatable child type menu @@ -161,17 +166,23 @@ public class ResourceCompositeSearchView extends ResourceSearchView { } } if (!createTypeValueMap.isEmpty()) { - addTableAction(extendLocatorId("CreateChild"), MSG.common_button_create_child(), null, - createTypeValueMap, new AbstractTableAction(TableActionEnablement.ALWAYS) { + addTableAction(extendLocatorId("CreateChild"), MSG.common_button_create_child(), null, createTypeValueMap, + new AbstractTableAction(TableActionEnablement.ALWAYS) {
public void executeAction(ListGridRecord[] selection, Object actionValue) { ResourceFactoryCreateWizard.showCreateWizard(parentResourceComposite.getResource(), - (ResourceType) actionValue); + (ResourceType) actionValue); } }); } }
+ protected void onUninventorySuccess() { + // refresh the entire gui so it encompasses any relevant tree view. Don't call this.refresh() + // because CoreGUI.refresh is more comprehensive. + CoreGUI.refresh(); + } + public ResourceComposite getParentResourceComposite() { return parentResourceComposite; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java index 025ee97..53d5b18 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java @@ -18,7 +18,19 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource;
-import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.*; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.AVAILABILITY; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CATEGORY; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.CTIME; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.DESCRIPTION; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.ITIME; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.KEY; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.LOCATION; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.MODIFIER; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.MTIME; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.NAME; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.PLUGIN; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.TYPE; +import static org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceDataSourceField.VERSION;
import java.util.ArrayList; import java.util.Collection; @@ -44,9 +56,9 @@ import org.rhq.core.domain.search.SearchSubsystem; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.components.table.EscapedHtmlCellFormatter; +import org.rhq.enterprise.gui.coregui.client.components.table.IconField; import org.rhq.enterprise.gui.coregui.client.components.table.RecordExtractor; import org.rhq.enterprise.gui.coregui.client.components.table.ResourceAuthorizedTableAction; -import org.rhq.enterprise.gui.coregui.client.components.table.IconField; import org.rhq.enterprise.gui.coregui.client.components.table.ResourceCategoryCellFormatter; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.components.table.TableActionEnablement; @@ -63,8 +75,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; /** * The list view for {@link Resource}s. * + * @author Jay Shaughnessy * @author Greg Hinkle */ +@SuppressWarnings("unchecked") public class ResourceSearchView extends Table {
private static final String DEFAULT_TITLE = MSG.view_inventory_resources_title(); @@ -103,7 +117,6 @@ public class ResourceSearchView extends Table { * * @param headerIcons 24x24 icon(s) to be displayed in the header */ - @SuppressWarnings("unchecked") public ResourceSearchView(String locatorId, Criteria criteria, String title, SortSpecifier[] sortSpecifier, String[] excludeFields, String... headerIcons) { super(locatorId, title, criteria, sortSpecifier, excludeFields); @@ -117,7 +130,6 @@ public class ResourceSearchView extends Table { }
// surpress unchecked warnings because the subclasses may have different generic types for the datasource - @SuppressWarnings("unchecked") protected RPCDataSource getDataSourceInstance() { return ResourceDatasource.getInstance(); } @@ -154,7 +166,7 @@ public class ResourceSearchView extends Table { CoreGUI.getMessageCenter().notify( new Message(MSG.view_inventory_resources_uninventorySuccessful(), Severity.Info));
- ResourceSearchView.this.refresh(); + onUninventorySuccess(); } }); } @@ -172,6 +184,10 @@ public class ResourceSearchView extends Table { }); }
+ protected void onUninventorySuccess() { + refresh(); + } + protected List<ListGridField> createFields() { List<ListGridField> fields = new ArrayList<ListGridField>();
@@ -181,12 +197,12 @@ public class ResourceSearchView extends Table { public String hoverHTML(Object value, ListGridRecord record, int rowNum, int colNum) { String resCat = record.getAttribute(CATEGORY.propertyName()); switch (ResourceCategory.valueOf(resCat)) { - case PLATFORM: - return MSG.common_title_platform(); - case SERVER: - return MSG.common_title_server(); - case SERVICE: - return MSG.common_title_service(); + case PLATFORM: + return MSG.common_title_platform(); + case SERVER: + return MSG.common_title_server(); + case SERVICE: + return MSG.common_title_service(); } return null; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java index 04c55c1..1044a5d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java @@ -27,6 +27,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGro import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** + * @author Jay Shaughnessy * @author Greg Hinkle */ public class ResourceTopView extends LocatableHLayout implements BookmarkableView { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java index 279ec46..501d9b2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java @@ -94,6 +94,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableMenu; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** + * @author Jay Shaughnessy * @author Greg Hinkle */ public class ResourceTreeView extends LocatableVLayout { @@ -310,6 +311,10 @@ public class ResourceTreeView extends LocatableVLayout { }
private void updateSelection() { + updateSelection(false); + } + + private void updateSelection(boolean isRefresh) {
TreeNode selectedNode;
@@ -325,11 +330,15 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.selectRecord(selectedNode); }
+ if (isRefresh) { + treeGrid.getTree().reloadChildren(selectedNode); + } + treeGrid.markForRedraw(); } }
- private void showContextMenu(AutoGroupTreeNode agNode) { + private void showContextMenu(final AutoGroupTreeNode agNode) { getAutoGroupBackingGroup(agNode, new AsyncCallback<ResourceGroup>() {
public void onFailure(Throwable caught) { @@ -337,7 +346,7 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(ResourceGroup result) { - autoGroupContextMenu.showContextMenu(result); + autoGroupContextMenu.showContextMenu(treeGrid.getTree(), agNode, result); } }); } @@ -380,7 +389,7 @@ public class ResourceTreeView extends LocatableVLayout { new ResourceTypeRepository.TypeLoadedCallback() {
public void onTypesLoaded(ResourceType type) { - buildResourceContextMenu(resourceComposite, type); + buildResourceContextMenu(node, resourceComposite, type); resourceContextMenu.showContextMenu(); } }); @@ -389,7 +398,8 @@ public class ResourceTreeView extends LocatableVLayout { }); }
- private void buildResourceContextMenu(final ResourceComposite resourceComposite, final ResourceType resourceType) { + private void buildResourceContextMenu(final ResourceTreeNode node, final ResourceComposite resourceComposite, + final ResourceType resourceType) { final Resource resource = resourceComposite.getResource(); final ResourcePermission resourcePermission = resourceComposite.getResourcePermission();
@@ -403,6 +413,19 @@ public class ResourceTreeView extends LocatableVLayout { // separator resourceContextMenu.addItem(new MenuItemSeparator());
+ // refresh node + MenuItem refresh = new MenuItem(MSG.common_button_refresh()); + refresh.addClickHandler(new ClickHandler() { + + public void onClick(MenuItemClickEvent event) { + treeGrid.getTree().reloadChildren(node); + } + }); + resourceContextMenu.addItem(refresh); + + // separator + resourceContextMenu.addItem(new MenuItemSeparator()); + // plugin config MenuItem pluginConfiguration = new MenuItem(MSG.view_tabs_common_connectionSettings()); boolean pluginConfigEnabled = resourceType.getPluginConfigurationDefinition() != null; @@ -701,14 +724,14 @@ public class ResourceTreeView extends LocatableVLayout { this.rootResource = rootResource; }
- public void setSelectedResource(final int selectedResourceId) { + public void setSelectedResource(final int selectedResourceId, boolean isRefresh) {
selectedNodeId = ResourceTreeNode.idOf(selectedResourceId);
if (treeGrid != null && treeGrid.getTree() != null && (treeGrid.getTree().findById(selectedNodeId)) != null) { // This is the case where the tree was previously loaded and we get fired to look at a different // node in the same tree and just have to switch the selection - updateSelection(); + updateSelection(isRefresh);
} else { // This is for cases where we have to load the tree fresh including down to the currently visible node @@ -900,6 +923,7 @@ public class ResourceTreeView extends LocatableVLayout { */
public void renderView(ViewPath viewPath) { + ViewId currentViewId = viewPath.getCurrent(); String currentViewIdPath = currentViewId.getPath(); if ("AutoGroup".equals(currentViewIdPath)) { @@ -911,8 +935,7 @@ public class ResourceTreeView extends LocatableVLayout { } else { String resourceIdString = currentViewId.getPath(); Integer resourceId = Integer.parseInt(resourceIdString); - setSelectedResource(resourceId); + setSelectedResource(resourceId, viewPath.isRefresh()); } } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java index 10fe75f..ee48168 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java @@ -141,6 +141,8 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_createSubmitType(getChildType().getName()), Message.Severity.Info)); getView().closeDialog(); + // try a refresh now but the resource may not get created fast enough to show up. + CoreGUI.refresh(); } });
@@ -163,6 +165,8 @@ public class ResourceFactoryCreateWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_createSubmit(newResourceName), Message.Severity.Info)); getView().closeDialog(); + // try a refresh now but the resource may not get created fast enough to show up. + CoreGUI.refresh(); } });
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java index 225a933..365c07c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryImportWizard.java @@ -97,6 +97,8 @@ public class ResourceFactoryImportWizard extends AbstractResourceFactoryWizard { new Message(MSG.widget_resourceFactoryWizard_importSubmitted(getChildType().getName()), Message.Severity.Info)); getView().closeDialog(); + // try a refresh now but the resource may not get added fast enough to show up. + CoreGUI.refresh(); } }); }
commit 2b9ad457efe41706015630ad5d526311ee1b9376 Author: John Sanda jsanda@redhat.com Date: Mon Aug 22 14:49:03 2011 -0400
DriftManagerBean needs to implement DriftManagerRemote
Also adding some more logging in DriftDetector.
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 ecf3821..f10ca40 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 @@ -71,15 +71,22 @@ public class DriftDetector implements Runnable { public void run() { DriftDetectionSchedule schedule = scheduleQueue.getNextSchedule(); if (schedule == null) { + log.debug("No schedules are in the queue."); return; }
+ if (log.isDebugEnabled()) { + log.debug("Processing " + schedule); + } + try { if (schedule.getNextScan() > (System.currentTimeMillis() + 100L)) { + log.debug("Skipping " + schedule + " because it is too early to do the next detection."); return; }
if (!schedule.getDriftConfiguration().isEnabled()) { + log.debug("Skipping " + schedule + " because the drift configuration is disabled."); return; }
@@ -111,6 +118,7 @@ public class DriftDetector implements Runnable { }
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()));
final ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), @@ -128,6 +136,9 @@ 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()); + } driftWriter.write(removedFileEntry(entry.getFile(), entry.getNewSHA())); changes.incrementAndGet(); } else { @@ -135,6 +146,9 @@ public class DriftDetector implements Runnable { String currentSHA = sha256(file); if (!currentSHA.equals(entry.getNewSHA())) { // The file has been updated + if (log.isInfoEnabled()) { + log.info("Detected modified file for " + schedule + " --> " + file.getAbsolutePath()); + } FileEntry modifiedEntry = changedFileEntry(entry.getFile(), entry.getNewSHA(), currentSHA); driftWriter.write(modifiedEntry); coverageWriter.write(modifiedEntry); @@ -155,6 +169,11 @@ public class DriftDetector implements Runnable { if (processedFiles.contains(file)) { return; } + + if (log.isInfoEnabled()) { + log.info("Detected added file for " + schedule + " --> " + file.getAbsolutePath()); + } + FileEntry newEntry = addedFileEntry(relativePath(basedir, file), sha256(file)); driftWriter.write(newEntry); coverageWriter.write(newEntry); @@ -175,6 +194,8 @@ public class DriftDetector implements Runnable { }
private void generateCoverageChangeSet(final DriftDetectionSchedule schedule) throws IOException { + log.debug("Generating coverage change set for " + schedule); + final ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, COVERAGE)); final DriftConfiguration config = schedule.getDriftConfiguration(); @@ -185,6 +206,9 @@ 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); + } writer.write(addedFileEntry(relativePath(basedir, file), sha256(file))); } catch (IOException e) { log.error("An error occurred while generating a coverage change set for " + schedule + ": " + 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 60c2547..3497520 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 @@ -90,7 +90,7 @@ import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; * @author Jay Shaughnessy */ @Stateless -public class DriftManagerBean implements DriftManagerLocal { +public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
// TODO Should security checks be handled here instead of delegating to the drift plugin? // Currently any security checks that need to be performed are delegated to the plugin.
commit 018fd0346961c6527e7f07b71e12f3f793e46546 Author: John Sanda jsanda@redhat.com Date: Mon Aug 22 13:37:19 2011 -0400
Fixing plugin property name in drift template
The plugin property name for the 'Core Files' template was set to jbossHomeDir but the correct property name is homeDir.
Also updating DriftDetector to catch any Throwable so that the thread continues execution even in the event of an unexpected error.
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 5ae6447..ecf3821 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 @@ -103,6 +103,8 @@ public class DriftDetector implements Runnable { if (changeSetType == COVERAGE || changes > 0) { driftClient.sendChangeSetToServer(schedule.getResourceId(), driftConfig, changeSetType); } + } catch (Throwable t) { + log.error("An unexpected error occurred during drift detection: " + t.getCause().getMessage(), t); } finally { scheduleQueue.deactivateSchedule(); } diff --git a/modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml index 1f6bc7c..5dc6600 100644 --- a/modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml @@ -1194,7 +1194,7 @@ <drift-configuration name="Core Files"> <basedir> <value-context>pluginConfiguration</value-context> - <value-name>jbossHomeDir</value-name> + <value-name>homeDir</value-name> </basedir> <includes> <include path="bin" />
commit 90f0867435ee2b426a2cd7eb67fa5d36a5293356 Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 22 12:38:37 2011 -0400
[BZ 732089] a new unit test to make sure the fix works.
diff --git a/.classpath b/.classpath index 52f9dab..cb9d57f 100644 --- a/.classpath +++ b/.classpath @@ -177,6 +177,7 @@ <classpathentry kind="src" path="modules/enterprise/remoting/cli/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/sars/agent-sar/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/safe-invoker/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/server/safe-invoker/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/container-lib/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/ant-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/filetemplate-bundle/src/main/java"/> diff --git a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java index a978a85..51b78ee 100644 --- a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java +++ b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java @@ -64,18 +64,49 @@ public class HibernateDetachUtility { SERIALIZATION, JAXB }
+ /* + * This is the type of object that will be used to generate identity + * hashcodes for objects that are being scanned during the detach. + * During production runtime, the hashCodeGenerator will use the + * java.lang.System mechanism, but since this is package scoped, + * tests can override this since. (See BZ 732089). + */ + static interface HashCodeGenerator { + Integer getHashCode(Object value); + } + + static class SystemHashCodeGenerator implements HashCodeGenerator { + @Override + public Integer getHashCode(Object value) { + return System.identityHashCode(value); + } + } + + static HashCodeGenerator hashCodeGenerator = new SystemHashCodeGenerator(); + // be able to configure the deepest recursion this utility will be allowed to go (see BZ 702109 that precipitated this need) private static final String DEPTH_ALLOWED_SYSPROP = "rhq.server.hibernate-detach-utility.depth-allowed"; + private static final String THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP = "rhq.server.hibernate-detach-utility.throw-exception-on-depth-limit"; private static final int depthAllowed; + private static final boolean throwExceptionOnDepthLimit; static { int value; try { - String str = System.getProperty(DEPTH_ALLOWED_SYSPROP, "50"); + String str = System.getProperty(DEPTH_ALLOWED_SYSPROP, "100"); value = Integer.parseInt(str); } catch (Throwable t) { - value = 50; + value = 100; } depthAllowed = value; + + boolean booleanValue; + try { + String str = System.getProperty(THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP, "true"); + booleanValue = Boolean.parseBoolean(str); + } catch (Throwable t) { + booleanValue = true; + } + throwExceptionOnDepthLimit = booleanValue; }
public static void nullOutUninitializedFields(Object value, SerializationType serializationType) throws Exception { @@ -107,18 +138,24 @@ public class HibernateDetachUtility { * for a single hash and is used to ensure we never try to detach an object already processed. * @param depth used to stop infinite recursion, defaults to a depth we don't expectto see, but it is configurable. * @param serializationType - * @throws Exception + * @throws Exception if a problem occurs + * @throws IllegalStateException if the recursion depth limit is reached */ private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjectMap, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) throws Exception { if (depth > depthAllowed) { - LOG.warn("Recursed too deep [" + depth + " > " + depthAllowed + String warningMessage = "Recursed too deep [" + depth + " > " + depthAllowed + "], will not attempt to detach object of type [" + ((value != null) ? value.getClass().getName() : "N/A") - + "]. This may cause serialization errors later. If so, " - + "you can try to work around this by setting the system property [" + DEPTH_ALLOWED_SYSPROP - + "] to a value higher than [" + depth + "]."); + + "]. This may cause serialization errors later. " + + "You can try to work around this by setting the system property [" + DEPTH_ALLOWED_SYSPROP + + "] to a value higher than [" + depth + "] or you can set the system property [" + + THROW_EXCEPTION_ON_DEPTH_LIMIT_SYSPROP + "] to 'false'"; + LOG.warn(warningMessage); + if (throwExceptionOnDepthLimit) { + throw new IllegalStateException(warningMessage); + } return; }
@@ -129,7 +166,7 @@ public class HibernateDetachUtility { // System.identityHashCode is a hash code, and therefore not guaranteed to be unique. And we've seen this // be the case. So, we use it to try and avoid duplicating work, but handle the case when two objects may // have an identity crisis. - Integer valueIdentity = System.identityHashCode(value); + Integer valueIdentity = hashCodeGenerator.getHashCode(value); Object checkedObject = checkedObjectMap.get(valueIdentity);
if (null == checkedObject) { diff --git a/modules/enterprise/server/safe-invoker/src/test/java/org/rhq/enterprise/server/util/HibernateDetachUtilityTest.java b/modules/enterprise/server/safe-invoker/src/test/java/org/rhq/enterprise/server/util/HibernateDetachUtilityTest.java new file mode 100644 index 0000000..3df5403 --- /dev/null +++ b/modules/enterprise/server/safe-invoker/src/test/java/org/rhq/enterprise/server/util/HibernateDetachUtilityTest.java @@ -0,0 +1,141 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.rhq.enterprise.server.util; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; + +import org.testng.annotations.Test; + +import org.rhq.enterprise.server.util.HibernateDetachUtility.SerializationType; + +@Test +public class HibernateDetachUtilityTest { + /** + * This tests the rare, but very possible, condition where two objects + * have the same identity hashcode (System.identityHashCode(A) == System.identityHashCode(B)) + * but are not identical objects (A != B). We have seen this as a valid condition + * on both SUN and IBM JRE implementations. + */ + public void testIdenticalHashCodesNonIdenticalObjects() throws Exception { + class ArrayObject implements Serializable { + private static final long serialVersionUID = 1L; + long id; + Integer[] array; + ArrayObject object; // needed for self-referencing + + ArrayObject(long key, ArrayObject obj, Integer... members) { + id = key; + object = obj; + array = members; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ArrayObject [id=").append(id).append(", object=").append( + (object == null) ? "null" : object.id).append(", array=").append(Arrays.toString(array)) + .append("]"); + return builder.toString(); + } + + } + + class DuplicateHashCodeGenerator implements HibernateDetachUtility.HashCodeGenerator { + public Integer getHashCode(Object value) { + if (value instanceof Integer && ((Integer) value).intValue() >= 2) { + return 11111; + } else if (value instanceof ArrayObject) { + return 22222; + } else { + return System.identityHashCode(value); + } + } + } + + ArrayObject array1 = new ArrayObject(1, null, 1, 2, 3); + ArrayObject array2 = new ArrayObject(2, array1, 2, 3); + array1.object = array2; // now 1 references 2 and 2 reference 1, circular dependency + ArrayObject array3 = new ArrayObject(3, array2, 3); + array3.object = array3; + ArrayList<ArrayObject> array = new ArrayList<ArrayObject>(3); + array.add(array1); + array.add(array2); + array.add(array3); + + // SANITY CHECK - make sure our setup is as we expect it to be + assert array.get(0).array[0] == Integer.valueOf(1); + assert array.get(0).array[1] == Integer.valueOf(2); + assert array.get(0).array[2] == Integer.valueOf(3); + assert array.get(1).array[0] == Integer.valueOf(2); + assert array.get(1).array[1] == Integer.valueOf(3); + assert array.get(2).array[0] == Integer.valueOf(3); + + // make sure array1 still references array2 and vice versa + assertObjectEquals(array.get(0).object, array.get(1)); + assertObjectEquals(array.get(1).object, array.get(0)); + + // make sure array3 still self-references + assertObjectEquals(array.get(2).object, array.get(2)); + + // simulate rare condition + HibernateDetachUtility.hashCodeGenerator = new DuplicateHashCodeGenerator(); + HibernateDetachUtility.nullOutUninitializedFields(array, SerializationType.SERIALIZATION); + assert array.get(0).array[0] == Integer.valueOf(1); + assert array.get(0).array[1] == Integer.valueOf(2); + assert array.get(0).array[2] == Integer.valueOf(3); + assert array.get(1).array[0] == Integer.valueOf(2); + assert array.get(1).array[1] == Integer.valueOf(3); + assert array.get(2).array[0] == Integer.valueOf(3); + + // make sure array1 still references array2 and vice versa + assertObjectEquals(array.get(0).object, array.get(1)); + assertObjectEquals(array.get(1).object, array.get(0)); + + // make sure array3 still self-references + assertObjectEquals(array.get(2).object, array.get(2)); + + // put it back the way it was + HibernateDetachUtility.hashCodeGenerator = new HibernateDetachUtility.SystemHashCodeGenerator(); + HibernateDetachUtility.nullOutUninitializedFields(array, SerializationType.SERIALIZATION); + assert array.get(0).array[0] == Integer.valueOf(1); + assert array.get(0).array[1] == Integer.valueOf(2); + assert array.get(0).array[2] == Integer.valueOf(3); + assert array.get(1).array[0] == Integer.valueOf(2); + assert array.get(1).array[1] == Integer.valueOf(3); + assert array.get(2).array[0] == Integer.valueOf(3); + + // make sure array1 still references array2 and vice versa + assertObjectEquals(array.get(0).object, array.get(1)); + assertObjectEquals(array.get(1).object, array.get(0)); + + // make sure array3 still self-references + assertObjectEquals(array.get(2).object, array.get(2)); + } + + private void assertObjectEquals(Object o1, Object o2) { + assert o1 == o2 : "Object [" + o1 + "] does not equal object [" + o2 + "]"; + } +} \ No newline at end of file
commit 727a1443bb20098900a08fa739e732f78581d0b9 Author: Jay Shaughnessy jshaughn@redhat.com Date: Sun Aug 21 12:42:38 2011 -0400
[BZ 729994 - Create/Import wizard does not allow reselection of template] Now, in the resource factory wizard (import, create child), a user can back up via the previous button, re-select the template, and the new selection will be honored when the config editor is next displayed.
(related to BZ 705713 - Templates not honored for resource-config when creating a new resource)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java index 5274e40..a05974a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryConfigurationStep.java @@ -45,6 +45,7 @@ public class ResourceFactoryConfigurationStep extends AbstractWizardStep { private boolean noConfigurationNeeded = false; // if true, it has been determined the user doesn't have to set any config private LocatableVLayout vLayout; private ConfigurationEditor editor; + private Configuration startingConfig; private DurationItem timeoutItem; AbstractResourceFactoryWizard wizard;
@@ -53,49 +54,14 @@ public class ResourceFactoryConfigurationStep extends AbstractWizardStep { }
public Canvas getCanvas(Locatable parent) { - if (vLayout == null) { + boolean newCanvas = this.vLayout == null; + + if (newCanvas) { String locatorId = (null == parent) ? "ResourceFactoryConfig" : parent .extendLocatorId("ResourceFactoryConfig"); - vLayout = new LocatableVLayout(locatorId); - - final ConfigurationDefinition def = wizard.getNewResourceConfigurationDefinition(); - if (def != null) { - - final Configuration startingConfig = wizard.getNewResourceStartingConfiguration(); - - ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService(); - configurationService.getOptionValuesForConfigDefinition(def,new AsyncCallback<ConfigurationDefinition>() { - - - @Override - public void onFailure(Throwable throwable) { - editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), - def, startingConfig); -// configurationEditor.setReadOnly(isReadOnly()); -// operationParametersConfigurationHolder.addMember(configurationEditor); -// operationParametersConfigurationHolder.show(); - vLayout.addMember(editor); - - } - - @Override - public void onSuccess(ConfigurationDefinition result) { - editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), - result, startingConfig); -// configurationEditor.setReadOnly(isReadOnly()); -// operationParametersConfigurationHolder.addMember(configurationEditor); -// operationParametersConfigurationHolder.show(); - vLayout.addMember(editor); - } - }); - - - -// Configuration startingConfig = wizard.getNewResourceStartingConfiguration(); -// editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), def, startingConfig); -// vLayout.addMember(editor); - } + this.vLayout = new LocatableVLayout(locatorId);
+ // only create the timeout member 1 time, even if we end up recreating the config editor TreeSet<TimeUnit> supportedUnits = new TreeSet<TimeUnit>(); supportedUnits.add(TimeUnit.SECONDS); supportedUnits.add(TimeUnit.MINUTES); @@ -109,6 +75,43 @@ public class ResourceFactoryConfigurationStep extends AbstractWizardStep { timeoutForm.setMargin(10); vLayout.addMember(timeoutForm); } + + // if this is a newCanvas, or if the starting config has changed, create a new config editor. The starting + // config (i.e. template) may have changed if the user, via the previous button, backed up and changed the + // selected template. + if (newCanvas || this.startingConfig != wizard.getNewResourceStartingConfiguration()) { + + final ConfigurationDefinition def = wizard.getNewResourceConfigurationDefinition(); + if (def != null) { + + this.startingConfig = wizard.getNewResourceStartingConfiguration(); + + if (!newCanvas) { + Canvas doomedConfigEditor = this.vLayout.getMember(0); + this.vLayout.removeMember(doomedConfigEditor); + doomedConfigEditor.destroy(); + } + + this.startingConfig = wizard.getNewResourceStartingConfiguration(); + + ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService(); + configurationService.getOptionValuesForConfigDefinition(def, + new AsyncCallback<ConfigurationDefinition>() { + + public void onFailure(Throwable throwable) { + editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), def, startingConfig); + vLayout.addMember(editor, 0); + + } + + public void onSuccess(ConfigurationDefinition result) { + editor = new ConfigurationEditor(vLayout.extendLocatorId("Editor"), result, startingConfig); + vLayout.addMember(editor, 0); + } + }); + } + } + return vLayout; }
commit 29b542700591bb3b481479671341c70447d53874 Author: Jay Shaughnessy jshaughn@redhat.com Date: Sun Aug 21 11:23:16 2011 -0400
[BZ 717788 - NPE on Inventory>Agent subtab for a platform that has UNKNOWN avail and has never been UP] Handle situation when no avail report has yet ben sent.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceAgentView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceAgentView.java index ddab284..ff1addc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceAgentView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/ResourceResourceAgentView.java @@ -174,7 +174,8 @@ public class ResourceResourceAgentView extends LocatableVLayout implements Refre nameValue.setValue(agent.getName()); addressValue.setValue(agent.getAddress()); portValue.setValue(agent.getPort()); - lastAvailReportValue.setValue(new Date(agent.getLastAvailabilityReport())); + Long lastAvail = agent.getLastAvailabilityReport(); + lastAvailReportValue.setValue((null != lastAvail) ? new Date(lastAvail) : MSG.common_val_none()); String remoteEndpoint = agent.getRemoteEndpoint(); if (remoteEndpoint != null) { // some browsers (firefox in particular) won't wrap unless you put breaks in the string
commit acc1feadf27a2235d5a070d3cd59b56515a62d74 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 19 17:35:49 2011 -0400
show different folder icon for categories
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java index 76ac9f1..92b7d9e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/CustomResourceTreeGrid.java @@ -25,6 +25,7 @@ import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Resource; import org.rhq.enterprise.gui.coregui.client.ImageManager; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.ResourceTreeNode; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.SubCategoryTreeNode; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid;
/** @@ -52,6 +53,8 @@ public class CustomResourceTreeGrid extends LocatableTreeGrid { boolean up = resource.getCurrentAvailability().getAvailabilityType() == AvailabilityType.UP; return ImageManager.getResourceIcon(resource.getResourceType().getCategory(), up); } + } else if (record instanceof SubCategoryTreeNode) { + return "resources/folder_mixed_" + (open ? "opened" : "closed") + ".png"; } else { return "resources/folder_group_" + (open ? "opened" : "closed") + ".png"; } diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_closed.png b/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_closed.png new file mode 100644 index 0000000..0f3ce88 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_closed.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_opened.png b/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_opened.png new file mode 100644 index 0000000..6352365 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/resources/folder_mixed_opened.png differ
commit 8c77babdf5f14c6a4161833c06ca6cf944d630a8 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Aug 19 16:45:29 2011 -0400
A fix to the identity collision logic, preventing falling through to the scrubbing if we've already done it (thanks, Ian!)
diff --git a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java index fd92da6..a978a85 100644 --- a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java +++ b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java @@ -189,10 +189,13 @@ public class HibernateDetachUtility { LOG.debug(message); }
- // if not already detached then add to the list of collision objects for this hash, and start scrubbing - if (!alreadyDetached) { - collisionObjects.add(value); + // now that we've done our logging, if already detached we're done. Otherwise add to the list of collision + // objects for this hash, and start scrubbing + if (alreadyDetached) { + return; } + + collisionObjects.add(value); }
// Perform the detaching
commit 0f1e427b130240ea6189c183cd6829e3400970f7 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Aug 19 15:53:01 2011 -0400
New and Improved HibernateDetachUtility, now with enhanced collision handling and lemony fresh scent!
[BZ-732089 - Hibernate Detach Utility Identity Conflicts]
diff --git a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java index a496efe..fd92da6 100644 --- a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java +++ b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java @@ -80,20 +80,38 @@ public class HibernateDetachUtility {
public static void nullOutUninitializedFields(Object value, SerializationType serializationType) throws Exception { long start = System.currentTimeMillis(); - Map<Integer, Object> checkedObjects = new HashMap<Integer, Object>(); - nullOutUninitializedFields(value, checkedObjects, 0, serializationType); + Map<Integer, Object> checkedObjectMap = new HashMap<Integer, Object>(); + Map<Integer, List<Object>> checkedObjectCollisionMap = new HashMap<Integer, List<Object>>(); + nullOutUninitializedFields(value, checkedObjectMap, checkedObjectCollisionMap, 0, serializationType); long duration = System.currentTimeMillis() - start; if (duration > 1000) { - LOG.info("Detached [" + checkedObjects.size() + "] objects in [" + duration + "]ms"); + LOG.info("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms"); } else { - LOG.debug("Detached [" + checkedObjects.size() + "] objects in [" + duration + "]ms"); + LOG.debug("Detached [" + checkedObjectMap.size() + "] objects in [" + duration + "]ms"); } // help the garbage collector be clearing these before we leave - checkedObjects.clear(); + checkedObjectMap.clear(); + checkedObjectCollisionMap.clear(); }
- private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjects, int depth, - SerializationType serializationType) throws Exception { + /** + * @param value the object needing to be detached/scrubbed. + * @param checkedObjectMap This maps identityHashCodes to Objects we've already detached. In that way we can + * quickly determine if we've already done the work for the incoming value and avoid taversing it again. This + * works well almost all of the time, but it is possible that two different objects can have the same identity hash + * (conflicts are always possible with a hash). In that case we utilize the checkedObjectCollisionMap (see below). + * @param checkedObjectCollisionMap checkedObjectMap maps the identityhash to the *first* object with that hash. In + * most cases there will only be mapping for one hash, but it is possible to encounter the same hash for multiple + * objects, especially on 32bit or IBM JVMs. It is important to know if an object has already been detached + * because if it is somehow self-referencing, we have to stop the recursion. This map holds the 2nd..Nth mapping + * for a single hash and is used to ensure we never try to detach an object already processed. + * @param depth used to stop infinite recursion, defaults to a depth we don't expectto see, but it is configurable. + * @param serializationType + * @throws Exception + */ + private static void nullOutUninitializedFields(Object value, Map<Integer, Object> checkedObjectMap, + Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) + throws Exception { if (depth > depthAllowed) { LOG.warn("Recursed too deep [" + depth + " > " + depthAllowed + "], will not attempt to detach object of type [" @@ -112,22 +130,72 @@ public class HibernateDetachUtility { // be the case. So, we use it to try and avoid duplicating work, but handle the case when two objects may // have an identity crisis. Integer valueIdentity = System.identityHashCode(value); - Object checkedObject = checkedObjects.get(valueIdentity); + Object checkedObject = checkedObjectMap.get(valueIdentity);
if (null == checkedObject) { - checkedObjects.put(valueIdentity, value); + // if we have not yet encountered an object with this hash, store it in our map and start scrubbing + checkedObjectMap.put(valueIdentity, value);
} else if (value == checkedObject) { + // if we have scrubbed this already, no more work to be done return;
} else { + // we have a situation where multiple objects have the same identity hashcode, work with our + // collision map to decide whether it needs to be scrubbed and add if necessary. + // Note that this code block is infrequently hit, it is by design that we've pushed the extra + // work, map, etc, involved for this infrequent case into its own block. The standard cases must + // be as fast and lean as possible. + + boolean alreadyDetached = false; + List<Object> collisionObjects = checkedObjectCollisionMap.get(valueIdentity); + + if (null == collisionObjects) { + // if this is the 2nd occurrence for this hash, create a new map entry + collisionObjects = new ArrayList<Object>(1); + checkedObjectCollisionMap.put(valueIdentity, collisionObjects); + + } else { + // if we have scrubbed this already, no more work to be done + for (Object collisionObject : collisionObjects) { + if (value == collisionObject) { + alreadyDetached = true; + break; + } + } + } + if (LOG.isDebugEnabled()) { - LOG.debug("UNEQUAL IDENTITY HASHCODE [" + valueIdentity + "]\n\tCurrent : " - + value.getClass().getName() + "\n\t" + value + "\n\tPrevious: " - + checkedObject.getClass().getName() + "\n\t" + checkedObject); + StringBuilder message = new StringBuilder("\n\tIDENTITY HASHCODE COLLISION [hash="); + message.append(valueIdentity); + message.append(", alreadyDetached="); + message.append(alreadyDetached); + message.append("]"); + message.append("\n\tCurrent : "); + message.append(value.getClass().getName()); + message.append("\n\t "); + message.append(value); + message.append("\n\tPrevious : "); + message.append(checkedObject.getClass().getName()); + message.append("\n\t "); + message.append(checkedObject); + for (Object collisionObject : collisionObjects) { + message.append("\n\tPrevious : "); + message.append(collisionObject.getClass().getName()); + message.append("\n\t "); + message.append(collisionObject); + } + + LOG.debug(message); + } + + // if not already detached then add to the list of collision objects for this hash, and start scrubbing + if (!alreadyDetached) { + collisionObjects.add(value); } }
+ // Perform the detaching if (value instanceof Object[]) { Object[] objArray = (Object[]) value; for (int i = 0; i < objArray.length; i++) { @@ -136,7 +204,8 @@ public class HibernateDetachUtility { if (replaceEntry != null) { objArray[i] = replaceEntry; } - nullOutUninitializedFields(objArray[i], checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(objArray[i], checkedObjectMap, checkedObjectCollisionMap, depth + 1, + serializationType); } } else if (value instanceof List) { // Null out any entries in initialized collections @@ -148,7 +217,8 @@ public class HibernateDetachUtility { val = replace; i.set(replace); } - nullOutUninitializedFields(val, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(val, checkedObjectMap, checkedObjectCollisionMap, depth + 1, + serializationType); }
} else if (value instanceof Collection) { @@ -162,7 +232,8 @@ public class HibernateDetachUtility { replacementItems.add(replacementItem); item = replacementItem; } - nullOutUninitializedFields(item, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(item, checkedObjectMap, checkedObjectCollisionMap, depth + 1, + serializationType); } collection.removeAll(itemsToBeReplaced); collection.addAll(replacementItems); // watch out! if this collection is a Set, HashMap$MapSet doesn't support addAll. See BZ 688000 @@ -194,8 +265,10 @@ public class HibernateDetachUtility {
// now go through each item in the map and null out their internal fields for (Object key : originalMap.keySet()) { - nullOutUninitializedFields(originalMap.get(key), checkedObjects, depth + 1, serializationType); - nullOutUninitializedFields(key, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(originalMap.get(key), checkedObjectMap, checkedObjectCollisionMap, + depth + 1, serializationType); + nullOutUninitializedFields(key, checkedObjectMap, checkedObjectCollisionMap, depth + 1, + serializationType); } } else if (value instanceof Enum) { // don't need to detach enums, treat them as special objects @@ -205,18 +278,19 @@ public class HibernateDetachUtility { if (serializationType == SerializationType.JAXB) { XmlAccessorType at = value.getClass().getAnnotation(XmlAccessorType.class); if (at != null && at.value() == XmlAccessType.FIELD) { - nullOutFieldsByFieldAccess(value, checkedObjects, depth, serializationType); + nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth, serializationType); } else { - nullOutFieldsByAccessors(value, checkedObjects, depth, serializationType); + nullOutFieldsByAccessors(value, checkedObjectMap, checkedObjectCollisionMap, depth, serializationType); } } else if (serializationType == SerializationType.SERIALIZATION) { - nullOutFieldsByFieldAccess(value, checkedObjects, depth, serializationType); + nullOutFieldsByFieldAccess(value, checkedObjectMap, checkedObjectCollisionMap, depth, serializationType); }
}
- private static void nullOutFieldsByFieldAccess(Object object, Map<Integer, Object> checkedObjects, int depth, - SerializationType serializationType) throws Exception { + private static void nullOutFieldsByFieldAccess(Object object, Map<Integer, Object> checkedObjects, + Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) + throws Exception {
Class tmpClass = object.getClass(); List<Field> fieldsToClean = new ArrayList<Field>(); @@ -232,11 +306,13 @@ public class HibernateDetachUtility { tmpClass = tmpClass.getSuperclass(); }
- nullOutFieldsByFieldAccess(object, fieldsToClean, checkedObjects, depth, serializationType); + nullOutFieldsByFieldAccess(object, fieldsToClean, checkedObjects, checkedObjectCollisionMap, depth, + serializationType); }
private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields, - Map<Integer, Object> checkedObjects, int depth, SerializationType serializationType) throws Exception { + Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, + SerializationType serializationType) throws Exception {
boolean accessModifierFlag = false; for (Field field : classFields) { @@ -260,10 +336,11 @@ public class HibernateDetachUtility { replacement = m.invoke(fieldValue);
String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$"; - + assistClassName = assistClassName.substring(0, assistClassName.indexOf(assistNameDelimiter)); if (!replacement.getClass().getName().contains("hibernate")) { - nullOutUninitializedFields(replacement, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, + depth + 1, serializationType);
field.set(object, replacement); } else { @@ -277,11 +354,12 @@ public class HibernateDetachUtility { if (replacement == null) {
String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName(); - + //see if there is a context classloader we should use instead of the current one. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - - Class clazz = contextClassLoader == null ? Class.forName(className) : Class.forName(className, true, contextClassLoader); + + Class clazz = contextClassLoader == null ? Class.forName(className) : Class.forName(className, + true, contextClassLoader); Class[] constArgs = { Integer.class }; Constructor construct = null;
@@ -327,7 +405,8 @@ public class HibernateDetachUtility { replacement = new ArrayList((List) fieldValue); } else if (fieldValue instanceof Set) { ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000 - nullOutUninitializedFields(l, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1, + serializationType); replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000 needToNullOutFields = false; } else if (fieldValue instanceof Collection) { @@ -336,7 +415,8 @@ public class HibernateDetachUtility { setField(object, field.getName(), replacement);
if (needToNullOutFields) { - nullOutUninitializedFields(replacement, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, + depth + 1, serializationType); } }
@@ -344,7 +424,8 @@ public class HibernateDetachUtility { if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq") || fieldValue instanceof Collection || fieldValue instanceof Object[] || fieldValue instanceof Map)) - nullOutUninitializedFields((fieldValue), checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap, depth + 1, + serializationType); } } if (accessModifierFlag) { @@ -364,7 +445,6 @@ public class HibernateDetachUtility { Method m = assistClass.getMethod("writeReplace"); replacement = m.invoke(object);
- String className = object.getClass().getName(); } catch (Exception e) { LOG.error("Unable to write replace object " + object.getClass(), e); } @@ -373,8 +453,9 @@ public class HibernateDetachUtility { return replacement; }
- private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects, int depth, - SerializationType serializationType) throws Exception { + private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects, + Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) + throws Exception { // Null out any collections that aren't loaded BeanInfo bi = Introspector.getBeanInfo(value.getClass(), Object.class);
@@ -409,7 +490,8 @@ public class HibernateDetachUtility { } else { if ((propertyValue instanceof Collection) || ((propertyValue != null) && propertyValue.getClass().getName().startsWith("org.rhq.core.domain"))) { - nullOutUninitializedFields(propertyValue, checkedObjects, depth + 1, serializationType); + nullOutUninitializedFields(propertyValue, checkedObjects, checkedObjectCollisionMap, depth + 1, + serializationType); } } }
commit aceb9d010cb9a910d998463a01857f47d25a5445 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 19 16:10:54 2011 -0400
[BZ 696224] support direct nav to traits details
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java index a4911f8..27a766c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java @@ -57,16 +57,22 @@ public abstract class AbstractMeasurementDataTraitListView extends TableSection
@Override protected void configureTable() { + super.configureTable(); + ListGrid listGrid = getListGrid(); listGrid.setSelectionType(SelectionStyle.SINGLE);
// Set widths and cell formatters on the fields. - listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_DISPLAY_NAME).setWidth("20%"); - ListGridField timestampField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP); - timestampField.setWidth("20%"); - timestampField.setCellFormatter(new TimestampCellFormatter()); + ListGridField displayNameField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_DISPLAY_NAME); + if (displayNameField != null) { + displayNameField.setWidth("20%"); + }
- super.configureTable(); + ListGridField timestampField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP); + if (timestampField != null) { + timestampField.setWidth("20%"); + timestampField.setCellFormatter(new TimestampCellFormatter()); + } }
@Override
commit 97c70790efd90a237830ebff95b2cc165975cf53 Author: Ian Springer ian.springer@redhat.com Date: Fri Aug 19 15:06:00 2011 -0400
[BZ 696276] fix exception that occurred when a non-admin user user clicked on a metric detailed chart link in one of the recent metrics portlets (https://bugzilla.redhat.com/show_bug.cgi?id=696276)
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GlobalActivationContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GlobalActivationContext.java index ea1e067..bc1937f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GlobalActivationContext.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GlobalActivationContext.java @@ -79,7 +79,8 @@ public class GlobalActivationContext implements ActivationContext { if (this.globalPermissions == null) { AuthorizationManagerLocal authorizationManager = LookupUtil.getAuthorizationManager(); Set<Permission> perms = authorizationManager.getExplicitGlobalPermissions(this.subject); - this.globalPermissions = EnumSet.copyOf(perms); + this.globalPermissions = EnumSet.noneOf(Permission.class); + this.globalPermissions.addAll(perms); } return this.globalPermissions; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GroupActivationContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GroupActivationContext.java index 2c572fb..7b1fe4c 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GroupActivationContext.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/GroupActivationContext.java @@ -70,14 +70,15 @@ public class GroupActivationContext extends AbstractResourceOrGroupActivationCon if (this.resourcePermissions == null) { Set<Permission> perms = this.authorizationManager.getImplicitGroupPermissions(getSubject(), this.group .getId()); - this.resourcePermissions = EnumSet.copyOf(perms); + this.resourcePermissions = EnumSet.noneOf(Permission.class); + this.resourcePermissions.addAll(perms); } return this.resourcePermissions; }
public Set<Resource> getResources() { // lazy load - if (null == this.group.getExplicitResources()) { + if (this.group.getExplicitResources() == null) { ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(this.group.getId()); criteria.fetchExplicitResources(true); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/ResourceActivationContext.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/ResourceActivationContext.java index 7f13169..b636eff 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/ResourceActivationContext.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/perspective/activator/context/ResourceActivationContext.java @@ -82,7 +82,8 @@ public class ResourceActivationContext extends AbstractResourceOrGroupActivation if (this.resourcePermissions == null) { Set<Permission> perms = this.authorizationManager.getImplicitResourcePermissions(getSubject(), this.resource.getId()); - this.resourcePermissions = EnumSet.copyOf(perms); + this.resourcePermissions = EnumSet.noneOf(Permission.class); + this.resourcePermissions.addAll(perms); } return this.resourcePermissions; }
commit 7f158ef2a64380659beb5a0ed80ed848756fb858 Author: Ian Springer ian.springer@redhat.com Date: Fri Aug 19 15:03:14 2011 -0400
[BZ 696214] fix so that if user updates one or more prefs via coregui, those updates get synced to portal-war - we do this by clearing server-jar's prefs cache for that user so the cache will refresh and pick up the updates (https://bugzilla.redhat.com/show_bug.cgi?id=696214)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java index 064035d..6079bf3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/SubjectGWTServiceImpl.java @@ -24,6 +24,7 @@ import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.SubjectGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.auth.SubjectManagerLocal; +import org.rhq.enterprise.server.auth.prefs.SubjectPreferencesCache; import org.rhq.enterprise.server.exception.LoginException; import org.rhq.enterprise.server.util.LookupUtil;
@@ -88,8 +89,12 @@ public class SubjectGWTServiceImpl extends AbstractGWTServiceImpl implements Sub
public Subject updateSubject(Subject subjectToModify) throws RuntimeException { try { - return SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify), - "SubjectManager.updateSubject"); + Subject subject = SerialUtility.prepare(subjectManager.updateSubject(getSessionSubject(), subjectToModify), + "SubjectManager.updateSubject"); + // Clear the prefs for this subject from the user prefs cache that portal-war uses, in case we just + // changed any prefs; otherwise the cache would contain stale prefs. + SubjectPreferencesCache.getInstance().clearConfiguration(subject.getId()); + return subject; } catch (Throwable t) { throw getExceptionToThrowToClient(t); }
commit cf9bcd6d8b65eabf03c19de9c231046d493c01bf Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Aug 19 12:03:24 2011 -0400
More work on op scheduling. Now will not schedule job with invalid op parameters config. Will provide warning message for invalid param or trigger config and wait for resolution. - removed some dead code and some minor refactoring for clarity
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java index 23a0469..bddf144 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java @@ -201,6 +201,10 @@ public abstract class AbstractRecordEditor<DS extends RPCDataSource> extends Loc return this.dataSource; }
+ public String getDataTypeName() { + return dataTypeName; + } + public boolean isReadOnly() { return this.isReadOnly; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java index a65fa33..0f001e5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.
import java.util.ArrayList; import java.util.Date; +import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,6 +51,7 @@ import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; @@ -64,6 +66,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.operation.schedule.ResourceOperationScheduleDataSource; import org.rhq.enterprise.gui.coregui.client.util.FormUtility; import org.rhq.enterprise.gui.coregui.client.util.TypeConversionUtility; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
@@ -87,8 +90,9 @@ public abstract class AbstractOperationScheduleDetailsView extends private StaticTextItem operationDescriptionItem; private StaticTextItem operationParametersItem; private LocatableHLayout operationParametersConfigurationHolder; + private ConfigurationEditor operationParametersConfigurationEditor; + private Configuration operationParameters; private JobTriggerEditor triggerEditor; - private Configuration parameters; private EnhancedDynamicForm notesForm; private Integer operationDefinitionId;
@@ -322,7 +326,7 @@ public abstract class AbstractOperationScheduleDetailsView extends } notesItem.setValue(notesValue);
- this.parameters = (Configuration) record + this.operationParameters = (Configuration) record .getAttributeAsObject(AbstractOperationScheduleDataSource.Field.PARAMETERS);
super.editExistingRecord(record); @@ -330,12 +334,21 @@ public abstract class AbstractOperationScheduleDetailsView extends
@Override protected void save(DSRequest requestProperties) { - requestProperties.setAttribute(AbstractOperationScheduleDataSource.RequestProperty.PARAMETERS, this.parameters); - - if (!this.triggerEditor.validate()) { - // TODO: print error Message - return; + if ((null != this.operationParametersConfigurationEditor && !this.operationParametersConfigurationEditor + .isValid()) + || !this.triggerEditor.validate()) { + { + Message message = new Message(MSG.widget_recordEditor_warn_validation(this.getDataTypeName()), + Message.Severity.Warning, EnumSet.of(Message.Option.Transient)); + CoreGUI.getMessageCenter().notify(message); + + return; + } } + + requestProperties.setAttribute(AbstractOperationScheduleDataSource.RequestProperty.PARAMETERS, + this.operationParameters); + EnhancedDynamicForm form = getForm();
Record jobTriggerRecord = new ListGridRecord(); @@ -393,30 +406,29 @@ public abstract class AbstractOperationScheduleDetailsView extends } this.operationParametersConfigurationHolder.hide(); } else { + // make sure we wipe out anything left by the previous op def + for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { + child.destroy(); + } + final ConfigurationDefinition parametersDefinition = this.operationNameToParametersDefinitionMap .get(operationName); if (parametersDefinition == null || parametersDefinition.getPropertyDefinitions().isEmpty()) { value = "<i>" + MSG.view_operationScheduleDetails_noParameters() + "</i>"; - // make sure we wipe out anything left by the previous op def - for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { - child.destroy(); - } this.operationParametersConfigurationHolder.hide(); + } else { value = isNewRecord() ? "<i>" + MSG.view_operationScheduleDetails_enterParametersBelow() + "</i>" : "";
- for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { - child.destroy(); - } - // Add spacer so params are indented. VLayout horizontalSpacer = new VLayout(); horizontalSpacer.setWidth(FIRST_COLUMN_WIDTH); this.operationParametersConfigurationHolder.addMember(horizontalSpacer);
if (isNewRecord()) { - this.parameters = (parametersDefinition.getDefaultTemplate() != null) ? parametersDefinition - .getDefaultTemplate().createConfiguration() : new Configuration(); + this.operationParameters = (parametersDefinition.getDefaultTemplate() != null) ? parametersDefinition + .getDefaultTemplate().createConfiguration() + : new Configuration(); } else {
} @@ -427,32 +439,24 @@ public abstract class AbstractOperationScheduleDetailsView extends
@Override public void onFailure(Throwable throwable) { - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - parametersDefinition, parameters); - configurationEditor.setReadOnly(isReadOnly()); - operationParametersConfigurationHolder.addMember(configurationEditor); + operationParametersConfigurationEditor = new ConfigurationEditor("ParametersEditor", + parametersDefinition, operationParameters); + operationParametersConfigurationEditor.setReadOnly(isReadOnly()); + operationParametersConfigurationHolder.addMember(operationParametersConfigurationEditor); operationParametersConfigurationHolder.show();
}
@Override public void onSuccess(ConfigurationDefinition result) { - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - result, parameters); - configurationEditor.setReadOnly(isReadOnly()); - operationParametersConfigurationHolder.addMember(configurationEditor); + operationParametersConfigurationEditor = new ConfigurationEditor("ParametersEditor", + result, operationParameters); + operationParametersConfigurationEditor.setReadOnly(isReadOnly()); + operationParametersConfigurationHolder.addMember(operationParametersConfigurationEditor); operationParametersConfigurationHolder.show();
} }); - - /* - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - parametersDefinition, this.parameters); - configurationEditor.setReadOnly(isReadOnly()); - this.operationParametersConfigurationHolder.addMember(configurationEditor); - this.operationParametersConfigurationHolder.show(); - */ } } this.operationParametersItem.setValue(value);
commit 05d671b031b5626fac75cbce22b84a18675c8e8e Author: Heiko W. Rupp hwr@redhat.com Date: Fri Aug 19 17:19:07 2011 +0200
BZ 732000 Directly return from shutdown operation to prevent a spurious failure message.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java index 2119a52..6168dad 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java @@ -59,7 +59,7 @@ public class HostControllerComponent extends BaseServerComponent implements Oper Operation op = new Operation("shutdown","host",domainHost); Result res = getASConnection().execute(op);
- postProcessResult(name,res); + return postProcessResult(name,res); }
// Defer other stuff to the base component for now
commit cd4a8bc5be50a8bf0ff47aa44baa2e8b67a075f0 Author: Ian Springer ian.springer@redhat.com Date: Fri Aug 19 10:53:14 2011 -0400
[BZ 732041] clear messages in message center and message bar when a user logs out (https://bugzilla.redhat.com/show_bug.cgi?id=732041)
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 80ee92d..2a52e4d 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 @@ -430,6 +430,11 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String>, Event.Na return MSGCONST; }
+ public void reset() { + messageCenter.reset(); + footer.reset(); + } + private class RootCanvas extends VLayout implements BookmarkableView { private ViewId currentViewId; private Canvas currentCanvas; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java index 88e7a9b..24841e3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/Footer.java @@ -235,6 +235,11 @@ public class Footer extends LocatableHLayout { return messageCenter; }
+ public void reset() { + messageBar.reset(); + messageCenter.reset(); + } + private HLayout createHSpacer(int width) { HLayout spacer = new HLayout(); spacer.setWidth(width); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java index b00d8a0..56c3658 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java @@ -505,11 +505,15 @@ public class UserSessionManager { }
sessionState = State.IS_LOGGED_OUT; + Log.info("Destroying session timer..."); coreGuiSessionTimer.cancel(); - Log.info("Destroying http session refresh timer..."); + + Log.info("Destroying HTTP session refresh timer..."); httpSessionTimer.cancel();
+ CoreGUI.get().reset(); + // log out the web session on the server-side in a delayed fashion, // allowing enough time to pass to let in-flight requests complete scheduleLogoutServerSide(String.valueOf(sessionSubject.getSessionId())); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java index 5d48055..25a8782 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java @@ -135,6 +135,10 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag } }
+ public void reset() { + clearMessage(true); + } + public void clearMessage(boolean clearSticky) { this.currentMessage = null; setLabelEmpty(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java index d9fba53..dbba59c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageCenter.java @@ -73,6 +73,10 @@ public class MessageCenter { return messages; }
+ public void reset() { + this.messages.clear(); + } + public interface MessageListener { void onMessage(Message message); } 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 f692f44..1a6b896 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 @@ -100,7 +100,7 @@ public class MessageCenterView extends Table implements MessageCenter.MessageLis try { window.hide(); } catch (Throwable e) { - Log.warn("Cannot destroy message center", e); + Log.warn("Cannot hide message center", e); } } }); @@ -127,6 +127,13 @@ public class MessageCenterView extends Table implements MessageCenter.MessageLis } }
+ public void reset() { + if (window != null) { + window.hide(); + } + refresh(); + } + @Override protected void configureTable() { getListGrid().setEmptyMessage(MSG.view_messageCenter_noRecentMessages());
commit a2489d6626a8a4ba5b36c80acc366883adb4ddc3 Author: Ian Springer ian.springer@redhat.com Date: Fri Aug 19 10:49:29 2011 -0400
[BZ 663722] fix bug in original fix for RHQ user passwords with special characters not working (https://bugzilla.redhat.com/show_bug.cgi?id=663722)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index f0422ae..b0d418f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -526,8 +526,8 @@ public class LoginView extends LocatableCanvas { requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); // URL-encode the username and password in case they contain URL special characters ('?', '&', '%', '+', // etc.), which would corrupt the request if not encoded. - String encodedUsername = URL.encode(username); - String encodedPassword = URL.encode(password); + String encodedUsername = URL.encodeComponent(username); + String encodedPassword = URL.encodeComponent(password); String requestData = "j_username=" + encodedUsername + "&j_password=" + encodedPassword; requestBuilder.setRequestData(requestData); requestBuilder.setCallback(new RequestCallback() {
commit b6bb1914c3e83c2655872c2104ac7773cf029f45 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Aug 19 10:05:13 2011 -0400
Add the default drift server plugin to the ear packaging.
diff --git a/modules/enterprise/server/ear/pom.xml b/modules/enterprise/server/ear/pom.xml index b1502d6..8cdaf8b 100644 --- a/modules/enterprise/server/ear/pom.xml +++ b/modules/enterprise/server/ear/pom.xml @@ -333,6 +333,13 @@ <artifactId>packagetype-cli</artifactId> <version>${project.version}</version> </artifactItem> + + <artifactItem> + <groupId>org.rhq</groupId> + <artifactId>rhq-serverplugin-drift</artifactId> + <version>${project.version}</version> + </artifactItem> + </artifactItems> <outputDirectory>${earDirectory}/rhq-serverplugins</outputDirectory> </configuration>
commit c5c70b8558f02f326030d7f43c63a81d6753d555 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 23:13:01 2011 -0400
<option> no longer supports default attrib
diff --git a/etc/samples/custom-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml b/etc/samples/custom-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml index 46bf0e7..eb390ab 100644 --- a/etc/samples/custom-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/etc/samples/custom-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml @@ -41,7 +41,7 @@ <c:simple-property name="scheduleType" type="string" required="true" default="cron" summary="true" description="Indicates when the schedule triggers"> <c:property-options> <c:option value="periodic"/> - <c:option value="cron" default="true"/> + <c:option value="cron" /> </c:property-options> </c:simple-property> <c:simple-property name="scheduleTrigger" type="string" required="true" default="0 0/5 * * * ?" summary="true" description="Based on the schedule type, this is either the period, in milliseconds, or the cron expression"/> @@ -77,7 +77,7 @@ <c:simple-property name="enabled" type="boolean" required="true" default="true" summary="true" description="Whether or not the job should be scheduled"/> <c:simple-property name="scheduleType" type="string" required="true" default="periodic" summary="true" description="Indicates when the schedule triggers"> <c:property-options> - <c:option value="periodic" default="true"/> + <c:option value="periodic" /> <c:option value="cron" /> </c:property-options> </c:simple-property> diff --git a/etc/samples/simplereport-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml b/etc/samples/simplereport-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml index 180b711..452a771 100644 --- a/etc/samples/simplereport-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/etc/samples/simplereport-serverplugin/src/main/resources/META-INF/rhq-serverplugin.xml @@ -26,7 +26,7 @@ description="Indicates when the reports should be generated"> <c:property-options> <c:option value="periodic"/> - <c:option value="cron" default="true" /> + <c:option value="cron" /> </c:property-options> </c:simple-property> <c:simple-property name="scheduleTrigger" type="string" required="true" default="0 0/5 * * * ?" summary="true" @@ -50,7 +50,7 @@ <c:simple-property name="scheduleType" type="string" required="true" default="periodic" summary="true" description="Indicates when the report should be generated"> <c:property-options> - <c:option value="periodic" default="true" /> + <c:option value="periodic" /> <c:option value="cron" /> </c:property-options> </c:simple-property> diff --git a/modules/core/plugin-container/src/test/xml/rhq-plugin-jmx-server-test.xml b/modules/core/plugin-container/src/test/xml/rhq-plugin-jmx-server-test.xml index 1bc6c55..583601d 100644 --- a/modules/core/plugin-container/src/test/xml/rhq-plugin-jmx-server-test.xml +++ b/modules/core/plugin-container/src/test/xml/rhq-plugin-jmx-server-test.xml @@ -10,7 +10,7 @@ <plugin-configuration> <c:simple-property name="type" type="string" description="The EMS connection type for this JMX Server"> <c:property-options> - <c:option value="JDK5ConnectionType" default="true"/> + <c:option value="JDK5ConnectionType"/> <c:option value="JBossConnectionType"/> </c:property-options> </c:simple-property> diff --git a/modules/enterprise/server/plugins/cloud/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/cloud/src/main/resources/META-INF/rhq-serverplugin.xml index e6944c0..f475641 100644 --- a/modules/enterprise/server/plugins/cloud/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/cloud/src/main/resources/META-INF/rhq-serverplugin.xml @@ -33,7 +33,7 @@ summary="true" description="Indicates the type of trigger this synchronize job will use"> <c:property-options> - <c:option value="periodic" default="true"/> + <c:option value="periodic" /> <c:option value="cron"/> </c:property-options> </c:simple-property>
commit 2012267a9dab1f48dcbda2febd6f0fb7f007bf2d Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 23:06:18 2011 -0400
fix this so it can build standalone
diff --git a/etc/samples/custom-serverplugin/pom.xml b/etc/samples/custom-serverplugin/pom.xml index 555fe7f..68d76f6 100644 --- a/etc/samples/custom-serverplugin/pom.xml +++ b/etc/samples/custom-serverplugin/pom.xml @@ -15,7 +15,7 @@ <description>A template for building a custom generic RHQ Server plugin</description>
<properties> - <rhq.version>3.0.0.B05</rhq.version> + <rhq.version>4.0.1</rhq.version> </properties>
<dependencies> @@ -28,6 +28,13 @@ <scope>provided</scope> <!-- provided by the server/plugin-container --> </dependency>
+ <dependency> + <groupId>org.rhq</groupId> + <artifactId>rhq-core-domain</artifactId> + <version>${rhq.version}</version> + <scope>provided</scope> <!-- provided by the server/plugin-container --> + </dependency> + <!-- TODO: This is a fix for the Javac bug requiring annotations to be available when compiling dependent classes. It is fixed in JDK 6. --> <dependency>
commit 306f6841328cb0087a4964ae0aa8f15b6a9177a8 Merge: b73d33a 77d91c0 Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 20:53:50 2011 -0400
Merge branch 'master' into drift
commit 77d91c08addab77787c7f151047f39b0d66d73a3 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 17:45:15 2011 -0400
path name was wrong
diff --git a/modules/enterprise/server/plugins/drift-rhq/pom.xml b/modules/enterprise/server/plugins/drift-rhq/pom.xml index 6ca8c6c..9c9d3b6 100644 --- a/modules/enterprise/server/plugins/drift-rhq/pom.xml +++ b/modules/enterprise/server/plugins/drift-rhq/pom.xml @@ -16,12 +16,12 @@ <description>Server side plugin providing RHQ Backend for drift management</description>
<scm> - <connection>scm:git:ssh://git.fedorahosted.org/git/rhq.git/modules/enterprise/server/plugins/drift/</connection> - <developerConnection>scm:git:ssh://git.fedorahosted.org/git/rhq.git/modules/enterprise/server/plugins/drift/</developerConnection> + <connection>scm:git:ssh://git.fedorahosted.org/git/rhq.git/modules/enterprise/server/plugins/drift-rhq/</connection> + <developerConnection>scm:git:ssh://git.fedorahosted.org/git/rhq.git/modules/enterprise/server/plugins/drift-rhq/</developerConnection> </scm>
<properties> - <scm.module.path>modules/enterprise/server/plugins/drift/</scm.module.path> + <scm.module.path>modules/enterprise/server/plugins/drift-rhq/</scm.module.path> </properties>
<dependencies>
commit b73d33a9758755bee235ad7e070ba7e420b98d2d Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 17:25:26 2011 -0400
Remove diffutils lib from core/util since it's not used here
diff --git a/modules/core/util/pom.xml b/modules/core/util/pom.xml index c94e4e6..dfa5bb8 100644 --- a/modules/core/util/pom.xml +++ b/modules/core/util/pom.xml @@ -52,12 +52,6 @@ <scope>test</scope> </dependency>
- <dependency> - <groupId>com.googlecode.java-diff-utils</groupId> - <artifactId>diffutils</artifactId> - <version>1.2.1</version> - </dependency> - </dependencies>
<build> diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java b/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java deleted file mode 100644 index 832e212..0000000 --- a/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java +++ /dev/null @@ -1,40 +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.util.file; - -import java.util.List; - -import difflib.DiffUtils; -import difflib.Patch; - -import static java.util.Arrays.asList; - -public class DiffUtil { - - public static List<String> generateUnifiedDiff(String oldContent, String newContent) { - List<String> oldList = asList(oldContent.split("\n")); - List<String> newList = asList(newContent.split("\n")); - - Patch patch = DiffUtils.diff(oldList, newList); - - return DiffUtils.generateUnifiedDiff("test.txt:12", "test.txt:32", oldList, patch, 5); - } - -} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java deleted file mode 100644 index 2e7e738..0000000 --- a/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java +++ /dev/null @@ -1,47 +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.util.file; - -import java.util.List; - -import org.testng.annotations.Test; - -public class DiffUtilTest { - - @Test - public void generateUnifiedDiff() throws Exception { - String original = "This is a test for diffing.\n" + - "I want to see what it generates for a unified diff.\n" + - "\n" + - "- John"; - - String modified = "This a test for diffing files.\n" + - "I want to see what it generates for a unified diff.\n" + - "I will eventually test other capabilities as well.\n" + - "\n" + - "- John"; - - List<String> deltas = DiffUtil.generateUnifiedDiff(original, modified); - for (String delta : deltas) { - System.out.println(delta); - } - } - -}
commit b08cf4047af122f3e9ece38a390d4cec36905d9f Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 18 16:49:47 2011 -0400
[BZ - 695810 - Unable to schedule operation from context menu in group tree] Now makes sure the async handling in the group init plays well with others. - extra: sort the op def display names in the drop down
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDataSource.java index 7ee12ad..ebab73e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDataSource.java @@ -19,10 +19,11 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail.operation.schedule;
+import java.util.Comparator; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; -import java.util.Set; +import java.util.TreeSet;
import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DataSourceField; @@ -102,7 +103,14 @@ public abstract class AbstractOperationScheduleDataSource<T extends OperationSch
DataSourceTextField operationNameField = createTextField(Field.OPERATION_NAME, MSG .dataSource_operationSchedule_field_operationName(), null, 100, true); - Set<OperationDefinition> operationDefinitions = this.resourceType.getOperationDefinitions(); + // sort the op def names in the drop down + TreeSet<OperationDefinition> operationDefinitions = new TreeSet<OperationDefinition>( + new Comparator<OperationDefinition>() { + public int compare(OperationDefinition o1, OperationDefinition o2) { + return o1.getDisplayName().compareTo(o2.getDisplayName()); + } + }); + operationDefinitions.addAll(this.resourceType.getOperationDefinitions()); LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>(); for (OperationDefinition operationDefinition : operationDefinitions) { valueMap.put(operationDefinition.getName(), operationDefinition.getDisplayName()); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java index 38c46a0..a65fa33 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java @@ -113,21 +113,30 @@ public abstract class AbstractOperationScheduleDetailsView extends public void renderView(ViewPath viewPath) { super.renderView(viewPath);
- int operationDefinitionId = 0; + // If the operationDefId has been seeded capture it now + this.operationDefinitionId = 0; if (!viewPath.isEnd()) { - operationDefinitionId = viewPath.getCurrentAsInt(); + this.operationDefinitionId = viewPath.getCurrentAsInt(); viewPath.next(); }
// Existing schedules are not editable. This may change in the future. boolean isReadOnly = (!hasControlPermission() || (getRecordId() != 0)); + + // Note: subclases may override this and perform async work prior to calling super, so + // be careful adding any code after this point in this method. init(isReadOnly); + } + + @Override + protected void init(boolean isReadOnly) { + super.init(isReadOnly);
// If the operationDefId has been seeded then treat it as a user-initiated change to // update associated widgets and button enablement. - if (operationDefinitionId > 0) { + if (this.operationDefinitionId != null) { FormItem nameField = this.getForm().getField(AbstractOperationScheduleDataSource.Field.OPERATION_NAME); - nameField.setValue(this.operationIdToNameMap.get(operationDefinitionId)); + nameField.setValue(this.operationIdToNameMap.get(this.operationDefinitionId)); handleOperationNameChange(); getForm().rememberValues(); } @@ -270,11 +279,6 @@ public abstract class AbstractOperationScheduleDetailsView extends protected Record createNewRecord() { Record record = super.createNewRecord();
- if (this.operationDefinitionId != null) { - String operationName = this.operationIdToNameMap.get(this.operationDefinitionId); - record.setAttribute(AbstractOperationScheduleDataSource.Field.OPERATION_NAME, operationName); - } - Subject sessionSubject = UserSessionManager.getSessionSubject(); AbstractOperationScheduleDataSource.SubjectRecord subjectRecord = new AbstractOperationScheduleDataSource.SubjectRecord( sessionSubject);
commit 804156d18f90aa65df3bb6b3bb7dc89e60946ce6 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 18 12:29:00 2011 -0400
Operation scheduling fixes - [BZ 695810 - Unable to schedule operation from context menu in group tree] - fix issues when seeding the operation def via tree context menu ( which equates to direct navigation) - fix reset to not assume the save/reset buttons should be disabled. we may not always reset to "no selection". - remove blinking button on enablement change, it's distracting and not standard in the gui. - get rid of some compiler warnings
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java index f9249f4..23a0469 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/form/AbstractRecordEditor.java @@ -47,7 +47,6 @@ import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.DetailsView; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.TitleBar; -import org.rhq.enterprise.gui.coregui.client.util.CanvasUtility; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; @@ -60,6 +59,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * * @author Ian Springer */ +@SuppressWarnings("unchecked") public abstract class AbstractRecordEditor<DS extends RPCDataSource> extends LocatableVLayout implements BookmarkableView, DetailsView {
@@ -229,13 +229,15 @@ public abstract class AbstractRecordEditor<DS extends RPCDataSource> extends Loc IButton saveButton = this.buttonBar.getSaveButton(); if (saveButton.isDisabled()) { saveButton.setDisabled(false); - CanvasUtility.blink(saveButton); + // removing blink, I think it's distracting and it's not consistent with the rest of the gui (jshaughn) + //CanvasUtility.blink(saveButton); }
IButton resetButton = this.buttonBar.getResetButton(); if (resetButton.isDisabled()) { resetButton.setDisabled(false); - CanvasUtility.blink(resetButton); + // removing blink, I think it's distracting and it's not consistent with the rest of the gui (jshaughn) + //CanvasUtility.blink(resetButton); } } } @@ -455,9 +457,9 @@ public abstract class AbstractRecordEditor<DS extends RPCDataSource> extends Loc resetButton.setDisabled(true); resetButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { - reset(); resetButton.disable(); saveButton.disable(); + reset(); } }); hLayout.addMember(resetButton); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java index ed727db..38c46a0 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/operation/schedule/AbstractOperationScheduleDetailsView.java @@ -72,6 +72,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * * @author Ian Springer */ +@SuppressWarnings("unchecked") public abstract class AbstractOperationScheduleDetailsView extends AbstractRecordEditor<AbstractOperationScheduleDataSource> {
@@ -112,14 +113,24 @@ public abstract class AbstractOperationScheduleDetailsView extends public void renderView(ViewPath viewPath) { super.renderView(viewPath);
+ int operationDefinitionId = 0; if (!viewPath.isEnd()) { - this.operationDefinitionId = viewPath.getCurrentAsInt(); + operationDefinitionId = viewPath.getCurrentAsInt(); viewPath.next(); }
// Existing schedules are not editable. This may change in the future. boolean isReadOnly = (!hasControlPermission() || (getRecordId() != 0)); init(isReadOnly); + + // If the operationDefId has been seeded then treat it as a user-initiated change to + // update associated widgets and button enablement. + if (operationDefinitionId > 0) { + FormItem nameField = this.getForm().getField(AbstractOperationScheduleDataSource.Field.OPERATION_NAME); + nameField.setValue(this.operationIdToNameMap.get(operationDefinitionId)); + handleOperationNameChange(); + getForm().rememberValues(); + } }
@Override @@ -146,8 +157,7 @@ public abstract class AbstractOperationScheduleDetailsView extends items.add(operationNameItem); operationNameItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { - refreshOperationDescriptionItem(); - refreshOperationParametersItem(); + handleOperationNameChange(); } });
@@ -164,6 +174,23 @@ public abstract class AbstractOperationScheduleDetailsView extends return items; }
+ // override reset because we can't just blindly reset the op def name and leave behind associated widgets + @Override + protected void reset() { + super.reset(); + handleOperationNameChange(); + } + + // The same logic needs to get applied to a user-initiated change, direct navigation to an op def, and + // a reset, which may reset to a selected op def, or to no op def. + private void handleOperationNameChange() { + refreshOperationDescriptionItem(); + refreshOperationParametersItem(); + if (null != getSelectedOperationName()) { + onItemChanged(); + } + } + @Override protected LocatableVLayout buildContentPane() { LocatableVLayout contentPane = super.buildContentPane(); @@ -357,12 +384,16 @@ public abstract class AbstractOperationScheduleDetailsView extends String value; if (operationName == null) { value = "<i>" + MSG.view_operationScheduleDetails_fieldDefault_parameters() + "</i>"; + for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { + child.destroy(); + } + this.operationParametersConfigurationHolder.hide(); } else { final ConfigurationDefinition parametersDefinition = this.operationNameToParametersDefinitionMap .get(operationName); if (parametersDefinition == null || parametersDefinition.getPropertyDefinitions().isEmpty()) { value = "<i>" + MSG.view_operationScheduleDetails_noParameters() + "</i>"; - + // make sure we wipe out anything left by the previous op def for (Canvas child : this.operationParametersConfigurationHolder.getChildren()) { child.destroy(); } @@ -387,38 +418,37 @@ public abstract class AbstractOperationScheduleDetailsView extends }
ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService(); - configurationService.getOptionValuesForConfigDefinition(parametersDefinition,new AsyncCallback<ConfigurationDefinition>() { - - - @Override - public void onFailure(Throwable throwable) { - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - parametersDefinition, parameters); - configurationEditor.setReadOnly(isReadOnly()); - operationParametersConfigurationHolder.addMember(configurationEditor); - operationParametersConfigurationHolder.show(); - - } - - @Override - public void onSuccess(ConfigurationDefinition result) { - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - result, parameters); - configurationEditor.setReadOnly(isReadOnly()); - operationParametersConfigurationHolder.addMember(configurationEditor); - operationParametersConfigurationHolder.show(); - - } - }); - - -/* - ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", - parametersDefinition, this.parameters); - configurationEditor.setReadOnly(isReadOnly()); - this.operationParametersConfigurationHolder.addMember(configurationEditor); - this.operationParametersConfigurationHolder.show(); -*/ + configurationService.getOptionValuesForConfigDefinition(parametersDefinition, + new AsyncCallback<ConfigurationDefinition>() { + + @Override + public void onFailure(Throwable throwable) { + ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", + parametersDefinition, parameters); + configurationEditor.setReadOnly(isReadOnly()); + operationParametersConfigurationHolder.addMember(configurationEditor); + operationParametersConfigurationHolder.show(); + + } + + @Override + public void onSuccess(ConfigurationDefinition result) { + ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", + result, parameters); + configurationEditor.setReadOnly(isReadOnly()); + operationParametersConfigurationHolder.addMember(configurationEditor); + operationParametersConfigurationHolder.show(); + + } + }); + + /* + ConfigurationEditor configurationEditor = new ConfigurationEditor("ParametersEditor", + parametersDefinition, this.parameters); + configurationEditor.setReadOnly(isReadOnly()); + this.operationParametersConfigurationHolder.addMember(configurationEditor); + this.operationParametersConfigurationHolder.show(); + */ } } this.operationParametersItem.setValue(value);
commit aa5e9d25a1446ebb5b2fa009ee45fb21fb642215 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 17:17:48 2011 -0400
add diff lib
diff --git a/.classpath b/.classpath index a46eaf4..52f9dab 100644 --- a/.classpath +++ b/.classpath @@ -118,7 +118,8 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-core-asl/1.7.4/jackson-core-asl-1.7.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.7.4/jackson-mapper-asl-1.7.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.3/mongo-java-driver-2.6.3.jar"/> - <classpathentry kind="var" path="M2_REPO/com/google/code/morphia/morphia/0.99/morphia-0.99.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/googlecode/java-diff-utils/diffutils/1.2.1/diffutils-1.2.1.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/morphia/morphia/0.99/morphia-0.99.jar"/> <classpathentry exported="true" kind="lib" path="modules/enterprise/remoting/webservices/target/rhq-remoting-webservices-4.1.0-SNAPSHOT/wsconsume-output"/> <classpathentry kind="src" path="modules/common/ant-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/drift-mongodb/src/main/java"/>
commit 831bee8fb6fe6b31f4bf5f332258062d7b956ce8 Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 17:07:50 2011 -0400
Add version info to file/diff viewers
When clicking the 'view' link to display the file contents, the title of the window is now <path>:<version> where version is the change set version. Version numbers are now also present in the diff viewer.
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 7d7a006..1dd9e56 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 @@ -36,13 +36,16 @@ import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.layout.VLayout;
+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.FileDiffReport; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.PopupWindow; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; +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.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; @@ -73,10 +76,12 @@ public class DriftDetailsView extends LocatableVLayout { }
private void show(String driftId) { + final DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService(); + GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.addFilterId(driftId); criteria.fetchChangeSet(true); - GWTServiceLookup.getDriftService().findDriftsByCriteria(criteria, + driftService.findDriftsByCriteria(criteria, new AsyncCallback<PageList<? extends Drift>>() { @Override public void onSuccess(PageList<? extends Drift> result) { @@ -86,8 +91,28 @@ public class DriftDetailsView extends LocatableVLayout { + "] results. Should have been 1. The details shown here might not be correct.", Severity.Warning)); } - Drift drift = result.get(0); - show(drift); + final Drift drift = result.get(0); + if (drift.getCategory() == FILE_CHANGED) { + GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria(); + criteria.addFilterResourceId(drift.getChangeSet().getResourceId()); + criteria.addFilterDriftConfigurationId(drift.getChangeSet().getDriftConfigurationId()); + criteria.addFilterVersion(Integer.toString(drift.getChangeSet().getVersion() - 1)); + + driftService.findDriftChangeSetsByCriteria(criteria, + new AsyncCallback<PageList<? extends DriftChangeSet>>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load change set", caught); + } + + @Override + public void onSuccess(PageList<? extends DriftChangeSet> changeSets) { + show(drift, changeSets.get(0)); + } + }); + } else { + show(drift, null); + } }
@Override @@ -97,7 +122,7 @@ public class DriftDetailsView extends LocatableVLayout { }); }
- private void show(final Drift drift) { + private void show(final Drift drift, final DriftChangeSet previousVersion) { for (Canvas child : getMembers()) { removeMember(child); child.destroy(); @@ -165,21 +190,25 @@ public class DriftDetailsView extends LocatableVLayout { oldFile.setValue(MSG.common_label_none()); oldFileLink = spacer; newFile.setValue(drift.getNewDriftFile().getHashId()); - newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId()); + newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId(), drift.getPath(), + drift.getChangeSet().getVersion()); break;
case FILE_CHANGED: category.setValue(DriftDataSource.CATEGORY_ICON_CHANGE); oldFile.setValue(drift.getOldDriftFile().getHashId()); - oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId()); + oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId(), drift.getPath(), + previousVersion.getVersion()); newFile.setValue(drift.getNewDriftFile().getHashId()); - newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId()); + newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId(), drift.getPath(), + drift.getChangeSet().getVersion()); break;
case FILE_REMOVED: category.setValue(DriftDataSource.CATEGORY_ICON_REMOVE); oldFile.setValue(drift.getOldDriftFile().getHashId()); - oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId()); + oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId(), drift.getPath(), + drift.getChangeSet().getVersion()); newFile.setValue(MSG.common_label_none()); newFileLink = spacer; break; @@ -197,28 +226,16 @@ public class DriftDetailsView extends LocatableVLayout { driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, newFile, newFileLink, numberOfChanges, viewDiffLink);
- generateDiff(drift, numberOfChanges, viewDiffLink); + generateDiff(drift, previousVersion.getVersion(), numberOfChanges, viewDiffLink); } else { driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, newFile, newFileLink); }
addMember(driftForm); - -// HLayout layout = new HLayout(); -// layout.setLayoutMargin(10); -// layout.setMembersMargin(20); -// -// Button viewHistory = new Button("View History"); -// Button viewDiff = new Button("View Diff"); -// viewDiff.setDisabled(true); -// -// layout.addMember(viewHistory); -// layout.addMember(viewDiff); -// addMember(layout); }
- private LinkItem createViewFileLink(final String hash) { + private LinkItem createViewFileLink(final String hash, final String path, final int version) { LinkItem link = new LinkItem(hash + "_fileLink"); link.setShowTitle(false); link.setLinkTitle("(view)"); @@ -233,8 +250,8 @@ public class DriftDetailsView extends LocatableVLayout { }
@Override - public void onSuccess(String result) { - LocatableWindow fileViewer = createFileViewer(result); + public void onSuccess(String contents) { + LocatableWindow fileViewer = createFileViewer(contents, path, version); fileViewer.show(); } }); @@ -244,7 +261,7 @@ public class DriftDetailsView extends LocatableVLayout { return link; }
- private LocatableWindow createFileViewer(String contents) { + private LocatableWindow createFileViewer(String contents, String path, int version) { VLayout layout = new VLayout(); DynamicForm form = new DynamicForm(); form.setWidth100(); @@ -262,11 +279,12 @@ public class DriftDetailsView extends LocatableVLayout {
PopupWindow window = new PopupWindow("fileViewer", layout); window.setIsModal(false); + window.setTitle(path + ":" + version);
return window; }
- private LocatableWindow createDiffViewer(String contents) { + private LocatableWindow createDiffViewer(String contents, String path, int oldVersion, int newVersion) { VLayout layout = new VLayout(); DynamicForm form = new DynamicForm(); form.setWidth100(); @@ -286,12 +304,14 @@ public class DriftDetailsView extends LocatableVLayout { layout.addMember(form);
PopupWindow window = new PopupWindow("diffViewer", layout); + window.setTitle(path + ":" + oldVersion + ":" + newVersion); window.setIsModal(false);
return window; }
- private void generateDiff(final Drift drift, final StaticTextItem changes, final LinkItem viewDiff) { + private void generateDiff(final Drift drift, final int oldVersion, final StaticTextItem changes, + final LinkItem viewDiff) { GWTServiceLookup.getDriftService().generateUnifiedDiff(drift, new AsyncCallback<FileDiffReport>() { @Override public void onFailure(Throwable caught) { @@ -305,8 +325,11 @@ public class DriftDetailsView extends LocatableVLayout { viewDiff.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { + int newVersion = drift.getChangeSet().getVersion(); + String diffContents = toHtml(diffReport.getDiff(), oldVersion, newVersion); + //LocatableWindow window = createFileViewer(diffReport.getDiff()); - LocatableWindow window = createDiffViewer(toHtml(diffReport.getDiff())); + LocatableWindow window = createDiffViewer(diffContents, drift.getPath(), oldVersion, newVersion); window.show(); } }); @@ -314,9 +337,13 @@ public class DriftDetailsView extends LocatableVLayout { }); }
- private String toHtml(List<String> deltas) { + private String toHtml(List<String> deltas, int oldVersion, int newVersion) { StringBuilder diff = new StringBuilder(); - for (String line : deltas) { + diff.append("<font color="red">").append(deltas.get(0)).append(":").append(oldVersion).append("</font><br/>"); + diff.append("<font color="green">").append(deltas.get(1)).append(":").append(newVersion) + .append("</font><br/>"); + + for (String line : deltas.subList(2, deltas.size())) { if (line.startsWith("@@")) { diff.append("<font color="purple">").append(line).append("</font><br/>"); } else if (line.startsWith("-")) { 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 8d35995..60c2547 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 @@ -358,8 +358,7 @@ public class DriftManagerBean implements DriftManagerLocal { List<String> newList = asList(newContent.split("\n"));
Patch patch = DiffUtils.diff(oldList, newList); - List<String> deltas = DiffUtils.generateUnifiedDiff(drift.getPath() + ":old", drift.getPath() + ":new", - oldList, patch, 10); + List<String> deltas = DiffUtils.generateUnifiedDiff(drift.getPath(), drift.getPath(), oldList, patch, 10);
return new FileDiffReport(patch.getDeltas().size(), deltas); }
commit adaec0ef9d777a67ca7dbc46fdc2722e0adaeed0 Author: Ian Springer ian.springer@redhat.com Date: Thu Aug 18 16:34:08 2011 -0400
[BZ 720000] add more null checking during parsing of portlet pref props in order to prevent NPEs (https://bugzilla.redhat.com/show_bug.cgi?id=720000)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java index 5fb7aeb..448f357 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java @@ -240,56 +240,51 @@ public class ResourceConfigurationUpdatesPortlet extends GroupConfigurationUpdat // } //result timeframe if enabled PropertySimple property = portletConfig.getSimple(Constant.METRIC_RANGE_ENABLE); - if (Boolean.valueOf(property.getBooleanValue())) {//then proceed setting - - boolean isAdvanced = false; + if (property != null && property.getBooleanValue()) {//then proceed setting //detect type of widget[Simple|Advanced] property = portletConfig.getSimple(Constant.METRIC_RANGE_BEGIN_END_FLAG); - if (property != null) { - isAdvanced = property.getBooleanValue(); - } + boolean isAdvanced = (property != null) && property.getBooleanValue(); if (isAdvanced) { //Advanced time settings - property = portletConfig.getSimple(Constant.METRIC_RANGE); - if (property != null) { - String currentSetting = property.getStringValue(); - String[] range = currentSetting.split(","); + String metricRange = portletConfig.getSimpleValue(Constant.METRIC_RANGE, null); + if (metricRange != null) { + String[] range = metricRange.split(","); criteria.addFilterStartTime(Long.valueOf(range[0])); criteria.addFilterEndTime(Long.valueOf(range[1])); } } else { //Simple time settings property = portletConfig.getSimple(Constant.METRIC_RANGE_LASTN); - if (property != null) { + if (property != null && property.getIntegerValue() != null) { int lastN = property.getIntegerValue(); property = portletConfig.getSimple(Constant.METRIC_RANGE_UNIT); - int lastUnits = property.getIntegerValue(); - ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer - .valueOf(lastUnits)); - criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0))); - criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1))); + if (property != null && property.getIntegerValue() != null) { + int lastUnits = property.getIntegerValue(); + ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer + .valueOf(lastUnits)); + criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0))); + criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1))); + } } } }
//result count - property = portletConfig.getSimple(Constant.RESULT_COUNT); - if (property != null) { - String currentSetting = property.getStringValue(); - if (currentSetting.trim().isEmpty() || currentSetting.equalsIgnoreCase("5")) { + String resultCount = portletConfig.getSimpleValue(Constant.RESULT_COUNT, null); + if (resultCount != null) { + if (resultCount.trim().isEmpty() || resultCount.equals("5")) { pageControl.setPageSize(5); } else { - pageControl = new PageControl(0, Integer.valueOf(currentSetting)); + pageControl = new PageControl(0, Integer.valueOf(resultCount)); } } criteria.setPageControl(pageControl);
//detect operation status filter - property = portletConfig.getSimple(Constant.CONFIG_UPDATE_STATUS); - if (property != null) { - String currentSetting = property.getStringValue(); - String[] parsedValues = currentSetting.trim().split(","); - if (currentSetting.trim().isEmpty() + String configUpdateStatus = portletConfig.getSimpleValue(Constant.CONFIG_UPDATE_STATUS, null); + if (configUpdateStatus != null) { + String[] parsedValues = configUpdateStatus.trim().split(","); + if (configUpdateStatus.trim().isEmpty() || parsedValues.length == ConfigurationUpdateStatus.values().length) { //all operation stati assumed } else {
commit c88d609cf81ef385172667fd842a4f723a9e315b Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 16:11:00 2011 -0400
Use PopupWindow to create a window for displaying files and diffs
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 f37ddf8..7d7a006 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 @@ -41,6 +41,7 @@ import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.PopupWindow; 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; @@ -244,15 +245,6 @@ public class DriftDetailsView extends LocatableVLayout { }
private LocatableWindow createFileViewer(String contents) { - LocatableWindow window = new LocatableWindow("test"); - window.setTitle("File Viewer"); - window.setWidth(800); - window.setHeight(600); - window.setIsModal(false); - window.setCanDragResize(true); - window.setShowResizer(true); - window.centerInPage(); - VLayout layout = new VLayout(); DynamicForm form = new DynamicForm(); form.setWidth100(); @@ -267,21 +259,14 @@ public class DriftDetailsView extends LocatableVLayout {
form.setItems(textArea); layout.addMember(form); - window.addItem(layout); + + PopupWindow window = new PopupWindow("fileViewer", layout); + window.setIsModal(false);
return window; }
- private LocatableWindow createViewer(String contents) { - LocatableWindow window = new LocatableWindow("test"); - window.setTitle("File Viewer"); - window.setWidth(800); - window.setHeight(600); - window.setIsModal(false); - window.setCanDragResize(true); - window.setShowResizer(true); - window.centerInPage(); - + private LocatableWindow createDiffViewer(String contents) { VLayout layout = new VLayout(); DynamicForm form = new DynamicForm(); form.setWidth100(); @@ -299,7 +284,9 @@ public class DriftDetailsView extends LocatableVLayout {
form.setItems(canvasItem); layout.addMember(form); - window.addItem(layout); + + PopupWindow window = new PopupWindow("diffViewer", layout); + window.setIsModal(false);
return window; } @@ -319,7 +306,7 @@ public class DriftDetailsView extends LocatableVLayout { @Override public void onClick(ClickEvent clickEvent) { //LocatableWindow window = createFileViewer(diffReport.getDiff()); - LocatableWindow window = createViewer(toHtml(diffReport.getDiff())); + LocatableWindow window = createDiffViewer(toHtml(diffReport.getDiff())); window.show(); } });
commit 310ab4017183dce3377816b2f097046047cfb6da Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 15:53:35 2011 -0400
Adding some syntax highlighting to the diff
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java index b5b71fc..8afbeb6 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java @@ -20,18 +20,19 @@ package org.rhq.core.domain.drift;
import java.io.Serializable; +import java.util.List;
public class FileDiffReport implements Serializable { private static final long serialVersionUID = 1L;
private int changes;
- private String diff; + List<String> diff;
public FileDiffReport() { }
- public FileDiffReport(int numChanges, String diff) { + public FileDiffReport(int numChanges, List<String> diff) { changes = numChanges; this.diff = diff; } @@ -40,7 +41,7 @@ public class FileDiffReport implements Serializable { return changes; }
- public String getDiff() { + public List<String> getDiff() { return diff; }
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 8f29084..f37ddf8 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 @@ -21,11 +21,12 @@ package org.rhq.enterprise.gui.coregui.client.drift;
import java.util.LinkedHashMap; +import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.widgets.Button; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.LinkItem; import com.smartgwt.client.widgets.form.fields.SpacerItem; @@ -33,7 +34,6 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; -import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.criteria.GenericDriftCriteria; @@ -272,6 +272,38 @@ public class DriftDetailsView extends LocatableVLayout { return window; }
+ private LocatableWindow createViewer(String contents) { + LocatableWindow window = new LocatableWindow("test"); + window.setTitle("File Viewer"); + window.setWidth(800); + window.setHeight(600); + window.setIsModal(false); + window.setCanDragResize(true); + window.setShowResizer(true); + window.centerInPage(); + + VLayout layout = new VLayout(); + DynamicForm form = new DynamicForm(); + form.setWidth100(); + form.setHeight100(); + + CanvasItem canvasItem = new CanvasItem(); + canvasItem.setColSpan(2); + canvasItem.setShowTitle(false); + canvasItem.setWidth("*"); + canvasItem.setHeight("*"); + + Canvas canvas = new Canvas(); + canvas.setContents(contents); + canvasItem.setCanvas(canvas); + + form.setItems(canvasItem); + layout.addMember(form); + window.addItem(layout); + + return window; + } + private void generateDiff(final Drift drift, final StaticTextItem changes, final LinkItem viewDiff) { GWTServiceLookup.getDriftService().generateUnifiedDiff(drift, new AsyncCallback<FileDiffReport>() { @Override @@ -286,7 +318,8 @@ public class DriftDetailsView extends LocatableVLayout { viewDiff.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { - LocatableWindow window = createFileViewer(diffReport.getDiff()); + //LocatableWindow window = createFileViewer(diffReport.getDiff()); + LocatableWindow window = createViewer(toHtml(diffReport.getDiff())); window.show(); } }); @@ -294,4 +327,21 @@ public class DriftDetailsView extends LocatableVLayout { }); }
+ private String toHtml(List<String> deltas) { + StringBuilder diff = new StringBuilder(); + for (String line : deltas) { + if (line.startsWith("@@")) { + diff.append("<font color="purple">").append(line).append("</font><br/>"); + } else if (line.startsWith("-")) { + diff.append("<font color="red">").append(line).append("</font><br/>"); + } else if (line.startsWith("+")) { + diff.append("<font color="green">").append(line).append("</font><br/>"); + } else { + diff.append(line).append("<br/>"); + } + } + + return diff.toString(); + } + } 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 7dff934..8d35995 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 @@ -361,12 +361,7 @@ public class DriftManagerBean implements DriftManagerLocal { List<String> deltas = DiffUtils.generateUnifiedDiff(drift.getPath() + ":old", drift.getPath() + ":new", oldList, patch, 10);
- StringBuilder diff = new StringBuilder(); - for (String delta : deltas) { - diff.append(delta).append("\n"); - } - - return new FileDiffReport(patch.getDeltas().size(), diff.toString()); + return new FileDiffReport(patch.getDeltas().size(), deltas); }
@Override
commit 89d55a95e2de3ace783b85551abd2d34acc8b43a Author: Ian Springer ian.springer@redhat.com Date: Thu Aug 18 15:50:16 2011 -0400
[BZ 731061] don't throw an exception when a job has no triggers, since this can occur when the job has already been triggered for the final time (https://bugzilla.redhat.com/show_bug.cgi?id=731061)
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java index 7e518fa..9dbe236 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerBean.java @@ -260,7 +260,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan Date next = scheduler.scheduleJob(jobDetail, trigger); ResourceOperationSchedule newSchedule = getResourceOperationSchedule(subject, jobDetail);
- LOG.debug("Scheduled resource operation [" + newSchedule + "] - next fire time is [" + next + "]"); + LOG.debug("Scheduled Resource operation [" + newSchedule + "] - next fire time is [" + next + "]");
return newSchedule; } @@ -439,12 +439,14 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan JobDetail jobDetail = scheduler.getJobDetail(jobName, groupName); ResourceOperationSchedule sched = getResourceOperationSchedule(subject, jobDetail);
- if (resourceId != sched.getResource().getId()) { - throw new IllegalStateException("Somehow a different resource [" + sched.getResource() - + "] was scheduled in the same job group as resource [" + resource + "]"); - } + if (sched != null) { + if (resourceId != sched.getResource().getId()) { + throw new IllegalStateException("Somehow a different resource [" + sched.getResource() + + "] was scheduled in the same job group as resource [" + resource + "]"); + }
- operationSchedules.add(sched); + operationSchedules.add(sched); + } }
return operationSchedules; @@ -462,12 +464,14 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan JobDetail jobDetail = scheduler.getJobDetail(jobName, groupName); GroupOperationSchedule sched = getGroupOperationSchedule(subject, jobDetail);
- if (groupId != sched.getGroup().getId()) { - throw new IllegalStateException("Somehow a different group [" + sched.getGroup() - + "] was scheduled in the same job group as group [" + group + "]"); - } + if (sched != null) { + if (groupId != sched.getGroup().getId()) { + throw new IllegalStateException("Somehow a different group [" + sched.getGroup() + + "] was scheduled in the same job group as group [" + group + "]"); + }
- operationSchedules.add(sched); + operationSchedules.add(sched); + } }
return operationSchedules; @@ -533,7 +537,13 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan sched.setSubject(subject); sched.setParameters(parameters); sched.setDescription(description); + Trigger trigger = getTriggerOfJob(jobDetail); + if (trigger == null) { + // The job must have run for the last time - return null to inform the user the job is defunct. + return null; + } + JobTrigger jobTrigger = convertToJobTrigger(trigger); sched.setJobTrigger(jobTrigger); sched.setNextFireTime(trigger.getNextFireTime()); @@ -564,7 +574,11 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan throws SchedulerException { JobId jobIdObject = new JobId(jobId); JobDetail jobDetail = scheduler.getJobDetail(jobIdObject.getJobName(), jobIdObject.getJobGroup()); - return getResourceOperationSchedule(subject, jobDetail); + ResourceOperationSchedule resourceOperationSchedule = getResourceOperationSchedule(subject, jobDetail); + if (resourceOperationSchedule == null) { + throw new SchedulerException("The job with ID [" + jobId + "] is no longer scheduled."); + } + return resourceOperationSchedule; }
public GroupOperationSchedule getGroupOperationSchedule(Subject subject, JobDetail jobDetail) { @@ -626,7 +640,13 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan sched.setExecutionOrder(executionOrder); sched.setDescription(description); sched.setHaltOnFailure(haltOnFailure); + Trigger trigger = getTriggerOfJob(jobDetail); + if (trigger == null) { + // The job must have run for the last time - return null to inform the user the job is defunct. + return null; + } + JobTrigger jobTrigger = convertToJobTrigger(trigger); sched.setJobTrigger(jobTrigger); sched.setNextFireTime(trigger.getNextFireTime()); @@ -637,7 +657,11 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan public GroupOperationSchedule getGroupOperationSchedule(Subject subject, String jobId) throws SchedulerException { JobId jobIdObject = new JobId(jobId); JobDetail jobDetail = scheduler.getJobDetail(jobIdObject.getJobName(), jobIdObject.getJobGroup()); - return getGroupOperationSchedule(subject, jobDetail); + GroupOperationSchedule groupOperationSchedule = getGroupOperationSchedule(subject, jobDetail); + if (groupOperationSchedule == null) { + throw new SchedulerException("The job with ID [" + jobId + "] is no longer scheduled."); + } + return groupOperationSchedule; }
public OperationHistory getOperationHistoryByHistoryId(Subject subject, int historyId) { @@ -1968,6 +1992,7 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan return queryRunner.execute(); }
+ @Nullable private Trigger getTriggerOfJob(JobDetail jobDetail) { Trigger[] triggers; try { @@ -1975,13 +2000,13 @@ public class OperationManagerBean implements OperationManagerLocal, OperationMan } catch (SchedulerException e) { throw new RuntimeException("Failed to lookup trigger for job [" + jobDetail.getFullName() + "].", e); } - if (triggers.length == 0) { - throw new IllegalStateException("Job [" + jobDetail.getFullName() + "] has no triggers."); - } if (triggers.length > 1) { throw new IllegalStateException("Job [" + jobDetail.getFullName() + "] has more than one trigger: " + Arrays.asList(triggers)); } + if (triggers.length == 0) { + return null; + } return triggers[0]; }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java index e365ee8..bf2d77c 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationManagerLocal.java @@ -188,13 +188,14 @@ public interface OperationManagerLocal { List<GroupOperationSchedule> findScheduledGroupOperations(Subject subject, int groupId) throws Exception;
/** - * Given a resource job's details, this returns the schedule for that resource job. + * Given a Resource operation job's details, this returns a schedule POJO corresponding to that job. * * @param subject * @param jobDetail * - * @return the object that encapsulates the resource schedule + * @return the object that encapsulates the resource schedule, or null if the specified job is no longer scheduled */ + @Nullable ResourceOperationSchedule getResourceOperationSchedule(Subject subject, JobDetail jobDetail);
/** @@ -210,13 +211,14 @@ public interface OperationManagerLocal { ResourceOperationSchedule getResourceOperationSchedule(Subject subject, String jobId) throws SchedulerException;
/** - * Given a group job's details, this returns the schedule for that group job. + * Given a group operation job's details, this returns a schedule POJO corresponding to that job. * * @param subject * @param jobDetail * - * @return the object that encapsulates the group schedule + * @return the object that encapsulates the group schedule, , or null if the specified job is no longer scheduled */ + @Nullable GroupOperationSchedule getGroupOperationSchedule(Subject subject, JobDetail jobDetail);
/** @@ -434,7 +436,7 @@ public interface OperationManagerLocal { * * @return the OperationDefinition object that corresponds to this operationId */ - OperationDefinition getOperationDefinition(Subject whoami, int operationId); + OperationDefinition getOperationDefinition(Subject subject, int operationId);
/** * @param resourceTypeId @@ -551,7 +553,7 @@ public interface OperationManagerLocal { * * @param subject * @param resourceId - * @param beginDate filter used to show only results occurring after this epoch millis parameter, nullable + * @param startDate filter used to show only results occurring after this epoch millis parameter, nullable * @param endDate filter used to show only results occurring before this epoch millis parameter, nullable * @param pc * @return all operation histories for the given resource @@ -574,12 +576,12 @@ public interface OperationManagerLocal { PageControl pc);
/** - * #see {@link OperationManagerRemote#getOperationHistoryByHistoryId + * TODO */ OperationHistory getOperationHistoryByHistoryId(Subject subject, int historyId);
/** - * #see {@link OperationManagerRemote#getOperationHistoryByJobId + * TODO */ OperationHistory getOperationHistoryByJobId(Subject subject, String historyJobId);
@@ -647,7 +649,7 @@ public interface OperationManagerLocal { void unscheduleResourceOperation(Subject subject, String jobId, int resourceId) throws UnscheduleException;
/** - * #see {@link OperationManagerRemote#unscheduleGroupOperation(Subject, String, PageControl) + * see {@link OperationManagerRemote#unscheduleGroupOperation(org.rhq.core.domain.auth.Subject, String, int)} */ void unscheduleGroupOperation(Subject subject, String jobId, int resourceGroupId) throws UnscheduleException;
commit d6f6da30f03dbeceeb6275cb8130e3b81a2072d9 Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 14:31:12 2011 -0400
Adding initial support for displaying diff between file and its previous version
If DriftDetailsView is displaying a modified file (as opposed to added or deleted), it will show some additional information in the form of the number of changes between the current and previous version and a link for displaying a unified diff of the two versions.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java new file mode 100644 index 0000000..b5b71fc --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/FileDiffReport.java @@ -0,0 +1,47 @@ +/* + * 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.io.Serializable; + +public class FileDiffReport implements Serializable { + private static final long serialVersionUID = 1L; + + private int changes; + + private String diff; + + public FileDiffReport() { + } + + public FileDiffReport(int numChanges, String diff) { + changes = numChanges; + this.diff = diff; + } + + public int getNumberOfChanges() { + return changes; + } + + public String getDiff() { + return diff; + } + +} 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 6901acc..8f29084 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 @@ -23,6 +23,7 @@ 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.Button; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.FormItem; @@ -32,10 +33,12 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.TextAreaItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; +import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; +import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; @@ -46,6 +49,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED; import static org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter.DATE_TIME_FORMAT_FULL;
/** @@ -180,11 +184,37 @@ public class DriftDetailsView extends LocatableVLayout { break; }
- //driftForm.setItems(id, path, category, timestamp, oldFile, newFile); - driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, + if (drift.getCategory() == FILE_CHANGED) { + StaticTextItem numberOfChanges = new StaticTextItem("numberOfChanges", "Number of Changes"); + numberOfChanges.setValue("Loading..."); + + LinkItem viewDiffLink = new LinkItem("viewDiff"); + viewDiffLink.setLinkTitle("(view diff)"); + viewDiffLink.setShowTitle(false); + viewDiffLink.setDisabled(true); + + driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, + newFile, newFileLink, numberOfChanges, viewDiffLink); + + generateDiff(drift, numberOfChanges, viewDiffLink); + } else { + driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, newFile, newFileLink); + }
addMember(driftForm); + +// HLayout layout = new HLayout(); +// layout.setLayoutMargin(10); +// layout.setMembersMargin(20); +// +// Button viewHistory = new Button("View History"); +// Button viewDiff = new Button("View Diff"); +// viewDiff.setDisabled(true); +// +// layout.addMember(viewHistory); +// layout.addMember(viewDiff); +// addMember(layout); }
private LinkItem createViewFileLink(final String hash) { @@ -241,4 +271,27 @@ public class DriftDetailsView extends LocatableVLayout {
return window; } + + private void generateDiff(final Drift drift, final StaticTextItem changes, final LinkItem viewDiff) { + GWTServiceLookup.getDriftService().generateUnifiedDiff(drift, new AsyncCallback<FileDiffReport>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load change report", caught); + } + + @Override + public void onSuccess(final FileDiffReport diffReport) { + changes.setValue(diffReport.getNumberOfChanges()); + viewDiff.setDisabled(false); + viewDiff.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent clickEvent) { + LocatableWindow window = createFileViewer(diffReport.getDiff()); + window.show(); + } + }); + } + }); + } + } 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 6e71e58..f8e2b20 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 @@ -30,6 +30,7 @@ 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.DriftSnapshot; +import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList;
/** @@ -110,4 +111,6 @@ public interface DriftGWTService extends RemoteService {
String getDriftFileBits(String hash) throws RuntimeException;
+ FileDiffReport generateUnifiedDiff(Drift drift); + } \ 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 eea74af..a71bba2 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 @@ -28,6 +28,7 @@ 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.DriftSnapshot; +import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; @@ -148,4 +149,13 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift throw getExceptionToThrowToClient(t); } } + + @Override + public FileDiffReport generateUnifiedDiff(Drift drift) { + try { + return driftManager.generateUnifiedDiff(drift); + } 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 94ef56e..7dff934 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 @@ -54,9 +54,9 @@ import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode; import org.rhq.core.domain.drift.DriftConfigurationDefinition; 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.resource.Resource; import org.rhq.core.domain.util.PageList; -import org.rhq.core.util.file.DiffUtil; import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.agentclient.AgentClient; import org.rhq.enterprise.server.auth.SubjectManagerLocal; @@ -69,6 +69,10 @@ 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;
@@ -347,11 +351,27 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override - public List<String> generateUnifiedDiff(Drift drift) { + public FileDiffReport generateUnifiedDiff(Drift drift) { String oldContent = getDriftFileBits(drift.getOldDriftFile().getHashId()); + List<String> oldList = asList(oldContent.split("\n")); String newContent = getDriftFileBits(drift.getNewDriftFile().getHashId()); + List<String> newList = asList(newContent.split("\n")); + + Patch patch = DiffUtils.diff(oldList, newList); + List<String> deltas = DiffUtils.generateUnifiedDiff(drift.getPath() + ":old", drift.getPath() + ":new", + oldList, patch, 10); + + StringBuilder diff = new StringBuilder(); + for (String delta : deltas) { + diff.append(delta).append("\n"); + }
- return DiffUtil.generateUnifiedDiff(oldContent, newContent); + return new FileDiffReport(patch.getDeltas().size(), diff.toString()); + } + + @Override + public PageList<Drift> findHistory(Drift drift) { + return null; }
@Override 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 19c77b9..290fb81 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 @@ -20,7 +20,6 @@ package org.rhq.enterprise.server.drift;
import java.io.InputStream; -import java.util.List;
import javax.ejb.Local;
@@ -29,6 +28,7 @@ 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.DriftConfiguration; +import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
@@ -119,5 +119,7 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR */ String getDriftFileBits(String hash);
- List<String> generateUnifiedDiff(Drift drift); + FileDiffReport generateUnifiedDiff(Drift drift); + + PageList<Drift> findHistory(Drift drift); } 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 858051f..fd33467 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 @@ -26,6 +26,7 @@ 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.DriftSnapshot; +import org.rhq.core.domain.drift.FileDiffReport; import org.rhq.core.domain.util.PageList;
@Remote @@ -58,4 +59,6 @@ public interface DriftManagerRemote { */ String getDriftFileBits(String hash);
+ FileDiffReport generateUnifiedDiff(Drift drift); + }
commit 1a5538b42ebd071ac3335766093da0c42355af11 Author: Ian Springer ian.springer@redhat.com Date: Thu Aug 18 11:10:57 2011 -0400
[BZ 663722] URL-encode username and password in POST request used to authenticate with portal-war (https://bugzilla.redhat.com/show_bug.cgi?id=663722)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java index bf4ecf7..f0422ae 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/LoginView.java @@ -31,6 +31,7 @@ import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; +import com.google.gwt.http.client.URL; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.FormErrorOrientation; @@ -515,22 +516,27 @@ public class LoginView extends LocatableCanvas { } }
- private void login(final String user, final String password) { + private void login(final String username, final String password) { BrowserUtility.forceIe6Hacks();
loginButton.setDisabled(true);
try { - RequestBuilder b = new RequestBuilder(RequestBuilder.POST, "/j_security_check.do"); - b.setHeader("Content-Type", "application/x-www-form-urlencoded"); - b.setRequestData("j_username=" + user + "&j_password=" + password); - b.setCallback(new RequestCallback() { + RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, "/j_security_check.do"); + requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded"); + // URL-encode the username and password in case they contain URL special characters ('?', '&', '%', '+', + // etc.), which would corrupt the request if not encoded. + String encodedUsername = URL.encode(username); + String encodedPassword = URL.encode(password); + String requestData = "j_username=" + encodedUsername + "&j_password=" + encodedPassword; + requestBuilder.setRequestData(requestData); + requestBuilder.setCallback(new RequestCallback() { public void onResponseReceived(Request request, Response response) { int statusCode = response.getStatusCode(); if (statusCode == 200) { window.destroy(); loginShowing = false; - UserSessionManager.login(user, password); + UserSessionManager.login(username, password); } else { handleError(statusCode); } @@ -540,7 +546,7 @@ public class LoginView extends LocatableCanvas { handleError(0); } }); - b.send(); + requestBuilder.send(); } catch (Exception e) { handleError(0); } finally {
commit 6cb08366ae31c036b28f00cf7b6bfbf698b5e0e5 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 10:12:03 2011 -0400
make purge time default 31 days
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml index 6af4dd7..42eabc0 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml @@ -129,9 +129,9 @@ <data ID="57" PROPERTY_KEY="ACTIVE_DRIFT_PLUGIN" PROPERTY_VALUE="drift-jpa" DEFAULT_PROPERTY_VALUE="drift-jpa" FREAD_ONLY="FALSE"/>
- <!-- purge drift files older than 7 days by default --> - <data ID="58" PROPERTY_KEY="DRIFT_FILE_PURGE" PROPERTY_VALUE="604800000" - DEFAULT_PROPERTY_VALUE="604800000" FREAD_ONLY="FALSE"/> + <!-- purge drift files older than 31 days by default --> + <data ID="58" PROPERTY_KEY="DRIFT_FILE_PURGE" PROPERTY_VALUE="2678400000" + DEFAULT_PROPERTY_VALUE="2678400000" FREAD_ONLY="FALSE"/>
</table>
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index 1315d9f..414f5a1 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3621,7 +3621,7 @@ <schema-directSQL> <statement desc="Adding drift file purge system setting"> INSERT INTO rhq_system_config (id, property_key, property_value, default_property_value) - VALUES (58, 'DRIFT_FILE_PURGE', '604800000', '604800000') + VALUES (58, 'DRIFT_FILE_PURGE', '2678400000', '2678400000') </statement> </schema-directSQL> </schemaSpec> diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java index a489ce3..0df7ad6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java @@ -423,7 +423,7 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu driftFilePurge.setDisplayName(MSG.view_admin_systemSettings_DriftFilePurge_name()); driftFilePurge.setPropertyGroupDefinition(dataManagerGroup); driftFilePurge.addConstraints(new IntegerRangeConstraint(Long.valueOf(1), null)); - driftFilePurge.setDefaultValue("7"); + driftFilePurge.setDefaultValue("31"); def.put(driftFilePurge);
PropertyDefinitionSimple dataReindex = new PropertyDefinitionSimple(Constant.DataReindex, MSG
commit 78317fc86782bc0554ce04f26c0b6000a7df676f Merge: fc6fa0e fcb3a2b Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 18 10:03:42 2011 -0400
Merge commit 'origin/drift' into drift-file-purge
commit fcb3a2be225a4dd2e710e7fd1886f55493642cb2 Merge: 3afedac 66918cb Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 09:42:00 2011 -0400
Merge branch 'master' into drift
commit 3afedacd9e871528c7dc0c63c548f351fc4e8e0c Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 09:35:16 2011 -0400
Removing calls to executeInTransaction to get test passing on hudson
I think the hudson failures may be due to a difference in TestNG versions, but I will investigate this later after the hudson build is passing again.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java index e436648..2b63aba 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java @@ -28,10 +28,8 @@ import org.testng.annotations.Test; import org.rhq.core.domain.drift.JPADriftFileBits; import org.rhq.enterprise.server.test.AbstractEJB3Test; import org.rhq.enterprise.server.util.LookupUtil; -import org.rhq.test.TransactionCallback;
import static org.rhq.core.domain.drift.DriftFileStatus.LOADED; -import static org.rhq.test.JPAUtils.executeInTransaction;
public class JPADriftServerBeanTest extends AbstractEJB3Test {
@@ -58,13 +56,18 @@ public class JPADriftServerBeanTest extends AbstractEJB3Test { content.setDataSize((long) string.length()); content.setData(Hibernate.createBlob(string.getBytes()));
- executeInTransaction(new TransactionCallback() { - @Override - public void execute() throws Exception { - EntityManager em = getEntityManager(); - em.persist(content); - } - }); + getTransactionManager().begin(); + EntityManager em = getEntityManager(); + em.persist(content); + getTransactionManager().commit(); + +// executeInTransaction(new TransactionCallback() { +// @Override +// public void execute() throws Exception { +// EntityManager em = getEntityManager(); +// em.persist(content); +// } +// }); JPADriftServerLocal driftServer = LookupUtil.getJPADriftServer();
assertEquals("Failed to load content", string, driftServer.getDriftFileBits(content.getHashId()));
commit ba447884eb3098483854ed0ccc8d1308ca67e46b Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 08:43:20 2011 -0400
Trying to fix test failure on hudson
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java index b0616ac..e436648 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java @@ -36,14 +36,17 @@ import static org.rhq.test.JPAUtils.executeInTransaction; public class JPADriftServerBeanTest extends AbstractEJB3Test {
@BeforeMethod - public void initDB() { - executeInTransaction(new TransactionCallback() { - @Override - public void execute() throws Exception { - EntityManager em = getEntityManager(); - em.createQuery("delete from JPADriftFileBits").executeUpdate(); - } - }); + public void initDB() throws Exception { +// executeInTransaction(new TransactionCallback() { +// @Override +// public void execute() throws Exception { +// EntityManager em = getEntityManager(); +// em.createQuery("delete from JPADriftFileBits").executeUpdate(); +// } +// }); + getTransactionManager().begin(); + getEntityManager().createQuery("delete from JPADriftFileBits").executeUpdate(); + getTransactionManager().commit(); }
@Test
commit 37aa6369fe1d4babcdd68a6132fb73bc77c78e9c Author: John Sanda jsanda@redhat.com Date: Thu Aug 18 08:00:42 2011 -0400
Adding initial support for generating a unified diff
This commit adds support in the SLSB layer for generating a unified diff for a Drift object. It compare the two versions referenced by the drift object.
This commit also adds the ability to view file contents on DriftDetailsView. This may very well be throw away work, but it giving me more practice in working with SmartGWT. And the next step is to add the ability to display a unified diff in the UI. Then I will have the ability to view different versions of a file as well as generate a diff of them.
diff --git a/modules/core/util/pom.xml b/modules/core/util/pom.xml index dfa5bb8..c94e4e6 100644 --- a/modules/core/util/pom.xml +++ b/modules/core/util/pom.xml @@ -52,6 +52,12 @@ <scope>test</scope> </dependency>
+ <dependency> + <groupId>com.googlecode.java-diff-utils</groupId> + <artifactId>diffutils</artifactId> + <version>1.2.1</version> + </dependency> + </dependencies>
<build> diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java b/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java new file mode 100644 index 0000000..832e212 --- /dev/null +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/DiffUtil.java @@ -0,0 +1,40 @@ +/* + * 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.util.file; + +import java.util.List; + +import difflib.DiffUtils; +import difflib.Patch; + +import static java.util.Arrays.asList; + +public class DiffUtil { + + public static List<String> generateUnifiedDiff(String oldContent, String newContent) { + List<String> oldList = asList(oldContent.split("\n")); + List<String> newList = asList(newContent.split("\n")); + + Patch patch = DiffUtils.diff(oldList, newList); + + return DiffUtils.generateUnifiedDiff("test.txt:12", "test.txt:32", oldList, patch, 5); + } + +} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java new file mode 100644 index 0000000..2e7e738 --- /dev/null +++ b/modules/core/util/src/test/java/org/rhq/core/util/file/DiffUtilTest.java @@ -0,0 +1,47 @@ +/* + * 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.util.file; + +import java.util.List; + +import org.testng.annotations.Test; + +public class DiffUtilTest { + + @Test + public void generateUnifiedDiff() throws Exception { + String original = "This is a test for diffing.\n" + + "I want to see what it generates for a unified diff.\n" + + "\n" + + "- John"; + + String modified = "This a test for diffing files.\n" + + "I want to see what it generates for a unified diff.\n" + + "I will eventually test other capabilities as well.\n" + + "\n" + + "- John"; + + List<String> deltas = DiffUtil.generateUnifiedDiff(original, modified); + for (String delta : deltas) { + System.out.println(delta); + } + } + +} 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 3ad61c3..6901acc 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 @@ -20,14 +20,19 @@
package org.rhq.enterprise.gui.coregui.client.drift;
-import static org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter.DATE_TIME_FORMAT_FULL; - import java.util.LinkedHashMap;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.LinkItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.TextAreaItem; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +import com.smartgwt.client.widgets.form.fields.events.ClickHandler; +import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; @@ -39,6 +44,9 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow; + +import static org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter.DATE_TIME_FORMAT_FULL;
/** * @author Jay Shaughnessy @@ -84,7 +92,7 @@ public class DriftDetailsView extends LocatableVLayout { }); }
- private void show(Drift drift) { + private void show(final Drift drift) { for (Canvas child : getMembers()) { removeMember(child); child.destroy(); @@ -113,6 +121,9 @@ public class DriftDetailsView extends LocatableVLayout { driftForm.setIsGroup(true); driftForm.setGroupTitle(MSG.view_drift()); driftForm.setWrapItemTitles(false); + driftForm.setNumCols(4); + + SpacerItem spacer = new SpacerItem();
StaticTextItem id = new StaticTextItem("id", MSG.common_title_id()); id.setValue(drift.getId()); @@ -138,30 +149,96 @@ public class DriftDetailsView extends LocatableVLayout { category.setShowIcons(true);
StaticTextItem oldFile = new StaticTextItem("oldFile", MSG.view_drift_table_oldFile()); + FormItem oldFileLink = null; + StaticTextItem newFile = new StaticTextItem("newFile", MSG.view_drift_table_newFile()); + FormItem newFileLink = null;
switch (drift.getCategory()) { case FILE_ADDED: category.setValue(DriftDataSource.CATEGORY_ICON_ADD); oldFile.setValue(MSG.common_label_none()); + oldFileLink = spacer; newFile.setValue(drift.getNewDriftFile().getHashId()); + newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId()); break;
case FILE_CHANGED: category.setValue(DriftDataSource.CATEGORY_ICON_CHANGE); oldFile.setValue(drift.getOldDriftFile().getHashId()); + oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId()); newFile.setValue(drift.getNewDriftFile().getHashId()); + newFileLink = createViewFileLink(drift.getNewDriftFile().getHashId()); break;
case FILE_REMOVED: category.setValue(DriftDataSource.CATEGORY_ICON_REMOVE); oldFile.setValue(drift.getOldDriftFile().getHashId()); + oldFileLink = createViewFileLink(drift.getOldDriftFile().getHashId()); newFile.setValue(MSG.common_label_none()); + newFileLink = spacer; break; }
- driftForm.setItems(id, path, category, timestamp, oldFile, newFile); + //driftForm.setItems(id, path, category, timestamp, oldFile, newFile); + driftForm.setItems(id, spacer, path, spacer, category, spacer, timestamp, spacer, oldFile, oldFileLink, + newFile, newFileLink);
addMember(driftForm); } + + private LinkItem createViewFileLink(final String hash) { + LinkItem link = new LinkItem(hash + "_fileLink"); + link.setShowTitle(false); + link.setLinkTitle("(view)"); + + link.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent clickEvent) { + GWTServiceLookup.getDriftService().getDriftFileBits(hash, new AsyncCallback<String>() { + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load file", caught); + } + + @Override + public void onSuccess(String result) { + LocatableWindow fileViewer = createFileViewer(result); + fileViewer.show(); + } + }); + } + }); + + return link; + } + + private LocatableWindow createFileViewer(String contents) { + LocatableWindow window = new LocatableWindow("test"); + window.setTitle("File Viewer"); + window.setWidth(800); + window.setHeight(600); + window.setIsModal(false); + window.setCanDragResize(true); + window.setShowResizer(true); + window.centerInPage(); + + VLayout layout = new VLayout(); + DynamicForm form = new DynamicForm(); + form.setWidth100(); + form.setHeight100(); + + TextAreaItem textArea = new TextAreaItem(); + textArea.setShowTitle(false); + textArea.setColSpan(2); + textArea.setValue(contents); + textArea.setWidth("*"); + textArea.setHeight("*"); + + form.setItems(textArea); + layout.addMember(form); + window.addItem(layout); + + return window; + } } 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 7b1c880..6e71e58 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 @@ -108,4 +108,6 @@ public interface DriftGWTService extends RemoteService { */ void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig) throws RuntimeException;
+ String getDriftFileBits(String hash) 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 ca3f30b..eea74af 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 @@ -139,4 +139,13 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift throw getExceptionToThrowToClient(t); } } + + @Override + public String getDriftFileBits(String hash) throws RuntimeException { + try { + return driftManager.getDriftFileBits(hash); + } 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 1200a0d..2bbaa2e 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 @@ -20,6 +20,7 @@ package org.rhq.enterprise.server.drift;
import java.io.File; import java.io.InputStream; +import java.util.List;
import javax.ejb.EJB; import javax.ejb.Stateless; @@ -55,6 +56,7 @@ import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.file.DiffUtil; import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.agentclient.AgentClient; import org.rhq.enterprise.server.auth.SubjectManagerLocal; @@ -345,6 +347,14 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + public List<String> generateUnifiedDiff(Drift drift) { + String oldContent = getDriftFileBits(drift.getOldDriftFile().getHashId()); + String newContent = getDriftFileBits(drift.getNewDriftFile().getHashId()); + + return DiffUtil.generateUnifiedDiff(oldContent, newContent); + } + + @Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) {
// before we do anything, make sure the drift config name is valid 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 9a435e4..69e2d52 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 @@ -20,12 +20,14 @@ package org.rhq.enterprise.server.drift;
import java.io.InputStream; +import java.util.List;
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.drift.Drift; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; @@ -115,4 +117,6 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR * @return The content as a string */ String getDriftFileBits(String hash); + + List<String> generateUnifiedDiff(Drift drift); }
commit 66918cbae7af05caf897da41231109d5b427737f Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 17 20:40:41 2011 -0400
[BZ - 726747 - Flipping between Inventory Summary and Platform Utilization repeatedly causes global uncaught exception.] reorganize slightly to avoid fast-click issues. move list grid field definition out of the async response processing and into onDraw.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java index b78a036..5bd705e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java @@ -92,6 +92,7 @@ public class PlatformSummaryPortlet extends LocatableListGrid implements Portlet setUseAllDataSourceFields(true); setAutoFitData(Autofit.VERTICAL); setOverflow(Overflow.AUTO); + setAutoFetchData(false);
setDataSource(new PlatformMetricDataSource(this)); setInitialCriteria(new Criteria(ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.PLATFORM @@ -113,12 +114,13 @@ public class PlatformSummaryPortlet extends LocatableListGrid implements Portlet
public void onSuccess(PageList<ResourceType> result) { setTypes(result); - buildUI(); + fetchData(new Criteria(ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.PLATFORM + .name())); } }); }
- private void buildUI() { + protected void onDraw() {
ListGridField nameField = new ListGridField(ResourceDataSourceField.NAME.propertyName(), MSG .common_title_name()); @@ -150,8 +152,6 @@ public class PlatformSummaryPortlet extends LocatableListGrid implements Portlet hideField(ResourceDataSourceField.PLUGIN.propertyName()); // its always the platform plugin, no need to show this hideField(ResourceDataSourceField.CATEGORY.propertyName()); // we only ever show platforms, no need to show this hideField(ResourceDataSourceField.AVAILABILITY.propertyName()); // the icon badging will indicate availability - - this.fetchData(new Criteria(ResourceDataSourceField.CATEGORY.propertyName(), ResourceCategory.PLATFORM.name())); }
protected void loadMetricsForResource(Resource resource, final Record record) {
commit 1abcfd00f4b01d085b2aa3c3c1a4dc67b75478aa Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 17 20:38:15 2011 -0400
fix category column width in Inventory Summary Report
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ResourceInstallReport.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ResourceInstallReport.java index 0eb0057..6988a94 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ResourceInstallReport.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ResourceInstallReport.java @@ -121,7 +121,7 @@ public class ResourceInstallReport extends LocatableVLayout implements Bookmarka
fieldTypeName.setWidth("35%"); fieldPlugin.setWidth("10%"); - fieldCategory.setWidth("25"); + fieldCategory.setWidth("55"); fieldVersion.setWidth("*"); fieldCount.setWidth("10%");
commit 3c707a6285961bffb7e35faa86e9ac4b12065ce3 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 02:26:50 2011 +0200
Healing the config-sync unit tests from a merge that changed a lot of assumptions made by them.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java index 6003e58..1359bee 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java @@ -50,7 +50,10 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList;
import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.sync.ExporterMessages; +import org.rhq.enterprise.server.sync.ExportReader; import org.rhq.enterprise.server.sync.ExportWriter; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.NoSingleEntity; @@ -58,6 +61,7 @@ import org.rhq.enterprise.server.sync.Synchronizer; import org.rhq.enterprise.server.sync.exporters.AbstractDelegatingExportingIterator; import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.ExportingIterator; +import org.rhq.enterprise.server.sync.importers.ExportedEntityMatcher; import org.rhq.enterprise.server.sync.importers.Importer; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; import org.rhq.test.JMockTest; @@ -84,9 +88,7 @@ public class ExportingInputStreamTest extends JMockTest { }
public void export(ExportWriter output) throws XMLStreamException { - output.writeStartElement("item"); output.writeCData(getCurrent().toString()); - output.writeEndElement(); }
public String getNotes() { @@ -111,6 +113,37 @@ public class ExportingInputStreamTest extends JMockTest { } }
+ private static class DummyImporter<T> implements Importer<NoSingleEntity, T> { + + @Override + public ConfigurationDefinition getImportConfigurationDefinition() { + return null; + } + + @Override + public void configure(Configuration importConfiguration) { + } + + @Override + public ExportedEntityMatcher<NoSingleEntity, T> getExportedEntityMatcher() { + return null; + } + + @Override + public void update(NoSingleEntity entity, T exportedEntity) throws Exception { + } + + @Override + public T unmarshallExportedEntity(ExportReader reader) throws XMLStreamException { + return null; + } + + @Override + public void finishImport() throws Exception { + } + + } + private static class ListToStringSynchronizer<T> implements Synchronizer<NoSingleEntity, T> { private List<T> list;
@@ -125,7 +158,7 @@ public class ExportingInputStreamTest extends JMockTest {
@Override public Importer<NoSingleEntity, T> getImporter() { - return null; + return new DummyImporter<T>(); }
@Override @@ -176,18 +209,24 @@ public class ExportingInputStreamTest extends JMockTest {
assertEquals(ExportingInputStream.CONFIGURATION_EXPORT_ELEMENT, root.getNodeName());
- assertEquals(root.getChildNodes().getLength(), 2, "Unexpected number of entities elements"); + NodeList entities = root.getElementsByTagName(ExportingInputStream.ENTITIES_EXPORT_ELEMENT); + assertEquals(entities.getLength(), 2, "Unexpected number of entities elements");
- Element export1 = (Element) root.getChildNodes().item(0); - Element export2 = (Element) root.getChildNodes().item(1); + Element export1 = (Element) entities.item(0); + Element export2 = (Element) entities.item(1);
assertEquals(export1.getAttribute("id"), StringListSynchronizer.class.getName()); assertEquals(export2.getAttribute("id"), IntegerListSynchronizer.class.getName());
String[] expectedNotes = new String[] {list1.toString(), list2.toString()};
- for(int i = 0; i < root.getChildNodes().getLength(); ++i) { - Element entitiesElement = (Element) root.getChildNodes().item(i); + for(int i = 0, elementIndex = 0; i < root.getChildNodes().getLength(); ++i) { + Node node = root.getChildNodes().item(i); + if (!(node instanceof Element)) { + continue; + } + + Element entitiesElement = (Element) node;
assertEquals(entitiesElement.getNodeName(), ExportingInputStream.ENTITIES_EXPORT_ELEMENT);
@@ -199,7 +238,7 @@ public class ExportingInputStreamTest extends JMockTest { assertNotNull(note, "Couldn't find exporter notes.");
String notesText = ((Element)note).getTextContent(); - assertEquals(notesText, expectedNotes[i], "Unexpected notes for entities."); + assertEquals(notesText, expectedNotes[elementIndex], "Unexpected notes for entities.");
NodeList entityElements = entitiesElement.getElementsByTagName(ExportingInputStream.ENTITY_EXPORT_ELEMENT);
@@ -222,6 +261,8 @@ public class ExportingInputStreamTest extends JMockTest {
assertEquals(notesText, ListToStringExporter.NOTE_PREFIX + dataText, "Unexpected discrepancy between data and notes in the export."); } + + ++elementIndex; } }
@@ -260,10 +301,9 @@ public class ExportingInputStreamTest extends JMockTest {
@Test(expectedExceptions = IOException.class) public void testExceptionHandling_ExportingIterator_next() throws Exception { - final ExportingIterator<?> iterator = context.mock(ExportingIterator.class); - + final ExportingIterator<?> iterator = context.mock(ExportingIterator.class); final Exporter<?, ?> exporter = context.mock(Exporter.class); - + final Importer<?, ?> importer = context.mock(Importer.class); final Synchronizer<?, ?> syncer = context.mock(Synchronizer.class);
context.checking(new Expectations() { @@ -290,6 +330,11 @@ public class ExportingInputStreamTest extends JMockTest {
allowing(syncer).getExporter(); will(returnValue(exporter)); + + allowing(syncer).getImporter(); + will(returnValue(importer)); + + allowing(importer).getImportConfigurationDefinition(); } });
@@ -308,6 +353,7 @@ public class ExportingInputStreamTest extends JMockTest { public void testExceptionHandling_ExportingIterator_export() throws Exception { final ExportingIterator<?> iterator = context.mock(ExportingIterator.class); final Exporter<?, ?> exporter = context.mock(Exporter.class); + final Importer<?, ?> importer = context.mock(Importer.class); final Synchronizer<?, ?> syncer = context.mock(Synchronizer.class);
context.checking(new Expectations() { @@ -334,6 +380,11 @@ public class ExportingInputStreamTest extends JMockTest {
allowing(syncer).getExporter(); will(returnValue(exporter)); + + allowing(syncer).getImporter(); + will(returnValue(importer)); + + allowing(importer).getImportConfigurationDefinition(); } });
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java index 819a5d9..7b50340 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java @@ -22,6 +22,7 @@ package org.rhq.enterprise.server.sync.test; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame;
+import java.util.Arrays; import java.util.Collections; import java.util.List;
@@ -60,32 +61,8 @@ public class MetricTemplateImporterTest extends JMockTest { private EntityManager em; private Query q; private MeasurementScheduleManagerLocal msm; - private List<MeasurementDefinition>[] consecutiveMatchingResults; - private boolean expectationsOnQueryParameters = true; + private List<MeasurementDefinition> defs;
- private class ReturnNextResultAction implements Action { - private int currentIndex = 0; - - @Override - public void describeTo(Description descr) { - descr.appendText("Returning the result of a faked query for matching measurement definitions: "); - if (currentIndex < consecutiveMatchingResults.length) { - descr.appendValue(consecutiveMatchingResults[currentIndex]); - } else { - descr.appendText("already returned all available results. Current index is ") - .appendText(Integer.toString(currentIndex)).appendText(" while only ") - .appendText(Integer.toString(consecutiveMatchingResults.length)) - .appendText(" results are available."); - } - } - - @Override - public Object invoke(Invocation invocation) throws Throwable { - return consecutiveMatchingResults[currentIndex++]; - } - - } - public TestPrerequisities(Mockery context) { em = context.mock(EntityManager.class); msm = context.mock(MeasurementScheduleManagerLocal.class); @@ -104,26 +81,17 @@ public class MetricTemplateImporterTest extends JMockTest { return msm; }
- public void setConsecutiveResultsOfMatchingQuery(List<MeasurementDefinition>... consecutiveResults) { - consecutiveMatchingResults = consecutiveResults; + public void setMeasurementDefinitions(List<MeasurementDefinition> defs) { + this.defs = defs; }
- public void setExpectationsOnQueryParameters(boolean value) { - expectationsOnQueryParameters = value; - } - + @SuppressWarnings("static-access") public void addExpectations(Expectations expectations) { - expectations.allowing(em).createNamedQuery( - expectations.with(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME)); + expectations.allowing(em).createQuery(expectations.with(expectations.any(String.class))); expectations.will(Expectations.returnValue(q)); - - if (expectationsOnQueryParameters) { - expectations.allowing(q).setParameter(expectations.with(Expectations.any(String.class)), - expectations.with(Expectations.any(Object.class))); - }
expectations.allowing(q).getResultList(); - expectations.will(new ReturnNextResultAction()); + expectations.will(Expectations.returnValue(defs)); } };
@@ -140,6 +108,11 @@ public class MetricTemplateImporterTest extends JMockTest { def.setDefaultOn(true); def.setDefaultInterval(1000);
+ //now we setup the prerequisites to return the faked results from the database + //for the non-matching template, we want the "database" to return no results + //while for the matching template, we want the "database" to return our own def. + prereqs.setMeasurementDefinitions(Collections.singletonList(def)); + //setup the expected behavior context.checking(new Expectations() { { @@ -158,14 +131,12 @@ public class MetricTemplateImporterTest extends JMockTest { new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager());
MetricTemplate nonMatching = new MetricTemplate(); + nonMatching.setResourceTypeName("asf"); + nonMatching.setResourceTypePlugin("asfd"); + nonMatching.setMetricName("asf"); + MetricTemplate matching = new MetricTemplate(def);
- //now we setup the prerequisites to return the faked results from the database - //for the non-matching template, we want the "database" to return no results - //while for the matching template, we want the "database" to return our own def. - prereqs.setConsecutiveResultsOfMatchingQuery(Collections.<MeasurementDefinition> emptyList(), - Collections.singletonList(def)); - importer.configure(null);
ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); @@ -199,6 +170,7 @@ public class MetricTemplateImporterTest extends JMockTest { defToDisable.setDefaultInterval(2000);
final TestPrerequisities prereqs = new TestPrerequisities(context); + prereqs.setMeasurementDefinitions(Arrays.asList(defToEnable, defToDisable));
context.checking(new Expectations() { { @@ -214,9 +186,6 @@ public class MetricTemplateImporterTest extends JMockTest { } });
- prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(defToEnable), - Collections.singletonList(defToDisable)); - MetricTemplateImporter importer = new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager());
@@ -249,6 +218,7 @@ public class MetricTemplateImporterTest extends JMockTest { def.setDefaultInterval(1000);
final TestPrerequisities prereqs = new TestPrerequisities(context); + prereqs.setMeasurementDefinitions(Collections.singletonList(def));
context.checking(new Expectations() { { @@ -261,8 +231,6 @@ public class MetricTemplateImporterTest extends JMockTest { } });
- prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(def)); - MetricTemplateImporter importer = new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager());
@@ -297,6 +265,7 @@ public class MetricTemplateImporterTest extends JMockTest { notUpdatedDef.setDefaultInterval(2000);
final TestPrerequisities prereqs = new TestPrerequisities(context); + prereqs.setMeasurementDefinitions(Arrays.asList(updatedDef, notUpdatedDef));
context.checking(new Expectations() { { @@ -311,9 +280,6 @@ public class MetricTemplateImporterTest extends JMockTest { } });
- prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(updatedDef), - Collections.singletonList(notUpdatedDef)); - MetricTemplateImporter importer = new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager());
@@ -374,19 +340,12 @@ public class MetricTemplateImporterTest extends JMockTest { perMinuteDef.setRawNumericType(NumericType.TRENDSUP);
final TestPrerequisities prereqs = new TestPrerequisities(context); - prereqs.setExpectationsOnQueryParameters(false); + prereqs.setMeasurementDefinitions(Arrays.asList(normalDef, perMinuteDef));
context.checking(new Expectations() { { - prereqs.setExpectationsOnQueryParameters(false); prereqs.addExpectations(this);
- exactly(2).of(prereqs.getQuery()).setParameter(with("name"), with(any(Object.class))); - exactly(2).of(prereqs.getQuery()).setParameter(with("resourceTypeName"), with(any(Object.class))); - exactly(2).of(prereqs.getQuery()).setParameter(with("resourceTypePlugin"), with(any(Object.class))); - oneOf(prereqs.getQuery()).setParameter(with("perMinute"), with(0)); - oneOf(prereqs.getQuery()).setParameter(with("perMinute"), with(1)); - MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager();
one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), @@ -396,9 +355,6 @@ public class MetricTemplateImporterTest extends JMockTest { } });
- prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(normalDef), - Collections.singletonList(perMinuteDef)); - MetricTemplateImporter importer = new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager());
commit 99d35f7b8466a77b86ba7ca5857004b3baea29f9 Merge: c2d5699 5c30887 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 00:38:01 2011 +0200
Merge branch 'feature/config-sync'
commit 5c30887d10e55eb54e6cbee87ed4b7b3c56b8850 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 17 03:35:49 2011 +0200
Import configuration now embedded in the export file. Other things included in this commit: - the export file is now indented for easier consumption by the humans - added documentation to the configuration instance schema
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java index 9d1d5f5..49dc6bf 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java @@ -52,8 +52,9 @@ import org.rhq.core.domain.sync.ExporterMessages; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.ExportingIterator; +import org.rhq.enterprise.server.sync.util.IndentingXMLStreamWriter; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; -import org.rhq.enterprise.server.xmlschema.ConfigurationInstanceUtil; +import org.rhq.enterprise.server.xmlschema.ConfigurationInstanceDescriptorUtil;
/** * Reading from this input stream produces the export file in a lazy (and therefore memory efficient) @@ -212,13 +213,14 @@ public class ExportingInputStream extends InputStream { try { XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); ofactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); - + try { out = exportOutput; if (zipOutput) { out = new GZIPOutputStream(out); } - wrt = ofactory.createXMLStreamWriter(out, "UTF-8"); + wrt = new IndentingXMLStreamWriter(ofactory.createXMLStreamWriter(out, "UTF-8")); + //wrt = ofactory.createXMLStreamWriter(out, "UTF-8"); } catch (XMLStreamException e) { LOG.error("Failed to create the XML stream writer to output the export file to.", e); return; @@ -255,7 +257,7 @@ public class ExportingInputStream extends InputStream { private void exportPrologue(XMLStreamWriter wrt) throws XMLStreamException { wrt.setDefaultNamespace(EXPORT_NAMESPACE); wrt.setPrefix(XMLConstants.DEFAULT_NS_PREFIX, EXPORT_NAMESPACE); - wrt.setPrefix("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + wrt.setPrefix("ci", ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE); wrt.setPrefix("c", CONFIGURATION_NAMESPACE);
NamespaceContext nsContext = new NamespaceContext() { @@ -264,7 +266,7 @@ public class ExportingInputStream extends InputStream { private final Map<String, String> PREFIXES = new HashMap<String, String>(); { PREFIXES.put(XMLConstants.DEFAULT_NS_PREFIX, EXPORT_NAMESPACE); - PREFIXES.put("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + PREFIXES.put("ci", ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE); PREFIXES.put("c", CONFIGURATION_NAMESPACE); }
@@ -309,10 +311,10 @@ public class ExportingInputStream extends InputStream { };
wrt.setNamespaceContext(nsContext); - + + wrt.writeStartDocument(); wrt.writeStartElement(EXPORT_NAMESPACE, CONFIGURATION_EXPORT_ELEMENT); - wrt.writeDefaultNamespace(EXPORT_NAMESPACE); - wrt.writeNamespace("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + wrt.writeNamespace("ci", ConfigurationInstanceDescriptorUtil.NS_CONFIGURATION_INSTANCE); wrt.writeNamespace("c", CONFIGURATION_NAMESPACE);
writeValidators(wrt); @@ -444,7 +446,7 @@ public class ExportingInputStream extends InputStream { if (def != null) { ConfigurationTemplate template = def.getDefaultTemplate(); if (template != null) { - ret = DefaultImportConfigurationDescriptor.create(ConfigurationInstanceUtil + ret = DefaultImportConfigurationDescriptor.create(ConfigurationInstanceDescriptorUtil .createConfigurationInstance(def, template.getConfiguration())); } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/util/IndentingXMLStreamWriter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/util/IndentingXMLStreamWriter.java new file mode 100644 index 0000000..5481482 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/util/IndentingXMLStreamWriter.java @@ -0,0 +1,393 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.util; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * + * + * @author Lukas Krejci + */ +public class IndentingXMLStreamWriter implements XMLStreamWriter { + + public static final String DEFAULT_INDENT_STRING = " "; + + private int depth; + private XMLStreamWriter wrapped; + private String indentString; + private boolean seenData; + + public IndentingXMLStreamWriter(XMLStreamWriter wrapped) { + this(wrapped, DEFAULT_INDENT_STRING); + } + + public IndentingXMLStreamWriter(XMLStreamWriter wrapped, String indentString) { + this.wrapped = wrapped; + this.indentString = indentString; + } + + private void onStartElement() throws XMLStreamException { + wrapped.writeCharacters("\n"); + writeIndent(); + ++depth; + seenData = false; + } + + private void onEndElement() throws XMLStreamException{ + --depth; + if (!seenData) { + wrapped.writeCharacters("\n"); + writeIndent(); + } + seenData = false; + } + + private void onEmptyElement() throws XMLStreamException { + seenData = false; + wrapped.writeCharacters("\n"); + writeIndent(); + } + + private void writeIndent() throws XMLStreamException { + for(int i = 0; i < depth; ++i) { + wrapped.writeCharacters(indentString); + } + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String) + */ + public void writeStartElement(String localName) throws XMLStreamException { + onStartElement(); + wrapped.writeStartElement(localName); + } + + /** + * @param namespaceURI + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String) + */ + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + onStartElement(); + wrapped.writeStartElement(namespaceURI, localName); + } + + /** + * @param prefix + * @param localName + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String, java.lang.String) + */ + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + onStartElement(); + wrapped.writeStartElement(prefix, localName, namespaceURI); + } + + /** + * @param namespaceURI + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String) + */ + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + onEmptyElement(); + wrapped.writeEmptyElement(namespaceURI, localName); + } + + /** + * @param prefix + * @param localName + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String, java.lang.String) + */ + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + onEmptyElement(); + wrapped.writeEmptyElement(prefix, localName, namespaceURI); + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String) + */ + public void writeEmptyElement(String localName) throws XMLStreamException { + onEmptyElement(); + wrapped.writeEmptyElement(localName); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEndElement() + */ + public void writeEndElement() throws XMLStreamException { + onEndElement(); + wrapped.writeEndElement(); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEndDocument() + */ + public void writeEndDocument() throws XMLStreamException { + while (depth > 0) { + writeEndElement(); + } + wrapped.writeEndDocument(); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#close() + */ + public void close() throws XMLStreamException { + wrapped.close(); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#flush() + */ + public void flush() throws XMLStreamException { + wrapped.flush(); + } + + /** + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String) + */ + public void writeAttribute(String localName, String value) throws XMLStreamException { + wrapped.writeAttribute(localName, value); + } + + /** + * @param prefix + * @param namespaceURI + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + public void writeAttribute(String prefix, String namespaceURI, String localName, String value) + throws XMLStreamException { + wrapped.writeAttribute(prefix, namespaceURI, localName, value); + } + + /** + * @param namespaceURI + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String) + */ + public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { + wrapped.writeAttribute(namespaceURI, localName, value); + } + + /** + * @param prefix + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeNamespace(java.lang.String, java.lang.String) + */ + public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { + wrapped.writeNamespace(prefix, namespaceURI); + } + + /** + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeDefaultNamespace(java.lang.String) + */ + public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { + wrapped.writeDefaultNamespace(namespaceURI); + } + + /** + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeComment(java.lang.String) + */ + public void writeComment(String data) throws XMLStreamException { + wrapped.writeComment(data); + } + + /** + * @param target + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String) + */ + public void writeProcessingInstruction(String target) throws XMLStreamException { + wrapped.writeProcessingInstruction(target); + } + + /** + * @param target + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String, java.lang.String) + */ + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + wrapped.writeProcessingInstruction(target, data); + } + + /** + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCData(java.lang.String) + */ + public void writeCData(String data) throws XMLStreamException { + wrapped.writeCData(data); + seenData = true; + } + + /** + * @param dtd + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeDTD(java.lang.String) + */ + public void writeDTD(String dtd) throws XMLStreamException { + writeIndent(); + wrapped.writeDTD(dtd); + } + + /** + * @param name + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEntityRef(java.lang.String) + */ + public void writeEntityRef(String name) throws XMLStreamException { + wrapped.writeEntityRef(name); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument() + */ + public void writeStartDocument() throws XMLStreamException { + wrapped.writeStartDocument(); + } + + /** + * @param version + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String) + */ + public void writeStartDocument(String version) throws XMLStreamException { + wrapped.writeStartDocument(version); + } + + /** + * @param encoding + * @param version + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String, java.lang.String) + */ + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + wrapped.writeStartDocument(encoding, version); + } + + /** + * @param text + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCharacters(java.lang.String) + */ + public void writeCharacters(String text) throws XMLStreamException { + wrapped.writeCharacters(text); + seenData = true; + } + + /** + * @param text + * @param start + * @param len + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCharacters(char[], int, int) + */ + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + wrapped.writeCharacters(text, start, len); + seenData = true; + } + + /** + * @param uri + * @return + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#getPrefix(java.lang.String) + */ + public String getPrefix(String uri) throws XMLStreamException { + return wrapped.getPrefix(uri); + } + + /** + * @param prefix + * @param uri + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setPrefix(java.lang.String, java.lang.String) + */ + public void setPrefix(String prefix, String uri) throws XMLStreamException { + wrapped.setPrefix(prefix, uri); + } + + /** + * @param uri + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setDefaultNamespace(java.lang.String) + */ + public void setDefaultNamespace(String uri) throws XMLStreamException { + wrapped.setDefaultNamespace(uri); + } + + /** + * @param context + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setNamespaceContext(javax.xml.namespace.NamespaceContext) + */ + public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { + wrapped.setNamespaceContext(context); + } + + /** + * @return + * @see javax.xml.stream.XMLStreamWriter#getNamespaceContext() + */ + public NamespaceContext getNamespaceContext() { + return wrapped.getNamespaceContext(); + } + + /** + * @param name + * @return + * @throws IllegalArgumentException + * @see javax.xml.stream.XMLStreamWriter#getProperty(java.lang.String) + */ + public Object getProperty(String name) throws IllegalArgumentException { + return wrapped.getProperty(name); + } +} diff --git a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtil.java b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtil.java new file mode 100644 index 0000000..b2f9ae3 --- /dev/null +++ b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtil.java @@ -0,0 +1,406 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.xmlschema; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.clientapi.descriptor.configuration.ConfigurationProperty; +import org.rhq.core.clientapi.descriptor.configuration.ListProperty; +import org.rhq.core.clientapi.descriptor.configuration.MapProperty; +import org.rhq.core.clientapi.descriptor.configuration.MeasurementUnitsDescriptor; +import org.rhq.core.clientapi.descriptor.configuration.Option; +import org.rhq.core.clientapi.descriptor.configuration.PropertyOptions; +import org.rhq.core.clientapi.descriptor.configuration.PropertyType; +import org.rhq.core.clientapi.descriptor.configuration.SimpleProperty; +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.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionEnumeration; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.core.domain.configuration.definition.PropertySimpleType; +import org.rhq.core.domain.measurement.MeasurementUnits; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueListDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueMapDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueSimpleDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ConfigurationInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ListPropertyInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.MapPropertyInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.PropertyValuesDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.SimplePropertyInstanceDescriptor; + +/** + * + * + * @author Lukas Krejci + */ +public class ConfigurationInstanceDescriptorUtil { + + public static final String NS_CONFIGURATION_INSTANCE = "urn:xmlns:rhq-configuration-instance"; + public static final String NS_CONFIGURATION = "urn:xmlns:rhq-configuration"; + + private static final Log LOG = LogFactory.getLog(ConfigurationInstanceDescriptorUtil.class); + + private ConfigurationInstanceDescriptorUtil() { + + } + + /** + * A configuration instance is a combination of a configuration definition and a concrete + * configuration instance with defined values. This is used during the config synchronization + * to output the default configuration of an importer directly in the export file so that the + * users have an easy way of modifying that configuration. + * + * @param definition + * @param configuration + * @return + */ + public static ConfigurationInstanceDescriptor createConfigurationInstance(ConfigurationDefinition definition, + Configuration configuration) { + + ConfigurationInstanceDescriptor ret = new ConfigurationInstanceDescriptor(); + + addAll(ret.getConfigurationProperty(), definition.getPropertyDefinitions(), configuration.getMap()); + + return ret; + } + + private static void addAll(List<JAXBElement<?>> descriptors, Map<String, PropertyDefinition> defs, Map<String, Property> props) { + for(Map.Entry<String, PropertyDefinition> e : defs.entrySet()) { + String propName = e.getKey(); + PropertyDefinition def = e.getValue(); + Property prop = props.get(propName); + + addSingle(descriptors, def, prop); + } + } + + private static void addSingle(List<JAXBElement<?>> descriptors, PropertyDefinition def, Property prop) { + ConfigurationProperty descriptor = null; + QName tagName = null; + + descriptor = createDescriptor(def, prop); + tagName = getTagName(descriptor); + + addToJAXBElementList(descriptors, Object.class, descriptor, tagName); + } + + private static ConfigurationProperty createDescriptor(PropertyDefinition def, Property prop) { + ConfigurationProperty ret = null; + + if (def instanceof PropertyDefinitionSimple) { + ret = createSimple((PropertyDefinitionSimple) def, (PropertySimple) prop); + } else if (def instanceof PropertyDefinitionList) { + ret = createList((PropertyDefinitionList) def, (PropertyList) prop); + } else if (def instanceof PropertyDefinitionMap) { + ret = createMap((PropertyDefinitionMap) def, (PropertyMap) prop); + } + + return ret; + } + + private static QName getTagName(ConfigurationProperty descriptor) { + if (descriptor instanceof SimplePropertyInstanceDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "simple-property"); + } else if (descriptor instanceof ListPropertyInstanceDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "list-property"); + } else if (descriptor instanceof MapPropertyInstanceDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "map-property"); + } else if (descriptor instanceof SimpleProperty) { + return new QName(NS_CONFIGURATION, "simple-property"); + } else if (descriptor instanceof ListProperty) { + return new QName(NS_CONFIGURATION, "list-property"); + } else if (descriptor instanceof MapProperty) { + return new QName(NS_CONFIGURATION, "map-property"); + } + + throw new IllegalArgumentException("Unknown descriptor type: " + descriptor.getClass()); + } + + private static QName getTagName(ComplexValueDescriptor value) { + if (value instanceof ComplexValueSimpleDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "simple-value"); + } else if (value instanceof ComplexValueListDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "list-value"); + } else if (value instanceof ComplexValueMapDescriptor) { + return new QName(NS_CONFIGURATION_INSTANCE, "map-value"); + } + + throw new IllegalArgumentException("Unknown value descriptor type: " + value.getClass()); + } + + private static SimplePropertyInstanceDescriptor createSimple(PropertyDefinitionSimple def, PropertySimple prop) { + SimplePropertyInstanceDescriptor ret = new SimplePropertyInstanceDescriptor(); + setCommonProps(ret, def, true); + + //these are prohibited, because they make no sense on the property instance + //ret.setDefaultValue(def.getDefaultValue()); + //ret.setInitialValue(prop.getStringValue()); + //ret.setActivationPolicy(pds.getActivationPolicy()); + ret.setPropertyOptions(convert(def.getEnumeratedValues())); + ret.setType(convert(def.getType())); + ret.setUnits(convert(def.getUnits())); + + if (prop != null) { + ret.setValue(prop.getStringValue()); + } + + return ret; + } + + private static ListPropertyInstanceDescriptor createList(PropertyDefinitionList def, PropertyList prop) { + ListPropertyInstanceDescriptor ret = new ListPropertyInstanceDescriptor(); + + setCommonProps(ret, def, true); + + ConfigurationProperty memberDef = convertDefinition(def.getMemberDefinition()); + ret.setConfigurationProperty(new JAXBElement<ConfigurationProperty>(getTagName(memberDef), ConfigurationProperty.class, memberDef)); + + if (prop != null) { + PropertyValuesDescriptor values = new PropertyValuesDescriptor(); + + ret.setValues(values); + + for(Property el : prop.getList()) { + ComplexValueDescriptor value = convertValue(el); + + //we don't need the property-name in lists, because the list has just a single member definition + value.setPropertyName(null); + + addToJAXBElementList(values.getComplexValue(), Object.class, value, getTagName(value)); + } + } + + return ret; + } + + private static MapPropertyInstanceDescriptor createMap(PropertyDefinitionMap def, PropertyMap prop) { + MapPropertyInstanceDescriptor ret = new MapPropertyInstanceDescriptor(); + + setCommonProps(ret, def, true); + + for(PropertyDefinition mem : def.getPropertyDefinitions().values()) { + ConfigurationProperty memDef = convertDefinition(mem); + + addToJAXBElementList(ret.getConfigurationProperty(), ConfigurationProperty.class, memDef, getTagName(memDef)); + } + + if (prop != null) { + PropertyValuesDescriptor values = new PropertyValuesDescriptor(); + + ret.setValues(values); + + for(Property el : prop.getMap().values()) { + ComplexValueDescriptor value = convertValue(el); + addToJAXBElementList(values.getComplexValue(), Object.class, value, getTagName(value)); + } + } + + return ret; + } + + private static void setCommonProps(ConfigurationProperty target, PropertyDefinition source, boolean creatingInstance) { + target.setName(source.getName()); + //let's always use long description + //target.setDescription(source.getDescription()); + target.setLongDescription(source.getDescription()); + target.setDisplayName(source.getDisplayName()); + + //these are prohibited on the instance because they make no sense there + if (!creatingInstance) { + target.setRequired(source.isRequired()); + target.setReadOnly(source.isReadOnly()); + target.setSummary(source.isSummary()); + } + } + + private static PropertyOptions convert(List<PropertyDefinitionEnumeration> options) { + if (options.isEmpty()) { + return null; + } + + PropertyOptions ret = new PropertyOptions(); + + ArrayList<PropertyDefinitionEnumeration> opts = new ArrayList<PropertyDefinitionEnumeration>(options); + + Collections.sort(opts, new Comparator<PropertyDefinitionEnumeration>() { + public int compare(PropertyDefinitionEnumeration o1, PropertyDefinitionEnumeration o2) { + return o1.getOrderIndex() - o2.getOrderIndex(); + } + }); + + for(PropertyDefinitionEnumeration option : opts) { + ret.getOption().add(convert(option)); + } + + return ret; + } + + private static Option convert(PropertyDefinitionEnumeration option) { + Option ret = new Option(); + ret.setName(option.getName()); + ret.setValue(option.getValue()); + return ret; + } + + private static PropertyType convert(PropertySimpleType type) { + if (type == null) { + return null; + } + + try { + return PropertyType.valueOf(type.name()); + } catch (IllegalArgumentException e) { + LOG.warn("Failed to convert a PropertySimpleType instance '" + type.name() + "' into a PropertyType.", e); + throw e; + } + } + + private static MeasurementUnitsDescriptor convert(MeasurementUnits unit) { + //XXX there actually are some differences in the available values for these + //two enums: + //Missing in MeasurementUnitsDescriptor: + //MeasurementUnits.JIFFY, MeasurementUnits.PETA_BYTES + + if (unit == null) { + return null; + } + + String value = unit.name(); + + try { + return MeasurementUnitsDescriptor.valueOf(value); + } catch (IllegalArgumentException e) { + LOG.warn("Failed to convert a MeasurementUnits instance '" + unit.getName() + "' into a MeasurementUnitsDescriptor.", e); + throw e; + } + } + + private static ConfigurationProperty convertDefinition(PropertyDefinition def) { + if (def instanceof PropertyDefinitionSimple) { + return convertSimple((PropertyDefinitionSimple) def); + } else if (def instanceof PropertyDefinitionList) { + return convertList((PropertyDefinitionList) def); + } else if (def instanceof PropertyDefinitionMap) { + return convertMap((PropertyDefinitionMap) def); + } + + throw new IllegalArgumentException("Unsupported property definition type: " + def.getClass()); + } + + private static SimpleProperty convertSimple(PropertyDefinitionSimple def) { + SimpleProperty ret = new SimpleProperty(); + setCommonProps(ret, def, false); + ret.setDefaultValue(def.getDefaultValue()); + ret.setPropertyOptions(convert(def.getEnumeratedValues())); + ret.setType(convert(def.getType())); + ret.setUnits(convert(def.getUnits())); + + return ret; + } + + private static ListProperty convertList(PropertyDefinitionList def) { + ListProperty ret = new ListProperty(); + setCommonProps(ret, def, false); + ConfigurationProperty memberDefinition = convertDefinition(def.getMemberDefinition()); + ret.setConfigurationProperty(new JAXBElement<ConfigurationProperty>(getTagName(memberDefinition), ConfigurationProperty.class, memberDefinition)); + + return ret; + } + + private static MapProperty convertMap(PropertyDefinitionMap def) { + MapProperty ret = new MapProperty(); + setCommonProps(ret, def, false); + + List<JAXBElement<? extends ConfigurationProperty>> elements = ret.getConfigurationProperty(); + for(PropertyDefinition el : def.getPropertyDefinitions().values()) { + ConfigurationProperty prop = convertDefinition(el); + QName tagName = getTagName(prop); + addToJAXBElementList(elements, ConfigurationProperty.class, prop, tagName); + } + + return ret; + } + + private static ComplexValueDescriptor convertValue(Property prop) { + if (prop instanceof PropertySimple) { + return convertSimpleValue((PropertySimple) prop); + } else if (prop instanceof PropertyList) { + return convertListValue((PropertyList) prop); + } else if (prop instanceof PropertyMap) { + return convertMapValue((PropertyMap) prop); + } + + throw new IllegalArgumentException("Unsupported property type to convert to a value descriptor: " + prop.getClass()); + } + + private static ComplexValueSimpleDescriptor convertSimpleValue(PropertySimple prop) { + ComplexValueSimpleDescriptor ret = new ComplexValueSimpleDescriptor(); + ret.setPropertyName(prop.getName()); + ret.setValue(prop.getStringValue()); + + return ret; + } + + private static ComplexValueListDescriptor convertListValue(PropertyList prop) { + ComplexValueListDescriptor ret = new ComplexValueListDescriptor(); + ret.setPropertyName(prop.getName()); + + for(Property el : prop.getList()) { + ComplexValueDescriptor value = convertValue(el); + addToJAXBElementList(ret.getComplexValue(), Object.class, value, getTagName(value)); + } + + return ret; + } + + private static ComplexValueMapDescriptor convertMapValue(PropertyMap prop) { + ComplexValueMapDescriptor ret = new ComplexValueMapDescriptor(); + ret.setPropertyName(prop.getName()); + + for (Property el : prop.getMap().values()) { + ComplexValueDescriptor value = convertValue(el); + addToJAXBElementList(ret.getComplexValue(), Object.class, value, getTagName(value)); + } + + return ret; + } + + private static <T> void addToJAXBElementList(List<JAXBElement<? extends T>> list, Class<T> baseClass, T property, QName tagName) { + JAXBElement<? extends T> el = new JAXBElement<T>(tagName, baseClass, property); + list.add(el); + } +} diff --git a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java deleted file mode 100644 index b383bbd..0000000 --- a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.enterprise.server.xmlschema; - -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; -import javax.xml.namespace.QName; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.Property; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; -import org.rhq.core.domain.configuration.definition.PropertyDefinition; -import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; -import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; -import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; -import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ConfigurationInstanceDescriptor; -import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.SimplePropertyInstanceDescriptor; - -/** - * - * - * @author Lukas Krejci - */ -public class ConfigurationInstanceUtil { - - public static final String NS_CONFIGURATION_INSTANCE = "urn:xmlns:rhq-configuration-instance"; - - private ConfigurationInstanceUtil() { - - } - - /** - * A configuration instance is a combination of a configuration definition and a concrete - * configuration instance with defined values. This is used during the config synchronization - * to output the default configuration of an importer directly in the export file so that the - * users have an easy way of modifying that configuration. - * - * @param definition - * @param configuration - * @return - */ - public static ConfigurationInstanceDescriptor createConfigurationInstance(ConfigurationDefinition definition, - Configuration configuration) { - - ConfigurationInstanceDescriptor ret = new ConfigurationInstanceDescriptor(); - - addAll(ret.getConfigurationProperty(), definition.getPropertyDefinitions(), configuration.getMap()); - - return ret; - } - - private static void addAll(List<JAXBElement<?>> descriptors, Map<String, PropertyDefinition> defs, Map<String, Property> props) { - for(Map.Entry<String, PropertyDefinition> e : defs.entrySet()) { - String propName = e.getKey(); - PropertyDefinition def = e.getValue(); - Property prop = props.get(propName); - - addSingle(descriptors, def, prop); - } - } - - private static void addSingle(List<JAXBElement<?>> descriptors, PropertyDefinition def, Property prop) { - Object descriptor = null; - String tagName = null; - - if (def instanceof PropertyDefinitionSimple) { - descriptor = createSimple(def, prop); - tagName = "simple-property"; - } else if (def instanceof PropertyDefinitionList) { - //TODO - } else if (def instanceof PropertyDefinitionMap) { - //TODO - } - - addToJAXBElementList(descriptors, Object.class, descriptor, new QName(NS_CONFIGURATION_INSTANCE, tagName)); - } - - private static SimplePropertyInstanceDescriptor createSimple(PropertyDefinition def, Property prop) { - SimplePropertyInstanceDescriptor ret = new SimplePropertyInstanceDescriptor(); - PropertyDefinitionSimple pds = (PropertyDefinitionSimple) def; - ret.setName(pds.getName()); - ret.setDescription(pds.getDescription()); - ret.setLongDescription(pds.getDescription()); - ret.setDisplayName(pds.getDisplayName()); - - //TODO add rest of the properties - - ret.setValue(((PropertySimple)prop).getStringValue()); - - return ret; - } - - - private static <T> void addToJAXBElementList(List<JAXBElement<? extends T>> list, Class<T> baseClass, T property, QName tagName) { - JAXBElement<? extends T> el = new JAXBElement<T>(tagName, baseClass, property.getClass(), property); - list.add(el); - } -} diff --git a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd index d94b696..97568b5 100644 --- a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd +++ b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd @@ -42,7 +42,7 @@ xs:sequence <xs:element type="ci:Configuration" name="default-configuration" minOccurs="0" maxOccurs="1"/> <xs:element minOccurs="0" maxOccurs="unbounded" type="ce:EntityExport" name="entity" /> - <xs:element type="xs:string" name="notes" /> + <xs:element type="xs:string" name="notes" minOccurs="0" maxOccurs="1"/> </xs:sequence> <xs:attribute name="id" type="xs:ID"> xs:annotation diff --git a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd index f05585d..9b4afab 100644 --- a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd +++ b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd @@ -18,16 +18,18 @@ </xs:appinfo> </xs:annotation>
- <xs:import namespace="urn:xmlns:rhq-configuration" - schemaLocation="rhq-configuration.xsd" /> + <xs:import namespace="urn:xmlns:rhq-configuration" schemaLocation="rhq-configuration.xsd"/>
- <xs:element name="configuration" type="ci:Configuration" /> + <xs:element name="configuration" type="ci:Configuration"> + xs:annotation + xs:documentationRepresents the configuration instance. The configuration instance specifies both the expected format of the configuration and the concrete values that conform to that format.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="Configuration"> xs:annotation xs:appinfo <jaxb:class name="ConfigurationInstanceDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:sequence <xs:element ref="ci:configuration-property" @@ -37,41 +39,56 @@
<xs:element name="configuration-property" abstract="true" />
- <xs:element name="simple-property" type="ci:SimpleProperty" - substitutionGroup="ci:configuration-property" /> - <xs:complexType name="SimpleProperty"> + <xs:element name="simple-property" + substitutionGroup="ci:configuration-property"> xs:annotation - xs:appinfo - <jaxb:class name="SimplePropertyInstanceDescriptor" /> - </xs:appinfo> - xs:documentation</xs:documentation> + xs:documentationThe simple property is defined by its name and value.</xs:documentation> </xs:annotation> - xs:complexContent - <xs:extension base="config:simpleProperty"> - <xs:attribute name="value" type="xs:string" /> - <xs:attribute name="default" use="prohibited" /> - <xs:attribute name="defaultValue" use="prohibited" /> - <xs:attribute name="summary" use="prohibited" /> - <xs:attribute name="readOnly" use="prohibited" /> - <xs:attribute name="activationPolicy" use="prohibited" /> - </xs:extension> - </xs:complexContent> - </xs:complexType> + xs:complexType + xs:annotation + xs:appinfo + <jaxb:class name="SimplePropertyInstanceDescriptor" /> + </xs:appinfo> + </xs:annotation> + xs:complexContent + <xs:extension base="config:simpleProperty"> + <xs:attribute name="value" type="xs:string"> + xs:annotation + xs:documentationThe value of the property represented as a string. The value is interpreted according to the property type.</xs:documentation> + </xs:annotation> + </xs:attribute> + <xs:attribute name="default" use="prohibited" /> + <xs:attribute name="defaultValue" use="prohibited" /> + <xs:attribute name="summary" use="prohibited" /> + <xs:attribute name="readOnly" use="prohibited" /> + <xs:attribute name="activationPolicy" use="prohibited" /> + </xs:extension> + </xs:complexContent> + </xs:complexType> + + </xs:element>
<xs:element name="list-property" type="ci:ListProperty" - substitutionGroup="ci:configuration-property" /> + substitutionGroup="ci:configuration-property"> + xs:annotation + xs:documentationThe list property contains the definition of the format of the list members. Additionally, the "values" tag contains the list of values in the specified format.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="ListProperty"> xs:annotation xs:appinfo <jaxb:class name="ListPropertyInstanceDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:complexContent <xs:extension base="config:listProperty"> xs:sequence <xs:element name="values" type="ci:PropertyValues" - minOccurs="0" maxOccurs="1" /> + minOccurs="0" maxOccurs="1"> + xs:annotation + xs:documentationThe list of values that correspond to the list definition. The individual values are not required to specify the "property-name" attribute because it is implied to be the same as the name of the member property definition of this list.</xs:documentation> + </xs:annotation> + </xs:element> </xs:sequence> <xs:attribute name="default" use="prohibited" /> <xs:attribute name="defaultValue" use="prohibited" /> @@ -83,19 +100,26 @@ </xs:complexType>
<xs:element name="map-property" type="ci:MapProperty" - substitutionGroup="ci:configuration-property" /> + substitutionGroup="ci:configuration-property"> + xs:annotation + xs:documentationSpecifies the definition of the properties. The values of the properties are contained in the "values" tag.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="MapProperty"> xs:annotation xs:appinfo <jaxb:class name="MapPropertyInstanceDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:complexContent <xs:extension base="config:mapProperty"> xs:sequence <xs:element name="values" type="ci:PropertyValues" - minOccurs="0" maxOccurs="1" /> + minOccurs="0" maxOccurs="1"> + xs:annotation + xs:documentationThe individual values in this map are required to specify the "property-name" attribute so they can be linked to the member property definition.</xs:documentation> + </xs:annotation> + </xs:element> </xs:sequence> <xs:attribute name="default" use="prohibited" /> <xs:attribute name="defaultValue" use="prohibited" /> @@ -106,16 +130,23 @@ </xs:complexContent> </xs:complexType>
- <xs:element name="complex-value" abstract="true" /> + <xs:element name="complex-value" abstract="true"> + xs:annotation + xs:documentationSpecifies the value of a property.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="ComplexValue"> xs:annotation xs:appinfo <jaxb:class name="ComplexValueDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> <xs:attribute name="property-name" type="xs:string" - use="required" /> + use="optional"> + xs:annotation + xs:documentationThe name of the property that defines the format of this value. This attribute is not mandatory if the value specifies a member in a list. It is required when specifying individual values of the members of a map.</xs:documentation> + </xs:annotation> + </xs:attribute> </xs:complexType>
<xs:complexType name="PropertyValues"> @@ -123,7 +154,7 @@ xs:appinfo <jaxb:class name="PropertyValuesDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> + xs:documentationThis lists the individual values of the property containing this tag.</xs:documentation> </xs:annotation> xs:sequence <xs:element ref="ci:complex-value" minOccurs="0" @@ -132,27 +163,39 @@ </xs:complexType>
<xs:element name="simple-value" type="ci:ComplexValueSimple" - substitutionGroup="ci:complex-value" /> + substitutionGroup="ci:complex-value"> + xs:annotation + xs:documentationThis specifies the value of a simple property.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="ComplexValueSimple"> xs:annotation xs:appinfo <jaxb:class name="ComplexValueSimpleDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:complexContent - <xs:restriction base="ci:ComplexValue" /> + <xs:extension base="ci:ComplexValue"> + <xs:attribute name="value" type="xs:string"> + xs:annotation + xs:documentationThe value of the property represented as a string. The string is interpreted according to the format of the property.</xs:documentation> + </xs:annotation> + </xs:attribute> + </xs:extension> </xs:complexContent> </xs:complexType>
<xs:element name="list-value" type="ci:ComplexValueList" - substitutionGroup="ci:complex-value" /> + substitutionGroup="ci:complex-value"> + xs:annotation + xs:documentationThis element represents a list value (i.e. a value that is in itself a list). This is different from defining a list and its values because the format of the list has already been defined in the parent element. The child values represent the individual elements of the list.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="ComplexValueList"> xs:annotation xs:appinfo <jaxb:class name="ComplexValueListDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:complexContent <xs:extension base="ci:ComplexValue"> @@ -165,13 +208,16 @@ </xs:complexType>
<xs:element name="map-value" type="ci:ComplexValueMap" - substitutionGroup="ci:complex-value" /> + substitutionGroup="ci:complex-value"> + xs:annotation + xs:documentationThis elements represents a map value (i.e. a value that is in itself a map). This is different from defining a map and its values because the format of the map has already been defined in the parent element. The child values reprenset the individual elements of the map.</xs:documentation> + </xs:annotation> + </xs:element> <xs:complexType name="ComplexValueMap"> xs:annotation xs:appinfo <jaxb:class name="ComplexValueMapDescriptor" /> </xs:appinfo> - xs:documentation</xs:documentation> </xs:annotation> xs:complexContent <xs:extension base="ci:ComplexValue"> diff --git a/modules/enterprise/server/xml-schemas/src/test/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtilTest.java b/modules/enterprise/server/xml-schemas/src/test/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtilTest.java new file mode 100644 index 0000000..2105e7f --- /dev/null +++ b/modules/enterprise/server/xml-schemas/src/test/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceDescriptorUtilTest.java @@ -0,0 +1,229 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.xmlschema; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlRootElement; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.testng.annotations.Test; + +import org.rhq.core.clientapi.descriptor.configuration.MapProperty; +import org.rhq.core.clientapi.descriptor.configuration.SimpleProperty; +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.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.core.domain.configuration.definition.PropertySimpleType; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueMapDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ComplexValueSimpleDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ConfigurationInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ListPropertyInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.SimplePropertyInstanceDescriptor; + +/** + * + * + * @author Lukas Krejci + */ +@Test +public class ConfigurationInstanceDescriptorUtilTest { + private static final Log LOG = LogFactory.getLog(ConfigurationInstanceDescriptorUtilTest.class); + + @XmlRootElement + public static final class StandaloneConfigurationInstance extends ConfigurationInstanceDescriptor { + public static StandaloneConfigurationInstance createFrom(ConfigurationInstanceDescriptor instance) { + StandaloneConfigurationInstance ret = new StandaloneConfigurationInstance(); + ret.configurationProperty = new ArrayList<JAXBElement<?>>(instance.getConfigurationProperty()); + + return ret; + } + } + + private static final Marshaller CONFIGURATION_INSTANCE_MARSHALLER; + static { + try { + JAXBContext context = JAXBContext.newInstance(StandaloneConfigurationInstance.class); + CONFIGURATION_INSTANCE_MARSHALLER = context.createMarshaller(); + } catch (Exception e) { + throw new IllegalStateException("Failed to initialize the configuration instance marshaller.", e); + } + } + + public void testSimplePropertyConversion() throws Exception { + ConfigurationDefinition def = new ConfigurationDefinition(null, null); + PropertyDefinitionSimple propDef = + new PropertyDefinitionSimple("prop", "prop descr", true, PropertySimpleType.BOOLEAN); + def.put(propDef); + + Configuration config = new Configuration(); + PropertySimple prop = new PropertySimple("prop", "true"); + config.put(prop); + + ConfigurationInstanceDescriptor instance = + ConfigurationInstanceDescriptorUtil.createConfigurationInstance(def, config); + + assertEquals(instance.getConfigurationProperty().size(), 1, + "Unexpected number of properties in the config instance."); + + SimplePropertyInstanceDescriptor propInstance = + (SimplePropertyInstanceDescriptor) instance.getConfigurationProperty().get(0).getValue(); + + assertEquals(propInstance.getName(), "prop", "Unexpected property instance name"); + assertEquals(propInstance.getValue(), "true", "Unexpected property instance value"); + assertEquals(propInstance.getLongDescription(), "prop descr", "Unexpected property instance description"); + assertTrue(propInstance.isRequired(), "Unexpected property instance required flag"); + + logInstance("Simple", instance); + } + + public void testListOfSimplesPropertyConversion() throws Exception { + ConfigurationDefinition def = new ConfigurationDefinition(null, null); + PropertyDefinitionList listDef = + new PropertyDefinitionList("list", "list descr", true, new PropertyDefinitionSimple("prop", "prop descr", + false, PropertySimpleType.FLOAT)); + def.put(listDef); + + Configuration config = new Configuration(); + PropertyList list = + new PropertyList("list", new PropertySimple("prop", "value1"), new PropertySimple("prop", "value2")); + config.put(list); + + ConfigurationInstanceDescriptor instance = + ConfigurationInstanceDescriptorUtil.createConfigurationInstance(def, config); + + assertEquals(instance.getConfigurationProperty().size(), 1, + "Unexpected number of properties in configuration instance."); + + ListPropertyInstanceDescriptor listInstance = + (ListPropertyInstanceDescriptor) instance.getConfigurationProperty().get(0).getValue(); + + assertEquals(listInstance.getName(), "list", "Unexpected list instance name"); + assertEquals(listInstance.getLongDescription(), "list descr", "Unexpected list instance description"); + assertTrue(listInstance.isRequired(), "Unexpected list instance required flag"); + + SimpleProperty propDef = (SimpleProperty) listInstance.getConfigurationProperty().getValue(); + assertEquals(propDef.getName(), "prop", "Unexpected simple instance name"); + assertEquals(propDef.getLongDescription(), "prop descr", "Unexpected simple instance description"); + assertTrue(!propDef.isRequired(), "Unexpected simple instance required flag"); + + assertEquals(listInstance.getValues().getComplexValue().size(), 2, "Unexpected number of list values"); + + ComplexValueSimpleDescriptor value1 = + (ComplexValueSimpleDescriptor) listInstance.getValues().getComplexValue().get(0).getValue(); + ComplexValueSimpleDescriptor value2 = + (ComplexValueSimpleDescriptor) listInstance.getValues().getComplexValue().get(1).getValue(); + + assertEquals(value1.getValue(), "value1"); + assertEquals(value2.getValue(), "value2"); + + logInstance("List of simples", instance); + } + + public void testListOfMapsPropertyConversion() throws Exception { + ConfigurationDefinition def = new ConfigurationDefinition(null, null); + PropertyDefinitionList listDef = + new PropertyDefinitionList("list", "list descr", true, new PropertyDefinitionMap("map", "map descr", true, + new PropertyDefinitionSimple("prop1", "prop1 descr", true, PropertySimpleType.BOOLEAN), + new PropertyDefinitionSimple("prop2", "prop2 descr", false, PropertySimpleType.PASSWORD))); + def.put(listDef); + + Configuration config = new Configuration(); + PropertyList list = + new PropertyList("list", new PropertyMap("map", new PropertySimple("prop1", "value1"), new PropertySimple( + "prop2", "value1")), new PropertyMap("map", new PropertySimple("prop1", "value2"), new PropertySimple( + "prop2", "value2"))); + config.put(list); + + ConfigurationInstanceDescriptor instance = + ConfigurationInstanceDescriptorUtil.createConfigurationInstance(def, config); + + assertEquals(instance.getConfigurationProperty().size(), 1, + "Unexpected number of properties in configuration instance."); + + ListPropertyInstanceDescriptor listInstance = + (ListPropertyInstanceDescriptor) instance.getConfigurationProperty().get(0).getValue(); + + assertEquals(listInstance.getName(), "list", "Unexpected list instance name"); + assertEquals(listInstance.getLongDescription(), "list descr", "Unexpected list instance description"); + assertTrue(listInstance.isRequired(), "Unexpected list instance required flag"); + + MapProperty propDef = (MapProperty) listInstance.getConfigurationProperty().getValue(); + assertEquals(propDef.getName(), "map", "Unexpected simple instance name"); + assertEquals(propDef.getLongDescription(), "map descr", "Unexpected simple instance description"); + assertTrue(propDef.isRequired(), "Unexpected simple instance required flag"); + + assertEquals(listInstance.getValues().getComplexValue().size(), 2, "Unexpected number of list values"); + + ComplexValueMapDescriptor map1 = + (ComplexValueMapDescriptor) listInstance.getValues().getComplexValue().get(0).getValue(); + ComplexValueMapDescriptor map2 = + (ComplexValueMapDescriptor) listInstance.getValues().getComplexValue().get(1).getValue(); + + assertEquals(map1.getComplexValue().size(), 2, "Unexpected number of map elements in the first map value."); + assertEquals(map2.getComplexValue().size(), 2, "Unexpected number of map elements in the second map value."); + + ComplexValueSimpleDescriptor value11 = (ComplexValueSimpleDescriptor) map1.getComplexValue().get(0).getValue(); + ComplexValueSimpleDescriptor value12 = (ComplexValueSimpleDescriptor) map1.getComplexValue().get(1).getValue(); + ComplexValueSimpleDescriptor value21 = (ComplexValueSimpleDescriptor) map2.getComplexValue().get(0).getValue(); + ComplexValueSimpleDescriptor value22 = (ComplexValueSimpleDescriptor) map2.getComplexValue().get(1).getValue(); + + assertEquals(value11.getPropertyName(), "prop1", "Unexpected name of the first property in the first map value"); + assertEquals(value11.getValue(), "value1", "Unexpected value of the first property in the first map value"); + assertEquals(value12.getPropertyName(), "prop2", "Unexpected name of the second property in the first map value"); + assertEquals(value12.getValue(), "value1", "Unexpected value of the second property in the first map value"); + assertEquals(value21.getPropertyName(), "prop1", "Unexpected name of the first property in the second map value"); + assertEquals(value21.getValue(), "value2", "Unexpected value of the first property in the second map value"); + assertEquals(value22.getPropertyName(), "prop2", "Unexpected name of the second property in the second map value"); + assertEquals(value22.getValue(), "value2", "Unexpected value of the second property in the second map value"); + + logInstance("List of maps", instance); + } + + public void testMapOfComplexPropertyConversion() { + //TODO implement + } + + private static void logInstance(String message, ConfigurationInstanceDescriptor instance) throws JAXBException, + IOException { + StringWriter wrt = new StringWriter(); + try { + CONFIGURATION_INSTANCE_MARSHALLER.marshal(StandaloneConfigurationInstance.createFrom(instance), wrt); + LOG.debug(message + "\n" + wrt.toString()); + } finally { + wrt.close(); + } + } +}
commit d85f3f4dbd8cb1a373c935323228761af1d1cb0b Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 17 03:33:29 2011 +0200
removed a wrong assertion and renamed some variables in the system settings exporter test.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java index 3798e55..2f8aa26 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java @@ -119,13 +119,11 @@ public class SystemSettingsExporterTest extends JMockTest {
assertEquals(m.getAttribute("referencedEntityId"), "0", "Unexpected referencedEntityId value");
- assertEquals(m.getChildNodes().getLength(), 1, "Unexpected number of properties in the system settings."); + NodeList entries = m.getElementsByTagName("entry");
- NodeList baseURLs = m.getElementsByTagName("entry"); + assertEquals(entries.getLength(), 1, "Unexpected number of entry elements in the system settings export.");
- assertEquals(baseURLs.getLength(), 1, "Unexpected number of baseURL elements in the system settings export."); - - Element baseURL = (Element) baseURLs.item(0); + Element baseURL = (Element) entries.item(0);
assertEquals(baseURL.getAttribute("key"), "BaseURL"); assertEquals(baseURL.getTextContent(), "herethereandeverywhere", "Unexpected value of baseURL");
commit ace66b3972dcbbe0b2cf155f4f04aa2cf2b5da46 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 17 03:32:20 2011 +0200
MetricTemplateSynchronizer wasn't testable.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java index 847fe2f..913c981 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java @@ -19,7 +19,6 @@
package org.rhq.enterprise.server.sync;
-import java.util.Collections; import java.util.HashSet; import java.util.Set;
@@ -29,6 +28,7 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.sync.entity.MetricTemplate; import org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerLocal; +import org.rhq.enterprise.server.measurement.MeasurementScheduleManagerLocal; import org.rhq.enterprise.server.resource.metadata.PluginManagerLocal; import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.MetricTemplateExporter; @@ -49,29 +49,32 @@ public class MetricTemplateSynchronizer implements Synchronizer<MeasurementDefin private Subject subject; private EntityManager entityManager; private MeasurementDefinitionManagerLocal measurementDefinitionManager; + private MeasurementScheduleManagerLocal measurementScheduleManager; private PluginManagerLocal pluginManager; - + public MetricTemplateSynchronizer() { - this(LookupUtil.getMeasurementDefinitionManager(), LookupUtil.getPluginManager()); + this(LookupUtil.getMeasurementDefinitionManager(), LookupUtil.getMeasurementScheduleManager(), LookupUtil.getPluginManager()); } - - public MetricTemplateSynchronizer(MeasurementDefinitionManagerLocal measurementDefinitionManager, PluginManagerLocal pluginManager) { + + public MetricTemplateSynchronizer(MeasurementDefinitionManagerLocal measurementDefinitionManager, + MeasurementScheduleManagerLocal measurementScheduleManager, PluginManagerLocal pluginManager) { this.measurementDefinitionManager = measurementDefinitionManager; + this.measurementScheduleManager = measurementScheduleManager; this.pluginManager = pluginManager; } - + @Override public void initialize(Subject subject, EntityManager entityManager) { this.subject = subject; this.entityManager = entityManager; } - + public Exporter<MeasurementDefinition, MetricTemplate> getExporter() { - return new MetricTemplateExporter(subject, measurementDefinitionManager); + return new MetricTemplateExporter(subject, measurementDefinitionManager); }
public Importer<MeasurementDefinition, MetricTemplate> getImporter() { - return new MetricTemplateImporter(subject, entityManager); + return new MetricTemplateImporter(subject, entityManager, measurementScheduleManager); }
public Set<ConsistencyValidator> getRequiredValidators() { diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java index a11a42c..70819af 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java @@ -22,8 +22,10 @@ package org.rhq.enterprise.server.sync.test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
+import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; @@ -54,6 +56,7 @@ import org.rhq.core.domain.sync.ExporterMessages; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerLocal; +import org.rhq.enterprise.server.measurement.MeasurementScheduleManagerLocal; import org.rhq.enterprise.server.resource.metadata.PluginManagerLocal; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.MetricTemplateSynchronizer; @@ -74,6 +77,7 @@ public class MetricTemplateExporterTest extends JMockTest { public void testCanExport() throws Exception { final MeasurementDefinitionManagerLocal measurementDefinitionManager = context.mock(MeasurementDefinitionManagerLocal.class); final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); + final MeasurementScheduleManagerLocal measurementScheduleManager = context.mock(MeasurementScheduleManagerLocal.class); context.checking(new Expectations() { { allowing(measurementDefinitionManager).findMeasurementDefinitionsByCriteria(with(any(Subject.class)), with(any(MeasurementDefinitionCriteria.class))); @@ -84,7 +88,7 @@ public class MetricTemplateExporterTest extends JMockTest { } });
- MetricTemplateSynchronizer exporter = new MetricTemplateSynchronizer(measurementDefinitionManager, pluginManager); + MetricTemplateSynchronizer exporter = new MetricTemplateSynchronizer(measurementDefinitionManager, measurementScheduleManager, pluginManager);
Set<Synchronizer<?, ?>> exporters = new HashSet<Synchronizer<?, ?>>(); exporters.add(exporter);
commit 7f7adf397febb3b9b38137e68811353451a250fa Author: Lukas Krejci lkrejci@redhat.com Date: Mon Aug 8 17:20:53 2011 +0200
Experimental unfinished support for persisting the default configuration in the export file.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/DefaultImportConfigurationDescriptor.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/DefaultImportConfigurationDescriptor.java new file mode 100644 index 0000000..6b13150 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/DefaultImportConfigurationDescriptor.java @@ -0,0 +1,43 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync; + +import javax.xml.bind.annotation.XmlRootElement; + +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ConfigurationInstanceDescriptor; + +/** + * + * + * @author Lukas Krejci + */ +@XmlRootElement(name = "default-configuration", namespace = ExportingInputStream.EXPORT_NAMESPACE) +public class DefaultImportConfigurationDescriptor extends ConfigurationInstanceDescriptor { + + public DefaultImportConfigurationDescriptor() { + + } + + public static DefaultImportConfigurationDescriptor create(ConfigurationInstanceDescriptor descriptor) { + DefaultImportConfigurationDescriptor ret = new DefaultImportConfigurationDescriptor(); + ret.configurationProperty = descriptor.getConfigurationProperty(); + return ret; + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java index 9399b62..9d1d5f5 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java @@ -26,11 +26,19 @@ import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.zip.GZIPOutputStream;
+import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -38,11 +46,14 @@ import javax.xml.stream.XMLStreamWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.sync.ExporterMessages; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.ExportingIterator; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; +import org.rhq.enterprise.server.xmlschema.ConfigurationInstanceUtil;
/** * Reading from this input stream produces the export file in a lazy (and therefore memory efficient) @@ -54,6 +65,9 @@ public class ExportingInputStream extends InputStream {
private static final Log LOG = LogFactory.getLog(ExportingInputStream.class);
+ public static final String CONFIGURATION_NAMESPACE = "urn:xmlns:rhq-configuration"; + public static final String EXPORT_NAMESPACE = "urn:xmlns:rhq-configuration-export"; + public static final String CONFIGURATION_EXPORT_ELEMENT = "configuration-export"; public static final String ENTITIES_EXPORT_ELEMENT = "entities"; public static final String ENTITY_EXPORT_ELEMENT = "entity"; @@ -61,6 +75,7 @@ public class ExportingInputStream extends InputStream { public static final String NOTES_ELEMENT = "notes"; public static final String DATA_ELEMENT = "data"; public static final String VALIDATOR_ELEMENT = "validator"; + public static final String DEFAULT_CONFIGURATION_ELEMENT = "default-configuration"; public static final String ID_ATTRIBUTE = "id"; public static final String CLASS_ATTRIBUTE = "class";
@@ -72,6 +87,8 @@ public class ExportingInputStream extends InputStream { private Throwable unexpectedExporterException; private boolean zipOutput;
+ private Marshaller configurationMarshaller; + /** * Constructs a new exporting input stream with the default buffer size of 64KB that zips up * the results. @@ -99,6 +116,18 @@ public class ExportingInputStream extends InputStream { inputStream = new PipedInputStream(size); exportOutput = new PipedOutputStream(inputStream); zipOutput = zip; + + try { + JAXBContext context = JAXBContext.newInstance(DefaultImportConfigurationDescriptor.class); + + configurationMarshaller = context.createMarshaller(); + configurationMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); + configurationMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + configurationMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + + } catch (JAXBException e) { + throw new IOException(e); + } }
@Override @@ -182,6 +211,7 @@ public class ExportingInputStream extends InputStream { OutputStream out = null; try { XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); + ofactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
try { out = exportOutput; @@ -223,9 +253,68 @@ public class ExportingInputStream extends InputStream { * @throws XMLStreamException */ private void exportPrologue(XMLStreamWriter wrt) throws XMLStreamException { - wrt.setDefaultNamespace("urn:xmlns:rhq-configuration-export"); - wrt.writeStartDocument(); - wrt.writeStartElement(CONFIGURATION_EXPORT_ELEMENT); + wrt.setDefaultNamespace(EXPORT_NAMESPACE); + wrt.setPrefix(XMLConstants.DEFAULT_NS_PREFIX, EXPORT_NAMESPACE); + wrt.setPrefix("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + wrt.setPrefix("c", CONFIGURATION_NAMESPACE); + + NamespaceContext nsContext = new NamespaceContext() { + + //this map has to correspond to the namespaces defined in the code above + private final Map<String, String> PREFIXES = new HashMap<String, String>(); + { + PREFIXES.put(XMLConstants.DEFAULT_NS_PREFIX, EXPORT_NAMESPACE); + PREFIXES.put("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + PREFIXES.put("c", CONFIGURATION_NAMESPACE); + } + + @Override + public Iterator<String> getPrefixes(String namespaceURI) { + String prefix = getPrefix(namespaceURI); + if (prefix == null) { + return Collections.<String> emptySet().iterator(); + } else { + return Collections.singleton(prefix).iterator(); + } + } + + @Override + public String getPrefix(String namespaceURI) { + if (namespaceURI == null) { + throw new IllegalArgumentException(); + } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) { + return XMLConstants.XMLNS_ATTRIBUTE; + } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) { + return XMLConstants.XML_NS_PREFIX; + } else { + String prefix = null; + for (Map.Entry<String, String> e : PREFIXES.entrySet()) { + String p = e.getKey(); + String namespace = e.getValue(); + + if (namespaceURI.equals(namespace)) { + prefix = p; + break; + } + } + + return prefix; + } + } + + @Override + public String getNamespaceURI(String prefix) { + return PREFIXES.get(prefix); + } + }; + + wrt.setNamespaceContext(nsContext); + + wrt.writeStartElement(EXPORT_NAMESPACE, CONFIGURATION_EXPORT_ELEMENT); + wrt.writeDefaultNamespace(EXPORT_NAMESPACE); + wrt.writeNamespace("ci", ConfigurationInstanceUtil.NS_CONFIGURATION_INSTANCE); + wrt.writeNamespace("c", CONFIGURATION_NAMESPACE); + writeValidators(wrt); }
@@ -266,21 +355,31 @@ public class ExportingInputStream extends InputStream {
messagesPerExporter.put(syn.getClass().getName(), messages);
- wrt.writeStartElement(ENTITIES_EXPORT_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, ENTITIES_EXPORT_ELEMENT); wrt.writeAttribute(ID_ATTRIBUTE, syn.getClass().getName());
Exporter<?, ?> exp = syn.getExporter(); ExportingIterator<?> it = exp.getExportingIterator();
+ DefaultImportConfigurationDescriptor importConfig = getDefaultImportConfiguraton(syn); + + if (importConfig != null) { + try { + configurationMarshaller.marshal(importConfig, wrt); + } catch (JAXBException e) { + throw new XMLStreamException(e); + } + } + messages.setPerEntityErrorMessages(new ArrayList<String>()); messages.setPerEntityNotes(new ArrayList<String>());
while (it.hasNext()) { it.next();
- wrt.writeStartElement(ENTITY_EXPORT_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, ENTITY_EXPORT_ELEMENT);
- wrt.writeStartElement(DATA_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, DATA_ELEMENT);
Exception exportError = null; try { @@ -299,18 +398,18 @@ public class ExportingInputStream extends InputStream {
if (notes != null) { messages.getPerEntityNotes().add(notes); - wrt.writeStartElement(NOTES_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, NOTES_ELEMENT); wrt.writeCharacters(notes); wrt.writeEndElement(); } } else { String message = ThrowableUtil.getStackAsString(exportError); messages.getPerEntityErrorMessages().add(message); - wrt.writeStartElement(ERROR_MESSAGE_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, ERROR_MESSAGE_ELEMENT); wrt.writeCharacters(message); wrt.writeEndElement(); } - + wrt.writeEndElement(); //entity }
@@ -319,7 +418,7 @@ public class ExportingInputStream extends InputStream { messages.setExporterNotes(notes);
if (notes != null) { - wrt.writeStartElement(NOTES_ELEMENT); + wrt.writeStartElement(EXPORT_NAMESPACE, NOTES_ELEMENT); wrt.writeCharacters(notes); wrt.writeEndElement(); } @@ -336,4 +435,20 @@ public class ExportingInputStream extends InputStream { LOG.error("Failed to close an output stream. This shouldn't happen.", e); } } + + private DefaultImportConfigurationDescriptor getDefaultImportConfiguraton(Synchronizer<?, ?> synchronizer) { + DefaultImportConfigurationDescriptor ret = null; + + ConfigurationDefinition def = synchronizer.getImporter().getImportConfigurationDefinition(); + + if (def != null) { + ConfigurationTemplate template = def.getDefaultTemplate(); + if (template != null) { + ret = DefaultImportConfigurationDescriptor.create(ConfigurationInstanceUtil + .createConfigurationInstance(def, template.getConfiguration())); + } + } + + return ret; + } } diff --git a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java new file mode 100644 index 0000000..b383bbd --- /dev/null +++ b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/ConfigurationInstanceUtil.java @@ -0,0 +1,118 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.xmlschema; + +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; +import javax.xml.namespace.QName; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.Property; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinition; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; +import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.ConfigurationInstanceDescriptor; +import org.rhq.enterprise.server.xmlschema.generated.configuration.instance.SimplePropertyInstanceDescriptor; + +/** + * + * + * @author Lukas Krejci + */ +public class ConfigurationInstanceUtil { + + public static final String NS_CONFIGURATION_INSTANCE = "urn:xmlns:rhq-configuration-instance"; + + private ConfigurationInstanceUtil() { + + } + + /** + * A configuration instance is a combination of a configuration definition and a concrete + * configuration instance with defined values. This is used during the config synchronization + * to output the default configuration of an importer directly in the export file so that the + * users have an easy way of modifying that configuration. + * + * @param definition + * @param configuration + * @return + */ + public static ConfigurationInstanceDescriptor createConfigurationInstance(ConfigurationDefinition definition, + Configuration configuration) { + + ConfigurationInstanceDescriptor ret = new ConfigurationInstanceDescriptor(); + + addAll(ret.getConfigurationProperty(), definition.getPropertyDefinitions(), configuration.getMap()); + + return ret; + } + + private static void addAll(List<JAXBElement<?>> descriptors, Map<String, PropertyDefinition> defs, Map<String, Property> props) { + for(Map.Entry<String, PropertyDefinition> e : defs.entrySet()) { + String propName = e.getKey(); + PropertyDefinition def = e.getValue(); + Property prop = props.get(propName); + + addSingle(descriptors, def, prop); + } + } + + private static void addSingle(List<JAXBElement<?>> descriptors, PropertyDefinition def, Property prop) { + Object descriptor = null; + String tagName = null; + + if (def instanceof PropertyDefinitionSimple) { + descriptor = createSimple(def, prop); + tagName = "simple-property"; + } else if (def instanceof PropertyDefinitionList) { + //TODO + } else if (def instanceof PropertyDefinitionMap) { + //TODO + } + + addToJAXBElementList(descriptors, Object.class, descriptor, new QName(NS_CONFIGURATION_INSTANCE, tagName)); + } + + private static SimplePropertyInstanceDescriptor createSimple(PropertyDefinition def, Property prop) { + SimplePropertyInstanceDescriptor ret = new SimplePropertyInstanceDescriptor(); + PropertyDefinitionSimple pds = (PropertyDefinitionSimple) def; + ret.setName(pds.getName()); + ret.setDescription(pds.getDescription()); + ret.setLongDescription(pds.getDescription()); + ret.setDisplayName(pds.getDisplayName()); + + //TODO add rest of the properties + + ret.setValue(((PropertySimple)prop).getStringValue()); + + return ret; + } + + + private static <T> void addToJAXBElementList(List<JAXBElement<? extends T>> list, Class<T> baseClass, T property, QName tagName) { + JAXBElement<? extends T> el = new JAXBElement<T>(tagName, baseClass, property.getClass(), property); + list.add(el); + } +} diff --git a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/XmlSchemas.java b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/XmlSchemas.java index ea48d0e..ce46022 100644 --- a/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/XmlSchemas.java +++ b/modules/enterprise/server/xml-schemas/src/main/java/org/rhq/enterprise/server/xmlschema/XmlSchemas.java @@ -79,4 +79,12 @@ public interface XmlSchemas { // the schema used to define content source metadata which is used by content plugins like the URL or Disk plugins public static final String XSD_SERVERPLUGIN_DRIFT = "rhq-serverplugin-drift.xsd"; public static final String PKG_SERVERPLUGIN_DRIFT = "org.rhq.enterprise.server.xmlschema.generated.serverplugin.drift"; + + //the schema that describes the format of the configuration export file + public static final String XSD_CONFIGURATION_EXPORT = "rhq-configuration-export.xsd"; + public static final String PKG_CONFIGURATION_EXPORT = "org.rhq.enterprise.server.xmlschema.generated.configuration.export"; + + //the schema that describes a configuration instance - a combination of configuration definition and concrete values + public static final String XSD_CONFIGURATION_INSTANCE = "rhq-configuration-instance.xsd"; + public static final String PKG_CONFIGURATION_INSTANCE = "org.rhq.enterprise.server.xmlschema.generated.configuration.instance"; } \ No newline at end of file diff --git a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd index a4c6d0d..d94b696 100644 --- a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd +++ b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd @@ -3,6 +3,7 @@ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:xmlns:rhq-configuration-export" xmlns:ce="urn:xmlns:rhq-configuration-export" + xmlns:ci="urn:xmlns:rhq-configuration-instance" elementFormDefault="qualified" jaxb:version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb%22%3E @@ -11,8 +12,16 @@ xs:documentation A schema for RHQ server configuration export files. </xs:documentation> + xs:appinfo + jaxb:schemaBindings + <jaxb:package + name="org.rhq.enterprise.server.xmlschema.generated.configuration.export" /> + </jaxb:schemaBindings> + </xs:appinfo> </xs:annotation>
+ <xs:import namespace="urn:xmlns:rhq-configuration-instance" schemaLocation="rhq-configuration-instance.xsd" /> + <xs:element name="configuration-export" type="ce:ConfigurationExport" />
<xs:complexType name="ConfigurationExport"> @@ -31,6 +40,7 @@
<xs:complexType name="EntitiesExport"> xs:sequence + <xs:element type="ci:Configuration" name="default-configuration" minOccurs="0" maxOccurs="1"/> <xs:element minOccurs="0" maxOccurs="unbounded" type="ce:EntityExport" name="entity" /> <xs:element type="xs:string" name="notes" /> </xs:sequence> diff --git a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd new file mode 100644 index 0000000..f05585d --- /dev/null +++ b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-instance.xsd @@ -0,0 +1,185 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> + +<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:config="urn:xmlns:rhq-configuration" xmlns:ci="urn:xmlns:rhq-configuration-instance" + targetNamespace="urn:xmlns:rhq-configuration-instance" + elementFormDefault="qualified" jaxb:version="2.0" + xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" blockDefault=""> + + xs:annotation + xs:documentationSchema for the definition of generic + configuration data. + </xs:documentation> + xs:appinfo + jaxb:schemaBindings + <jaxb:package + name="org.rhq.enterprise.server.xmlschema.generated.configuration.instance" /> + </jaxb:schemaBindings> + </xs:appinfo> + </xs:annotation> + + <xs:import namespace="urn:xmlns:rhq-configuration" + schemaLocation="rhq-configuration.xsd" /> + + <xs:element name="configuration" type="ci:Configuration" /> + <xs:complexType name="Configuration"> + xs:annotation + xs:appinfo + <jaxb:class name="ConfigurationInstanceDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:sequence + <xs:element ref="ci:configuration-property" + minOccurs="0" maxOccurs="unbounded" /> + </xs:sequence> + </xs:complexType> + + <xs:element name="configuration-property" abstract="true" /> + + <xs:element name="simple-property" type="ci:SimpleProperty" + substitutionGroup="ci:configuration-property" /> + <xs:complexType name="SimpleProperty"> + xs:annotation + xs:appinfo + <jaxb:class name="SimplePropertyInstanceDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:extension base="config:simpleProperty"> + <xs:attribute name="value" type="xs:string" /> + <xs:attribute name="default" use="prohibited" /> + <xs:attribute name="defaultValue" use="prohibited" /> + <xs:attribute name="summary" use="prohibited" /> + <xs:attribute name="readOnly" use="prohibited" /> + <xs:attribute name="activationPolicy" use="prohibited" /> + </xs:extension> + </xs:complexContent> + </xs:complexType> + + <xs:element name="list-property" type="ci:ListProperty" + substitutionGroup="ci:configuration-property" /> + <xs:complexType name="ListProperty"> + xs:annotation + xs:appinfo + <jaxb:class name="ListPropertyInstanceDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:extension base="config:listProperty"> + xs:sequence + <xs:element name="values" type="ci:PropertyValues" + minOccurs="0" maxOccurs="1" /> + </xs:sequence> + <xs:attribute name="default" use="prohibited" /> + <xs:attribute name="defaultValue" use="prohibited" /> + <xs:attribute name="summary" use="prohibited" /> + <xs:attribute name="readOnly" use="prohibited" /> + <xs:attribute name="activationPolicy" use="prohibited" /> + </xs:extension> + </xs:complexContent> + </xs:complexType> + + <xs:element name="map-property" type="ci:MapProperty" + substitutionGroup="ci:configuration-property" /> + <xs:complexType name="MapProperty"> + xs:annotation + xs:appinfo + <jaxb:class name="MapPropertyInstanceDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:extension base="config:mapProperty"> + xs:sequence + <xs:element name="values" type="ci:PropertyValues" + minOccurs="0" maxOccurs="1" /> + </xs:sequence> + <xs:attribute name="default" use="prohibited" /> + <xs:attribute name="defaultValue" use="prohibited" /> + <xs:attribute name="summary" use="prohibited" /> + <xs:attribute name="readOnly" use="prohibited" /> + <xs:attribute name="activationPolicy" use="prohibited" /> + </xs:extension> + </xs:complexContent> + </xs:complexType> + + <xs:element name="complex-value" abstract="true" /> + <xs:complexType name="ComplexValue"> + xs:annotation + xs:appinfo + <jaxb:class name="ComplexValueDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + <xs:attribute name="property-name" type="xs:string" + use="required" /> + </xs:complexType> + + <xs:complexType name="PropertyValues"> + xs:annotation + xs:appinfo + <jaxb:class name="PropertyValuesDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:sequence + <xs:element ref="ci:complex-value" minOccurs="0" + maxOccurs="unbounded" /> + </xs:sequence> + </xs:complexType> + + <xs:element name="simple-value" type="ci:ComplexValueSimple" + substitutionGroup="ci:complex-value" /> + <xs:complexType name="ComplexValueSimple"> + xs:annotation + xs:appinfo + <jaxb:class name="ComplexValueSimpleDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:restriction base="ci:ComplexValue" /> + </xs:complexContent> + </xs:complexType> + + <xs:element name="list-value" type="ci:ComplexValueList" + substitutionGroup="ci:complex-value" /> + <xs:complexType name="ComplexValueList"> + xs:annotation + xs:appinfo + <jaxb:class name="ComplexValueListDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:extension base="ci:ComplexValue"> + xs:sequence + <xs:element ref="ci:complex-value" + minOccurs="0" maxOccurs="unbounded" /> + </xs:sequence> + </xs:extension> + </xs:complexContent> + </xs:complexType> + + <xs:element name="map-value" type="ci:ComplexValueMap" + substitutionGroup="ci:complex-value" /> + <xs:complexType name="ComplexValueMap"> + xs:annotation + xs:appinfo + <jaxb:class name="ComplexValueMapDescriptor" /> + </xs:appinfo> + xs:documentation</xs:documentation> + </xs:annotation> + xs:complexContent + <xs:extension base="ci:ComplexValue"> + xs:sequence + <xs:element ref="ci:complex-value" + minOccurs="0" maxOccurs="unbounded" /> + </xs:sequence> + </xs:extension> + </xs:complexContent> + </xs:complexType> +</xs:schema>
commit a180c52b8431425794ed1302a6312be5c907c92f Merge: 0d0d84b c2d5699 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 00:32:45 2011 +0200
Merge remote-tracking branch 'origin/master' into feature/config-sync
commit 0d0d84b6c6403bab45bf2b08194eb0f788524f65 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 00:31:35 2011 +0200
Preload all the measurement definitions before they are matched against entries in the export file. This speeds up the import big time (somewhat obviously).
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index 1445ba9..78eea09 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -178,34 +178,38 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M public ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> getExportedEntityMatcher() { return new ExportedEntityMatcher<MeasurementDefinition, MetricTemplate>() {
+ private Map<MetricTemplate, MeasurementDefinition> cache; + + { + //this instance will be used many many times to find the measurement + //definitions that correspond to the templates stored in the export file + //it is therefore more optimal to just preload all the mds in a cache + //and use that to find matches than to query the database each time. + cache = new HashMap<MetricTemplate, MeasurementDefinition>(); + + Query q = entityManager.createQuery("SELECT md FROM MeasurementDefinition md"); + + for (Object r : q.getResultList()) { + MeasurementDefinition md = (MeasurementDefinition) r; + + cache.put(new MetricTemplate(md), md); + } + + } @Override public MeasurementDefinition findMatch(MetricTemplate object) { - Query q = - entityManager - .createNamedQuery(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME); - q.setParameter("name", object.getMetricName()); - q.setParameter("resourceTypeName", object.getResourceTypeName()); - q.setParameter("resourceTypePlugin", object.getResourceTypePlugin()); - q.setParameter("perMinute", object.isPerMinute() ? 1 : 0); - - List<?> results = q.getResultList(); - - if (results.isEmpty()) { - if (LOG.isDebugEnabled()) { + MeasurementDefinition md = cache.get(object); + + if (md == null && LOG.isDebugEnabled()) { LOG.debug("Failed to find a measurement definition corresponding to " + object + ". This means that the plugins in the source RHQ install were different than in this RHQ install " + "but the DeployedAgentPluginsValidator failed to catch that. This most probably means that the " + "export file has been tampered with. Letting the import continue because that might have been intentional change by the user."); - } - return null; - } else if (results.size() > 1) { - throw new IllegalStateException( - "Found more than one measurement definition with the same name and resource type. This should never happen. " - + results); - } else { - return (MeasurementDefinition) results.get(0); + } + + return md; } }; }
commit d7449e1aeefbea1354204e51d142fabca29d7889 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 00:29:00 2011 +0200
BZ 731587 - added a new metric template validator that checks that the imported metric templates match records in the database and are not duplicated in the export file.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/MetricTemplate.java b/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/MetricTemplate.java index 1ed11bf..7e52250 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/MetricTemplate.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/MetricTemplate.java @@ -39,25 +39,25 @@ public class MetricTemplate extends AbstractExportedEntity {
@XmlAttribute private String resourceTypeName; - + @XmlAttribute private String resourceTypePlugin; - + @XmlAttribute private String metricName;
@XmlAttribute private boolean perMinute; - + @XmlAttribute private long defaultInterval; - + @XmlAttribute private boolean enabled;
public MetricTemplate() { } - + public MetricTemplate(MeasurementDefinition definition) { resourceTypeName = definition.getResourceType().getName(); resourceTypePlugin = definition.getResourceType().getPlugin(); @@ -67,7 +67,7 @@ public class MetricTemplate extends AbstractExportedEntity { perMinute = definition.getRawNumericType() != null; setReferencedEntityId(definition.getId()); } - + public String getResourceTypeName() { return resourceTypeName; } @@ -114,22 +114,43 @@ public class MetricTemplate extends AbstractExportedEntity { public boolean isPerMinute() { return perMinute; } - + /** * @param perMinute the perMinute to set */ public void setPerMinute(boolean perMinute) { this.perMinute = perMinute; } - + + @Override + public int hashCode() { + return (perMinute ? 31 : 1) * metricName.hashCode() * resourceTypeName.hashCode() + * resourceTypePlugin.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + + if (!(other instanceof MetricTemplate)) { + return false; + } + + MetricTemplate o = (MetricTemplate) other; + + return metricName.equals(o.metricName) && resourceTypeName.equals(o.resourceTypeName) + && resourceTypePlugin.equals(o.resourceTypePlugin) && (perMinute == o.perMinute); + } + @Override public String toString() { StringBuilder bld = new StringBuilder(); - bld.append("MetricTemplate[metric='").append(metricName).append("', resourceType='") - .append(resourceTypeName).append("', plugin='").append(resourceTypePlugin) - .append("', perMinute=").append(perMinute).append(", defaultInterval=") - .append(defaultInterval).append(", enabled=").append(enabled).append("]"); - + bld.append("MetricTemplate[metric='").append(metricName).append("', resourceType='").append(resourceTypeName) + .append("', plugin='").append(resourceTypePlugin).append("', perMinute=").append(perMinute) + .append(", defaultInterval=").append(defaultInterval).append(", enabled=").append(enabled).append("]"); + return bld.toString(); } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java index 30f8409..847fe2f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/MetricTemplateSynchronizer.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.server.sync;
import java.util.Collections; +import java.util.HashSet; import java.util.Set;
import javax.persistence.EntityManager; @@ -35,6 +36,7 @@ import org.rhq.enterprise.server.sync.importers.Importer; import org.rhq.enterprise.server.sync.importers.MetricTemplateImporter; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; import org.rhq.enterprise.server.sync.validators.DeployedAgentPluginsValidator; +import org.rhq.enterprise.server.sync.validators.MetricTemplateValidator; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -73,7 +75,10 @@ public class MetricTemplateSynchronizer implements Synchronizer<MeasurementDefin }
public Set<ConsistencyValidator> getRequiredValidators() { - return Collections.<ConsistencyValidator>singleton(new DeployedAgentPluginsValidator(pluginManager)); + HashSet<ConsistencyValidator> ret = new HashSet<ConsistencyValidator>(); + ret.add(new DeployedAgentPluginsValidator(pluginManager)); + ret.add(new MetricTemplateValidator()); + return ret; }
} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java index 53d07da..c036dd6 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java @@ -390,8 +390,8 @@ public class SynchronizationManagerBean implements SynchronizationManagerLocal, validator.initialize(subject, entityManager);
//perform the validation - validator.initializeValidation(new ExportReader(rdr)); - validator.validateCurrentState(); + validator.initializeExportedStateValidation(new ExportReader(rdr)); + validator.validateExportedState();
return validator; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/Synchronizer.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/Synchronizer.java index df38ca5..5e559d7 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/Synchronizer.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/Synchronizer.java @@ -40,7 +40,7 @@ public interface Synchronizer<Entity, ExportedEntity> {
/** * Initializes the synchronizer so that it can access database - * and authorization aware. + * and is authorization aware. * * @param subject the currently logged in user * @param entityManager the entity manager to access the database with (if not using one diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/ConsistencyValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/ConsistencyValidator.java index 0b4a8f1..2b42f5a 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/ConsistencyValidator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/ConsistencyValidator.java @@ -48,6 +48,7 @@ public interface ConsistencyValidator {
/** * Initializes the validator with the current authentication info and access to database. + * This method is only called during import. * * @param subject the currently authenticated user * @param entityManager the entity manager that can be used to access the database if the @@ -68,7 +69,7 @@ public interface ConsistencyValidator {
/** * This method initializes the consistency checker to perform the - * {@link #validateCurrentState()} method later on. + * {@link #validateExportedState()} method later on. * <p> * This method is called during import and the reader points to a structure * previously stored by the {@link #exportState(ExportWriter)} method on @@ -77,18 +78,18 @@ public interface ConsistencyValidator { * @param reader * @throws XMLStreamException */ - void initializeValidation(ExportReader reader) throws XMLStreamException; + void initializeExportedStateValidation(ExportReader reader) throws XMLStreamException;
/** * Validates that the current RHQ installation is consistent with the state * mandated during the export. * <p> - * This method is only ever called after the {@link #initializeValidation(XMLStreamReader)} + * This method is only ever called after the {@link #initializeExportedStateValidation(XMLStreamReader)} * is invoked. * * @throws InconsistentStateException in case of failed consistency check */ - void validateCurrentState() throws InconsistentStateException; + void validateExportedState() throws InconsistentStateException;
/** * Returns the types of exported entities this validator can validate before export. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java index 17eae8a..2ec3f54 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java @@ -130,7 +130,7 @@ public class DeployedAgentPluginsValidator implements ConsistencyValidator { }
@Override - public void initializeValidation(ExportReader reader) throws XMLStreamException { + public void initializeExportedStateValidation(ExportReader reader) throws XMLStreamException { pluginsToValidate = new HashSet<ConsistentPlugin>();
while (reader.hasNext()) { @@ -152,7 +152,7 @@ public class DeployedAgentPluginsValidator implements ConsistencyValidator { }
@Override - public void validateCurrentState() throws InconsistentStateException { + public void validateExportedState() throws InconsistentStateException { List<Plugin> localPlugins = pluginManager.getInstalledPlugins(); Set<ConsistentPlugin> localAgentPlugins = new HashSet<ConsistentPlugin>(); for(Plugin p : localPlugins) { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/MetricTemplateValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/MetricTemplateValidator.java new file mode 100644 index 0000000..eddddf7 --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/MetricTemplateValidator.java @@ -0,0 +1,121 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.validators; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.xml.stream.XMLStreamException; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.sync.entity.MetricTemplate; +import org.rhq.enterprise.server.sync.ExportReader; +import org.rhq.enterprise.server.sync.ExportWriter; +import org.rhq.enterprise.server.sync.ValidationException; + +/** + * + * + * @author Lukas Krejci + */ +public class MetricTemplateValidator implements ConsistencyValidator { + + private EntityManager entityManager; + private Set<MetricTemplate> allMeasurementDefinitions; + private Set<MetricTemplate> alreadyCheckedTemplates; + private boolean dataInitialized = false; + + @Override + public void initialize(Subject subject, EntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public void exportState(ExportWriter writer) throws XMLStreamException { + } + + @Override + public void initializeExportedStateValidation(ExportReader reader) throws XMLStreamException { + } + + @Override + public void validateExportedState() throws InconsistentStateException { + } + + @Override + public Set<Class<?>> getValidatedEntityTypes() { + return Collections.<Class<?>> singleton(MetricTemplate.class); + } + + @Override + public void validateExportedEntity(Object entity) throws ValidationException { + initializeData(); + + MetricTemplate template = (MetricTemplate) entity; + + if (!allMeasurementDefinitions.contains(template)) { + throw new ValidationException( + "The metric template " + + template + + " does not have any corresponding metric template in the database. This either means that the source of the export had different plugins installed, the export file has been manually edited to contain this inconsistency or that the database is corrupted."); + } + + if (!alreadyCheckedTemplates.add(template)) { + throw new ValidationException("Was the export file manually updated? The metric template " + template + " has been seen multiple times."); + } + } + + private void initializeData() { + if (dataInitialized) { + return; + } + + allMeasurementDefinitions = new HashSet<MetricTemplate>(); + alreadyCheckedTemplates = new HashSet<MetricTemplate>(); + + Query q = entityManager.createQuery("SELECT md FROM MeasurementDefinition md"); + + for (Object r : q.getResultList()) { + MeasurementDefinition md = (MeasurementDefinition) r; + + allMeasurementDefinitions.add(new MetricTemplate(md)); + } + + dataInitialized = true; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + + return other instanceof MetricTemplateValidator; + } +} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/SystemSettingsValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/SystemSettingsValidator.java index 64335d5..1d34516 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/SystemSettingsValidator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/SystemSettingsValidator.java @@ -61,11 +61,11 @@ public class SystemSettingsValidator implements ConsistencyValidator { }
@Override - public void initializeValidation(ExportReader reader) throws XMLStreamException { + public void initializeExportedStateValidation(ExportReader reader) throws XMLStreamException { }
@Override - public void validateCurrentState() throws InconsistentStateException { + public void validateExportedState() throws InconsistentStateException { }
@Override diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java index 14cf4ce..133750d 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java @@ -99,7 +99,7 @@ public class DeployedAgentPluginsValidatorTest extends JMockTest { //this is what is expected by the validators rdr.nextTag();
- validator.initializeValidation(new ExportReader(rdr)); + validator.initializeExportedStateValidation(new ExportReader(rdr));
rdr.close();
@@ -137,14 +137,14 @@ public class DeployedAgentPluginsValidatorTest extends JMockTest { validator.setPluginsToValidate(pluginsToValidate);
//this should validate cleanly - validator.validateCurrentState(); + validator.validateExportedState();
//now add 1 plugin to the validated state DeployedAgentPluginsValidator.ConsistentPlugin newPlugin = createPlugin("superfluous", "1", "md5_4"); pluginsToValidate.add(newPlugin);
try { - validator.validateCurrentState(); + validator.validateExportedState(); fail("validation should have detected that the current installation has one plugin less."); } catch (InconsistentStateException e) { //this is expected @@ -155,7 +155,7 @@ public class DeployedAgentPluginsValidatorTest extends JMockTest { installedPlugins.add(newPlugin);
try { - validator.validateCurrentState(); + validator.validateExportedState(); fail("validation should have detected that the current installation has one plugin more."); } catch (InconsistentStateException e) { //ok @@ -169,7 +169,7 @@ public class DeployedAgentPluginsValidatorTest extends JMockTest { newPlugin.setMd5("md5_different");
try { - validator.validateCurrentState(); + validator.validateExportedState(); fail("validation should have failed because one of the plugins differs between current and exported states."); } catch (InconsistentStateException e) { //ok @@ -179,7 +179,7 @@ public class DeployedAgentPluginsValidatorTest extends JMockTest { newPluginCopy.setMd5("md5_different");
try { - validator.validateCurrentState(); + validator.validateExportedState(); fail("validation should have failed because one of the plugins differs between current and exported states."); } catch (InconsistentStateException e) { //ok diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateValidatorTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateValidatorTest.java new file mode 100644 index 0000000..3afe29f --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateValidatorTest.java @@ -0,0 +1,161 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.test; + +import static org.testng.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.jmock.Expectations; +import org.testng.annotations.Test; + +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.measurement.NumericType; +import org.rhq.core.domain.resource.ResourceCategory; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.sync.entity.MetricTemplate; +import org.rhq.enterprise.server.sync.ValidationException; +import org.rhq.enterprise.server.sync.validators.MetricTemplateValidator; +import org.rhq.test.JMockTest; + +/** + * + * + * @author Lukas Krejci + */ +@Test +public class MetricTemplateValidatorTest extends JMockTest { + + private static final ResourceType FAKE_RESOURCE_TYPE = new ResourceType("fake", "fake", ResourceCategory.PLATFORM, null); + + public void testAllValidatorsEqual() { + MetricTemplateValidator v1 = new MetricTemplateValidator(); + MetricTemplateValidator v2 = new MetricTemplateValidator(); + MetricTemplateValidator v3 = new MetricTemplateValidator(); + + assertEquals(v1, v2); + assertEquals(v2, v3); + assertEquals(v1, v3); + } + + public void testDetectsUnknownTemplates() throws Exception { + final EntityManager entityManager = context.mock(EntityManager.class); + final Query q = context.mock(Query.class); + + final List<MeasurementDefinition> allDefs = new ArrayList<MeasurementDefinition>(); + + context.checking(new Expectations() { + { + //make the entity manager return the test data + allowing(entityManager).createQuery(with(any(String.class))); + will(returnValue(q)); + + allowing(q).getResultList(); + will(returnValue(allDefs)); + } + }); + + //add some test data + allDefs.add(createMeasurementDefinition("m1", false)); + allDefs.add(createMeasurementDefinition("m1", true)); + allDefs.add(createMeasurementDefinition("m2", false)); + allDefs.add(createMeasurementDefinition("m3", false)); + + MetricTemplateValidator validator = new MetricTemplateValidator(); + + validator.initialize(null, entityManager); + validator.initializeExportedStateValidation(null); + + //check that all the defined measurement defs pass + for(MeasurementDefinition md : allDefs) { + validator.validateExportedEntity(new MetricTemplate(md)); + } + + //now let's create an "unknown" metric template + MetricTemplate unknown = new MetricTemplate(); + unknown.setMetricName("unknown"); + unknown.setResourceTypeName("some"); + unknown.setResourceTypePlugin("other"); + + try { + validator.validateExportedEntity(unknown); + fail("Validating a metric template " + unknown + " should have failed."); + } catch (ValidationException e) { + //expected + } + } + + public void testDetectsDuplicitEntries() throws Exception { + final EntityManager entityManager = context.mock(EntityManager.class); + final Query q = context.mock(Query.class); + + final List<MeasurementDefinition> allDefs = new ArrayList<MeasurementDefinition>(); + + context.checking(new Expectations() { + { + //make the entity manager return the test data + allowing(entityManager).createQuery(with(any(String.class))); + will(returnValue(q)); + + allowing(q).getResultList(); + will(returnValue(allDefs)); + } + }); + + //add some test data + allDefs.add(createMeasurementDefinition("m1", false)); + allDefs.add(createMeasurementDefinition("m1", true)); + allDefs.add(createMeasurementDefinition("m2", false)); + allDefs.add(createMeasurementDefinition("m3", false)); + + MetricTemplateValidator validator = new MetricTemplateValidator(); + + validator.initialize(null, entityManager); + validator.initializeExportedStateValidation(null); + + //check that all the defined measurement defs pass + for(MeasurementDefinition md : allDefs) { + validator.validateExportedEntity(new MetricTemplate(md)); + } + + //now let's try and validate the first test data again. + //this simulates the duplicate entries in the export file + try { + MetricTemplate duplicate = new MetricTemplate(allDefs.get(0)); + validator.validateExportedEntity(duplicate); + fail("Validating a duplicate metric template " + duplicate + " should have failed."); + } catch (ValidationException e) { + //expected + } + } + + private static MeasurementDefinition createMeasurementDefinition(String name, boolean perMinute) { + MeasurementDefinition ret = new MeasurementDefinition(FAKE_RESOURCE_TYPE, name); + if (perMinute) { + ret.setRawNumericType(NumericType.TRENDSUP); + } + + return ret; + } +}
commit e92a7814473cfe577963585a934395d44a0ed31e Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 18 00:17:22 2011 +0200
make the import robust against whitespace in the XML.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java index ab19eac..53d07da 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/SynchronizationManagerBean.java @@ -310,7 +310,7 @@ public class SynchronizationManagerBean implements SynchronizationManagerLocal, switch (rdr.next()) { case XMLStreamConstants.START_ELEMENT: if (ExportingInputStream.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) { - rdr.next(); + rdr.nextTag(); Object exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr)); Class<?> exportedEntityClass = exportedEntity.getClass();
@@ -416,7 +416,7 @@ public class SynchronizationManagerBean implements SynchronizationManagerLocal, switch (rdr.next()) { case XMLStreamConstants.START_ELEMENT: if (ExportingInputStream.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) { - rdr.next(); + rdr.nextTag(); X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr)); E entity = matcher == null ? null : matcher.findMatch(exportedEntity); importer.update(entity, exportedEntity);
commit c2d569900a246117d66dfc2c057303d1fdd6a836 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 18:12:49 2011 -0400
[BZ 719997] fix so row detail links and double-clicking on rows in recent alerts portlets links to the correct details URL - the one corresponding to the current entity context (https://bugzilla.redhat.com/show_bug.cgi?id=719997)
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 9dbdcfe..63535a8 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 @@ -22,6 +22,7 @@ */ package org.rhq.enterprise.gui.coregui.client;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.enterprise.gui.coregui.client.admin.roles.RolesView; import org.rhq.enterprise.gui.coregui.client.admin.users.UsersView; @@ -36,7 +37,7 @@ public class LinkManager {
public static String getResourceLink(int resourceId) { if (GWT) { - return "#Resource/" + resourceId + "/Summary/Activity"; + return "#Resource/" + resourceId; } else { return "/rhq/resource/summary/overview.xhtml?id=" + resourceId; } @@ -180,7 +181,6 @@ public class LinkManager { } else { link = "/rhq/resource/operation/resourceOperationHistoryDetails-plain.xhtml?id=" + resourceId + "&opId=" + opHistoryId; - } return link; } @@ -197,12 +197,24 @@ public class LinkManager { return link; }
- public static String getSubsystemAlertHistoryLink(int resourceId, int alertHistoryId) { + public static String getAlertDetailLink(EntityContext entityContext, int alertId) { String link; if (GWT) { - link = "#Resource/" + resourceId + "/Alerts/History/" + alertHistoryId; - } else { - link = "/rhq/subsystem/alertHistory.xhtml"; + 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; + } + link = baseLink + "/" + alertId; + } else { + link = null; // TODO }
return link; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java index d448ac6..0997bee 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java @@ -57,7 +57,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * A view that displays a paginated table of fired {@link org.rhq.core.domain.alert.Alert alert}s, along with the * ability to filter those alerts, sort those alerts, double-click a row to view full details an alert, and perform * various operations on the the alerts: delete selected, delete all from source, ack selected, ack all from source. - * This view full respects the user's authorization, and will not allow operations on the alerts unless the user is + * This view fully respects the user's authorization, and will not allow operations on the alerts unless the user is * either the inventory manager or has MANAGE_ALERTS permission on every resource corresponding to the alerts being * operated on. * @@ -150,19 +150,6 @@ public class AlertHistoryView extends TableSection<AlertDataSource> { return AlertCriteria.SORT_FIELD_CTIME; }
- @Override - protected CellFormatter getDetailsLinkColumnCellFormatter() { - return new CellFormatter() { - public String format(Object value, ListGridRecord record, int i, int i1) { - Integer resourceId = record.getAttributeAsInt(AncestryUtil.RESOURCE_ID); - Integer alertHistoryId = getId(record); - String url = LinkManager.getSubsystemAlertHistoryLink(resourceId, alertHistoryId); - String formattedValue = TimestampCellFormatter.format(value); - return SeleniumUtility.getLocatableHref(url, formattedValue, null); - } - }; - } - /** * Subclasses can override this to indicate they do not support * deleting all alerts or acknowledging all alerts. Portlet subclasses diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java index 5cc231e..7b3b86d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java @@ -17,6 +17,8 @@ import com.smartgwt.client.widgets.form.fields.CheckboxItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem;
+import com.smartgwt.client.widgets.grid.CellFormatter; +import com.smartgwt.client.widgets.grid.ListGridRecord; import org.rhq.core.domain.alert.Alert; import org.rhq.core.domain.alert.AlertPriority; import org.rhq.core.domain.authz.Permission; @@ -30,9 +32,12 @@ import org.rhq.core.domain.util.OrderingField; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.LinkManager; import org.rhq.enterprise.gui.coregui.client.alert.AlertDataSource; import org.rhq.enterprise.gui.coregui.client.alert.AlertHistoryView; import org.rhq.enterprise.gui.coregui.client.components.measurement.CustomConfigMeasurementRangeEditor; +import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortletUtil; import org.rhq.enterprise.gui.coregui.client.dashboard.CustomSettingsPortlet; @@ -42,6 +47,7 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.PortletConfigura import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; +import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** * A base class for deriving recent alerts portlets for different entity contexts. In this way the @@ -71,6 +77,28 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple }
@Override + protected CellFormatter getDetailsLinkColumnCellFormatter() { + return new CellFormatter() { + public String format(Object value, ListGridRecord record, int i, int i1) { + String url = getAlertDetailLink(record); + String formattedValue = TimestampCellFormatter.format(value); + return SeleniumUtility.getLocatableHref(url, formattedValue, null); + } + }; + } + + @Override + public void showDetails(ListGridRecord record) { + String url = getAlertDetailLink(record); + CoreGUI.goToView(url); + } + + private String getAlertDetailLink(ListGridRecord record) { + Integer alertId = getId(record); + return LinkManager.getAlertDetailLink(getContext(), alertId); + } + + @Override protected boolean canSupportDeleteAndAcknowledgeAll() { return false; }
commit b2ec9e64a469979a9b46181a718514690454d619 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 16:42:39 2011 -0400
[BZ 731541] fix so group config editor member values modal actually shows the member property values (https://bugzilla.redhat.com/show_bug.cgi?id=731541)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java index c7b087c..eadf70f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java @@ -268,12 +268,6 @@ public class GroupConfigurationEditor extends ConfigurationEditor { } membersForm.setItems(items.toArray(new FormItem[items.size()]));
- for (FormItem valueItem : valueItems) { - String defaultValue = valueItem.getAttribute("defaultValue"); - setValue(valueItem, defaultValue); - valueItem.setDisabled(false); - } - // TODO: Anchor the button bar at the bottom of the modal window, so it's always visible. HLayout buttonBar = new HLayout(); buttonBar.setAlign(Alignment.CENTER);
commit 8d247e17ecf62ef38e950ec31e6de36e81423221 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 16:33:22 2011 -0400
[BZ 705727] change the message so its more clear what is happening
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 25544b8..a67dfc0 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 @@ -1375,7 +1375,7 @@ view_inventory_problemGroups = Problem Groups view_inventory_resource_loadFailed = Resource with id [{0}] does not exist or is not accessible view_inventory_resources_deleteConfirm = Are you sure you want to delete the selected resources? view_inventory_resources_deleteFailed = Failed to delete the selected resources -view_inventory_resources_deleteSuccessful = You have successfully deleted the selected resources +view_inventory_resources_deleteSuccessful = A request to perform the resource deletion has been submitted successfully to the agent(s). view_inventory_resources_loadFailed = Failed to load resource composite data view_inventory_resources_title = Resources view_inventory_resources_title_children = Child Resources 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 5ba4580..d3c7734 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 @@ -1104,7 +1104,7 @@ view_inventory_problemGroups = Gruppen mit Problemen view_inventory_resource_loadFailed = Resource with id [{0}] does not exist or is not accessible~ view_inventory_resources_deleteConfirm = Are you sure you want to delete the selected resources?~ view_inventory_resources_deleteFailed = Failed to delete the selected resources~ -view_inventory_resources_deleteSuccessful = You have successfully deleted the selected resources~ +##view_inventory_resources_deleteSuccessful = A request to perform the resource deletion has been submitted successfully to the agent(s). view_inventory_resources_loadFailed = Failed to load resource composite data~ view_inventory_resources_title = Ressourcen view_inventory_resources_title_children = Child Resources~ 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 7912b39..e9d4607 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 @@ -1344,7 +1344,7 @@ view_inventory_problemGroups = åé¡ã°ã«ãŒã view_inventory_resource_loadFailed = ID [{0}] ãTæã€ãªãœãŒã¹ã¯ååšããªãããã¢ã¯ã»ã¹ã§ããŸãã view_inventory_resources_deleteConfirm = éžæããããªãœãŒã¹ãåé€ãããã§ãã? view_inventory_resources_deleteFailed = éžæããããªãœãŒã¹ã®åé€ã«å€±æããŸãã -view_inventory_resources_deleteSuccessful = éžæããããªãœãŒã¹ã®åé€ã«æåããŸãã +##view_inventory_resources_deleteSuccessful = A request to perform the resource deletion has been submitted successfully to the agent(s). view_inventory_resources_loadFailed = ãªãœãŒã¹åæããŒã¿ã®ããŒãã«å€±æããŸãã view_inventory_resources_title = ãªãœãŒã¹ view_inventory_resources_title_children = åãªãœãŒã¹ 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 25f20f9..d80405a 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 @@ -1395,7 +1395,7 @@ view_inventory_problemGroups = Problem Groups view_inventory_resource_loadFailed = Resource with id [{0}] does not exist or is not accessible view_inventory_resources_deleteConfirm = Are you sure you want to delete the selected resources? view_inventory_resources_deleteFailed = Failed to delete the selected resources -view_inventory_resources_deleteSuccessful = You have successfully deleted the selected resources +##view_inventory_resources_deleteSuccessful = A request to perform the resource deletion has been submitted successfully to the agent(s). view_inventory_resources_loadFailed = Failed to load resource composite data view_inventory_resources_title = Recursos membros view_inventory_resources_title_children = Child Resources 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 33d7e2b..087f17b 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 @@ -1352,7 +1352,7 @@ view_inventory_problemGroups = \u95ee\u9898\u7ec4 view_inventory_resource_loadFailed = id\u4e3a [{0}]\u7684\u8d44\u6e90\u4e0d\u5b58\u5728\u6216\u8005\u4e0d\u53ef\u8fbe view_inventory_resources_deleteConfirm = \u786e\u5b9a\u5220\u9664\u9009\u4e2d\u7684\u8d44\u6e90\uff1f view_inventory_resources_deleteFailed = \u5220\u9664\u6307\u5b9a\u7684\u8d44\u6e90\u5931\u8d25 -view_inventory_resources_deleteSuccessful = \u6210\u529f\u7684\u5220\u9664\u6307\u5b9a\u7684\u8d44\u6e90 +##view_inventory_resources_deleteSuccessful = A request to perform the resource deletion has been submitted successfully to the agent(s). view_inventory_resources_loadFailed = \u52a0\u8f7d\u8d44\u6e90\u7ec4\u5408\u6570\u636e\u5931\u8d25 view_inventory_resources_title = \u8d44\u6e90 view_inventory_resources_title_children = \u5b50\u8d44\u6e90
commit 1a388660d005affd5d404c5c997478fe0808313b Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 16:14:55 2011 -0400
[BZ 721053] do not show delete all/ack all buttons on alert portlets
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java index 3fa6202..d448ac6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/AlertHistoryView.java @@ -163,6 +163,19 @@ public class AlertHistoryView extends TableSection<AlertDataSource> { }; }
+ /** + * Subclasses can override this to indicate they do not support + * deleting all alerts or acknowledging all alerts. Portlet subclasses + * that only trim their views to the top N alerts can override this to + * return false so they don't delete or acknowledge alerts that aren't displayed + * to the user. + * + * @return this default implementation returns true + */ + protected boolean canSupportDeleteAndAcknowledgeAll() { + return true; + } + protected void setupTableInteractions(final boolean hasWriteAccess) { TableActionEnablement singleTargetEnablement = hasWriteAccess ? TableActionEnablement.ANY : TableActionEnablement.NEVER; @@ -179,30 +192,33 @@ public class AlertHistoryView extends TableSection<AlertDataSource> { acknowledge(selection); } }); - addTableAction("DeleteAll", MSG.common_button_delete_all(), MSG.view_alerts_delete_confirm_all(), - 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("AcknowledgeAll", MSG.common_button_ack_all(), MSG.view_alerts_ack_confirm_all(), - 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) { - acknowledgeAll(); - } - }); + if (canSupportDeleteAndAcknowledgeAll()) { + addTableAction("DeleteAll", MSG.common_button_delete_all(), MSG.view_alerts_delete_confirm_all(), + 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("AcknowledgeAll", MSG.common_button_ack_all(), MSG.view_alerts_ack_confirm_all(), + 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) { + acknowledgeAll(); + } + }); + } }
void delete(ListGridRecord[] records) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java index 073cee8..5cc231e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java @@ -70,6 +70,11 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple setShowHeader(false);//disable header for portlets }
+ @Override + protected boolean canSupportDeleteAndAcknowledgeAll() { + return false; + } + public Timer getRefreshTimer() { return refreshTimer; }
commit a7d37237828a22d5ab19cc4ec63f28a5f9ef0083 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 15:50:34 2011 -0400
[BZ 719731] fix group config view
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java index c446a9e..cb3a3ec 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/ConfigurationManagerBean.java @@ -192,7 +192,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf // Mask the configuration before returning it. Resource resource = resourceManager.getResourceById(subjectManager.getOverlord(), resourceId); ConfigurationDefinition pluginConfigurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), resource.getResourceType().getId()); + subjectManager.getOverlord(), resource.getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); ConfigurationMaskingUtility.maskConfiguration(pluginConfiguration, pluginConfigurationDefinition); @@ -267,7 +267,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
public PluginConfigurationUpdate updatePluginConfiguration(Subject subject, int resourceId, @XmlJavaTypeAdapter(ConfigurationAdapter.class) Configuration newPluginConfiguration) - throws ResourceNotFoundException { + throws ResourceNotFoundException { Subject overlord = subjectManager.getOverlord(); Resource resource = resourceManager.getResourceById(overlord, resourceId);
@@ -279,7 +279,8 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf ConfigurationMaskingUtility.unmaskConfiguration(newPluginConfiguration, existingPluginConfiguration);
// create our new update request and assign it to our resource - its status will initially be "in progress" - PluginConfigurationUpdate update = new PluginConfigurationUpdate(resource, newPluginConfiguration, subject.getName()); + PluginConfigurationUpdate update = new PluginConfigurationUpdate(resource, newPluginConfiguration, subject + .getName());
update.setStatus(ConfigurationUpdateStatus.SUCCESS); entityManager.persist(update); @@ -340,7 +341,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf // Mask the configuration before returning it. Resource resource = resourceManager.getResourceById(subjectManager.getOverlord(), resourceId); ConfigurationDefinition resourceConfigurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), resource.getResourceType().getId()); + subjectManager.getOverlord(), resource.getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); ConfigurationMaskingUtility.maskConfiguration(resourceConfiguration, resourceConfigurationDefinition); @@ -354,8 +355,8 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
Resource resource = entityManager.getReference(Resource.class, resourceId); if (resource == null) { - throw new NoResultException("Cannot get latest resource configuration for unknown Resource [" - + resourceId + "]."); + throw new NoResultException("Cannot get latest resource configuration for unknown Resource [" + resourceId + + "]."); }
if (!authorizationManager.hasResourcePermission(subject, Permission.CONFIGURE_READ, resource.getId())) { @@ -422,11 +423,11 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf + "]; will assume latest resource configuration update is the current resource configuration."); }
- if (current!=null) { + if (current != null) { // Mask the configuration before returning the update. Configuration configuration = current.getConfiguration(); ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), resource.getResourceType().getId()); + subjectManager.getOverlord(), resource.getResourceType().getId()); // We do not want the masked configuration persisted, so detach all entities before masking the configuration. entityManager.clear(); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); @@ -439,6 +440,10 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf return getLatestResourceConfigurationUpdate(subject, resourceId, true); }
+ /** + * Will return the persisted Resource Configuration update, or null if the specified Configuration + * is identical to the currently persisted Configuration. + */ private ResourceConfigurationUpdate persistNewAgentReportedResourceConfiguration(Resource resource, Configuration liveConfig) throws ConfigurationUpdateStillInProgressException {
@@ -471,8 +476,8 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
Resource resource = entityManager.getReference(Resource.class, resourceId); if (resource == null) { - throw new NoResultException("Cannot get latest plugin configuration for unknown Resource [" - + resourceId + "]."); + throw new NoResultException("Cannot get latest plugin configuration for unknown Resource [" + resourceId + + "]."); }
if (!authorizationManager.canViewResource(subject, resource.getId())) { @@ -492,7 +497,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf // Mask the configuration before returning the update. Configuration configuration = current.getConfiguration(); ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), resource.getResourceType().getId()); + subjectManager.getOverlord(), resource.getResourceType().getId()); // We do not want the masked configuration persisted, so detach all entities before masking the configuration. entityManager.clear(); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); @@ -511,7 +516,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf query.setParameter("resourceId", resourceId); ResourceConfigurationUpdate latestConfigUpdate = (ResourceConfigurationUpdate) query.getSingleResult(); if (!authorizationManager.hasResourcePermission(subject, Permission.CONFIGURE_READ, latestConfigUpdate - .getResource().getId())) { + .getResource().getId())) { throw new PermissionException("User [" + subject.getName() + "] does not have permission to view Resource configuration for [" + latestConfigUpdate.getResource() + "]"); @@ -635,17 +640,20 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf // If the live config is different than the persisted config, persist it as the new current config. ResourceConfigurationUpdate update = persistNewAgentReportedResourceConfiguration(memberResource, liveConfig); - if (update != null) + if (update != null) { currentPersistedConfigs.put(memberResource.getId(), update.getConfiguration()); - else - log.error("Current Configuration for " + memberResource - + " does not match latest associated ResourceConfigurationUpdate with SUCCESS status."); + log.info("Live configuration for [" + memberResource + + "] did not match latest associated ResourceConfigurationUpdate with SUCCESS status."); + } else { + // this means the live config is identical to the persisted config + currentPersistedConfigs.put(memberResource.getId(), liveConfig); + } } }
// Mask the configurations before returning them. ConfigurationDefinition resourceConfigurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), group.getResourceType().getId()); + subjectManager.getOverlord(), group.getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); for (Configuration resourceConfiguration : currentPersistedConfigs.values()) { @@ -669,7 +677,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
// Mask the configurations before returning them. ConfigurationDefinition pluginConfigurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), group.getResourceType().getId()); + subjectManager.getOverlord(), group.getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); for (Configuration pluginConfiguration : currentPersistedConfigs.values()) { @@ -690,7 +698,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf }
Query countQuery = PersistenceUtility.createCountQuery(entityManager, - ResourceConfigurationUpdate.QUERY_FIND_BY_GROUP_ID_AND_STATUS); + ResourceConfigurationUpdate.QUERY_FIND_BY_GROUP_ID_AND_STATUS); countQuery.setParameter("groupId", compatibleGroup.getId()); countQuery.setParameter("status", ConfigurationUpdateStatus.INPROGRESS); long count = (Long) countQuery.getSingleResult(); @@ -941,7 +949,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (PluginConfigurationUpdate update : updates) { Configuration configuration = update.getConfiguration(); ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), update.getResource().getResourceType().getId()); + subjectManager.getOverlord(), update.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); }
@@ -1003,7 +1011,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (ResourceConfigurationUpdate update : updates) { Configuration configuration = update.getConfiguration(); ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), update.getResource().getResourceType().getId()); + subjectManager.getOverlord(), update.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); }
@@ -1165,7 +1173,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf }
ResourceConfigurationUpdate newUpdate = configurationManager.persistNewResourceConfigurationUpdateHistory( - subject, resourceId, configToUpdate, ConfigurationUpdateStatus.INPROGRESS, subject.getName(), false); + subject, resourceId, configToUpdate, ConfigurationUpdateStatus.INPROGRESS, subject.getName(), false); executeResourceConfigurationUpdate(newUpdate); return newUpdate; } @@ -1229,8 +1237,9 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf // configuration. // TODO: Consider synchronizing to avoid the condition where someone calls this method twice quickly in two // different tx's, which would put two updates in INPROGRESS and cause havoc. - ResourceConfigurationUpdate newUpdate = configurationManager.persistNewResourceConfigurationUpdateHistory(subject, resourceId, - newResourceConfiguration, ConfigurationUpdateStatus.INPROGRESS, subject.getName(), false); + ResourceConfigurationUpdate newUpdate = configurationManager.persistNewResourceConfigurationUpdateHistory( + subject, resourceId, newResourceConfiguration, ConfigurationUpdateStatus.INPROGRESS, subject.getName(), + false);
executeResourceConfigurationUpdate(newUpdate);
@@ -1400,7 +1409,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
// find the current update request that is persisted - this is the one that is being reported as being complete ResourceConfigurationUpdate update = entityManager.find(ResourceConfigurationUpdate.class, response - .getConfigurationUpdateId()); + .getConfigurationUpdateId()); if (update == null) { throw new IllegalStateException( "The completed request passed in does not match any request for any resource in inventory: " + response); @@ -1434,7 +1443,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf @SuppressWarnings("unchecked") public void checkForCompletedGroupResourceConfigurationUpdate(int resourceConfigUpdateId) { ResourceConfigurationUpdate resourceConfigUpdate = entityManager.find(ResourceConfigurationUpdate.class, - resourceConfigUpdateId); + resourceConfigUpdateId); if (resourceConfigUpdate.getStatus() == ConfigurationUpdateStatus.INPROGRESS) { // If this update isn't done, then, by definition, the group update isn't done either. return; @@ -1537,7 +1546,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf
public boolean hasPluginConfiguration(int resourceTypeId) { Query countQuery = PersistenceUtility.createCountQuery(entityManager, - ConfigurationDefinition.QUERY_FIND_PLUGIN_BY_RESOURCE_TYPE_ID); + ConfigurationDefinition.QUERY_FIND_PLUGIN_BY_RESOURCE_TYPE_ID);
countQuery.setParameter("resourceTypeId", resourceTypeId); long count = (Long) countQuery.getSingleResult(); @@ -1625,14 +1634,14 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf }
public Configuration getConfiguration(Subject subject, int configurationId) { - @SuppressWarnings({"UnnecessaryLocalVariable"}) + @SuppressWarnings( { "UnnecessaryLocalVariable" }) Configuration configuration = getConfigurationById(configurationId); return configuration; }
public Configuration getConfigurationFromDefaultTemplate(ConfigurationDefinition definition) { ConfigurationDefinition managedDefinition = entityManager.find(ConfigurationDefinition.class, definition - .getId()); + .getId()); Configuration configuration = managedDefinition.getDefaultTemplate().getConfiguration(); ConfigurationMaskingUtility.maskConfiguration(configuration, managedDefinition); return configuration; @@ -1918,17 +1927,17 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf public Map<Integer, Configuration> getResourceConfigurationMapForGroupUpdate(Subject subject, Integer groupResourceConfigurationUpdateId) { // this method will perform the CONFIGURE_READ security check for us, no need to keep reference to result - GroupResourceConfigurationUpdate groupResourceConfigurationUpdate = getGroupResourceConfigurationUpdate(subject, - groupResourceConfigurationUpdateId); + GroupResourceConfigurationUpdate groupResourceConfigurationUpdate = getGroupResourceConfigurationUpdate( + subject, groupResourceConfigurationUpdateId);
Tuple<String, Object> groupIdParameter = new Tuple<String, Object>("groupConfigurationUpdateId", groupResourceConfigurationUpdateId); - Map<Integer, Configuration> results = executeGetConfigurationMapQuery(Configuration.QUERY_GET_RESOURCE_CONFIG_MAP_BY_GROUP_UPDATE_ID, 100, - groupIdParameter); + Map<Integer, Configuration> results = executeGetConfigurationMapQuery( + Configuration.QUERY_GET_RESOURCE_CONFIG_MAP_BY_GROUP_UPDATE_ID, 100, groupIdParameter);
// Mask the configurations before returning them. ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), groupResourceConfigurationUpdate.getGroup().getResourceType().getId()); + subjectManager.getOverlord(), groupResourceConfigurationUpdate.getGroup().getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); for (Configuration configuration : results.values()) { @@ -1943,16 +1952,16 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf Integer groupPluginConfigurationUpdateId) { // this method will perform the CONFIGURE_READ security check for us, no need to keep reference to result GroupPluginConfigurationUpdate groupPluginConfigurationUpdate = getGroupPluginConfigurationUpdate(subject, - groupPluginConfigurationUpdateId); + groupPluginConfigurationUpdateId);
Tuple<String, Object> groupIdParameter = new Tuple<String, Object>("groupConfigurationUpdateId", groupPluginConfigurationUpdateId); - Map<Integer, Configuration> results = executeGetConfigurationMapQuery(Configuration.QUERY_GET_PLUGIN_CONFIG_MAP_BY_GROUP_UPDATE_ID, 100, - groupIdParameter); + Map<Integer, Configuration> results = executeGetConfigurationMapQuery( + Configuration.QUERY_GET_PLUGIN_CONFIG_MAP_BY_GROUP_UPDATE_ID, 100, groupIdParameter);
// Mask the configurations before returning them. ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), groupPluginConfigurationUpdate.getGroup().getResourceType().getId()); + subjectManager.getOverlord(), groupPluginConfigurationUpdate.getGroup().getResourceType().getId()); // We do not want the masked configurations persisted, so detach all entities before masking the configurations. entityManager.clear(); for (Configuration configuration : results.values()) { @@ -2004,7 +2013,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf pc.initDefaultOrderingField("modifiedTime", PageOrdering.DESC);
Query query = PersistenceUtility.createQueryWithOrderBy(entityManager, - GroupPluginConfigurationUpdate.QUERY_FIND_BY_GROUP_ID, pc); + GroupPluginConfigurationUpdate.QUERY_FIND_BY_GROUP_ID, pc); Query countQuery = PersistenceUtility.createCountQuery(entityManager, GroupPluginConfigurationUpdate.QUERY_FIND_BY_GROUP_ID); query.setParameter("groupId", groupId); @@ -2045,8 +2054,8 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf }
@SuppressWarnings("unchecked") - public ConfigurationUpdateStatus updateGroupResourceConfigurationUpdateStatus(int groupResourceConfigurationUpdateId, - String errorMessages) { + public ConfigurationUpdateStatus updateGroupResourceConfigurationUpdateStatus( + int groupResourceConfigurationUpdateId, String errorMessages) { GroupResourceConfigurationUpdate groupResourceConfigUpdate = configurationManager .getGroupResourceConfigurationById(groupResourceConfigurationUpdateId);
@@ -2072,9 +2081,9 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf return completeGroupConfigurationUpdate(groupPluginConfigUpdate, updateStatusTuples, errorMessages); }
- private ConfigurationUpdateStatus completeGroupConfigurationUpdate(AbstractGroupConfigurationUpdate groupConfigUpdate, - List<ConfigurationUpdateStatus> memberConfigUpdateStatusTuples, - String errorMessages) { + private ConfigurationUpdateStatus completeGroupConfigurationUpdate( + AbstractGroupConfigurationUpdate groupConfigUpdate, + List<ConfigurationUpdateStatus> memberConfigUpdateStatusTuples, String errorMessages) { ConfigurationUpdateStatus groupConfigUpdateStatus; if (memberConfigUpdateStatusTuples.contains(ConfigurationUpdateStatus.FAILURE) || errorMessages != null) { groupConfigUpdateStatus = ConfigurationUpdateStatus.FAILURE; @@ -2285,7 +2294,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (ResourceConfigurationUpdate update : updates) { Configuration configuration = update.getConfiguration(); ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), update.getResource().getResourceType().getId()); + subjectManager.getOverlord(), update.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); }
@@ -2312,7 +2321,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (PluginConfigurationUpdate update : updates) { Configuration configuration = update.getConfiguration(); ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), update.getResource().getResourceType().getId()); + subjectManager.getOverlord(), update.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); }
@@ -2344,7 +2353,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (ResourceConfigurationUpdate memberUpdate : memberUpdates) { Configuration configuration = memberUpdate.getConfiguration(); ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), memberUpdate.getResource().getResourceType().getId()); + subjectManager.getOverlord(), memberUpdate.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); } } @@ -2378,7 +2387,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf for (PluginConfigurationUpdate memberUpdate : memberUpdates) { Configuration configuration = memberUpdate.getConfiguration(); ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType( - subjectManager.getOverlord(), memberUpdate.getResource().getResourceType().getId()); + subjectManager.getOverlord(), memberUpdate.getResource().getResourceType().getId()); ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition); } } @@ -2387,52 +2396,44 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf return updates; }
- public ConfigurationDefinition getOptionsForConfigurationDefinition(Subject subject, ConfigurationDefinition def) {
- - for (Map.Entry<String,PropertyDefinition> entry : def.getPropertyDefinitions().entrySet()) { + for (Map.Entry<String, PropertyDefinition> entry : def.getPropertyDefinitions().entrySet()) { PropertyDefinition pd = entry.getValue();
if (pd instanceof PropertyDefinitionSimple) { PropertyDefinitionSimple pds = (PropertyDefinitionSimple) pd; handlePDS(subject, pds);
- } - else if (pd instanceof PropertyDefinitionList) { + } else if (pd instanceof PropertyDefinitionList) { PropertyDefinitionList pdl = (PropertyDefinitionList) pd; PropertyDefinition memberDef = pdl.getMemberDefinition(); if (memberDef instanceof PropertyDefinitionSimple) { PropertyDefinitionSimple pds = (PropertyDefinitionSimple) memberDef; handlePDS(subject, pds); - } - else if (memberDef instanceof PropertyDefinitionMap) { + } else if (memberDef instanceof PropertyDefinitionMap) { PropertyDefinitionMap pdm = (PropertyDefinitionMap) memberDef; for (PropertyDefinition inner : pdm.getPropertyDefinitions().values()) { if (inner instanceof PropertyDefinitionSimple) { handlePDS(subject, (PropertyDefinitionSimple) inner); } - log.debug("3 >>>>>>>>>> " + inner.toString() + " in " + pdl.toString() + " <<<<<<< not yet supported"); + log.debug("3 ____[ " + inner.toString() + " in " + pdl.toString() + " ]____ not yet supported"); } - } - else { - log.debug("2 >>>>>>>>>> " + memberDef.toString() + " in " + pdl.toString() + " <<<<<<< not yet supported"); + } else { + log.debug("2 ____[ " + memberDef.toString() + " in " + pdl.toString() + " ]____ not yet supported"); }
- } - else if (pd instanceof PropertyDefinitionMap) { + } else if (pd instanceof PropertyDefinitionMap) { PropertyDefinitionMap pdm = (PropertyDefinitionMap) pd; - for (PropertyDefinition inner : pdm.getPropertyDefinitions().values()) { - if (inner instanceof PropertyDefinitionSimple) { - handlePDS(subject, (PropertyDefinitionSimple) inner); - } - else { - log.debug("4 >>>>>>>>>> " + inner.toString() + " in " + pdm.toString() + " <<<<<<< not yet supported"); - } + for (PropertyDefinition inner : pdm.getPropertyDefinitions().values()) { + if (inner instanceof PropertyDefinitionSimple) { + handlePDS(subject, (PropertyDefinitionSimple) inner); + } else { + log.debug("4 ____[ " + inner.toString() + " in " + pdm.toString() + " ]____ not yet supported"); } - } - else { - log.debug("1 >>>>>>>>>> " + pd.toString() + " <<<<<<< not yet supported"); + } + } else { + log.debug("1 ____[ " + pd.toString() + " ]____ not yet supported"); } }
@@ -2446,51 +2447,50 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf */ private void handlePDS(Subject subject, PropertyDefinitionSimple pds) {
- if (pds.getOptionsSource()!=null) { + if (pds.getOptionsSource() != null) { // evaluate the source parameters PropertyOptionsSource pos = pds.getOptionsSource(); PropertyOptionsSource.TargetType tt = pos.getTargetType(); String expression = pos.getExpression(); - if (tt== PropertyOptionsSource.TargetType.RESOURCE || tt== PropertyOptionsSource.TargetType.CONFIGURATION) { + if (tt == PropertyOptionsSource.TargetType.RESOURCE || tt == PropertyOptionsSource.TargetType.CONFIGURATION) { ResourceCriteria criteria = new ResourceCriteria();
- - if (tt==PropertyOptionsSource.TargetType.CONFIGURATION) { + if (tt == PropertyOptionsSource.TargetType.CONFIGURATION) { // split out expression part for target=configuration // return if no property specifier is given String expr = expression; if (!expr.contains(":")) { - log.warn("Option source expression for property " + pds.getName() + " and target configuration contains no ':'"); + log.warn("Option source expression for property " + pds.getName() + + " and target configuration contains no ':'"); return; } - } - else { + } else { criteria.setSearchExpression(expression); }
- - List<ResourceComposite> composites = resourceManager.findResourceCompositesByCriteria(subject,criteria); + List<ResourceComposite> composites = resourceManager + .findResourceCompositesByCriteria(subject, criteria); for (ResourceComposite composite : composites) {
- if (tt== PropertyOptionsSource.TargetType.RESOURCE) { + if (tt == PropertyOptionsSource.TargetType.RESOURCE) {
- PropertyDefinitionEnumeration pde = new PropertyDefinitionEnumeration(composite.getResource().getName(),""+composite.getResource().getName()); + PropertyDefinitionEnumeration pde = new PropertyDefinitionEnumeration(composite.getResource() + .getName(), "" + composite.getResource().getName()); // TODO filter -- or leave up to search expression?? pds.getEnumeratedValues().add(pde); - } - else if (tt== PropertyOptionsSource.TargetType.CONFIGURATION) { + } else if (tt == PropertyOptionsSource.TargetType.CONFIGURATION) { // for configuration we need to drill down into the resource configuration - if (!handleConfigurationTarget(pds, expression, composite.getResource())) return; + if (!handleConfigurationTarget(pds, expression, composite.getResource())) + return;
} } - } - else if (tt == PropertyOptionsSource.TargetType.GROUP) { + } else if (tt == PropertyOptionsSource.TargetType.GROUP) { // for groups we need to talk to the group manager ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.setSearchExpression(expression);
- resourceGroupManager.findResourceGroupCompositesByCriteria(subject,criteria); + resourceGroupManager.findResourceGroupCompositesByCriteria(subject, criteria); } // TODO plugin and resourceType } @@ -2507,8 +2507,7 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf * @param resource the * @return false if the property can not be resolved, true otherwise */ - private boolean handleConfigurationTarget(PropertyDefinitionSimple pds, String expression, - Resource resource) { + private boolean handleConfigurationTarget(PropertyDefinitionSimple pds, String expression, Resource resource) { Configuration configuration = resource.getResourceConfiguration(); Property p; String propName = expression.substring(0, expression.indexOf(":")); @@ -2525,12 +2524,13 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf return false; } if (!(p instanceof PropertyList)) { - log.warn("Option source expression for property " + pds.getName() + " and target configuration does not point to a list"); + log.warn("Option source expression for property " + pds.getName() + + " and target configuration does not point to a list"); return false; } PropertyList pl = (PropertyList) p; List<Property> propertyList = pl.getList(); - if (propertyList.size()==0) + if (propertyList.size() == 0) return false;
// Now List of simple or list of maps (of simple) ? @@ -2538,30 +2538,31 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf if (propertyList.get(0) instanceof PropertySimple) { if (isMap) { log.warn(" expected a List of Maps, but got a list of simple"); - return false; + return false; }
for (Property tmp : propertyList) { - PropertySimple ps= (PropertySimple) tmp; + PropertySimple ps = (PropertySimple) tmp; String name = ps.getStringValue(); - if (name!=null) { + if (name != null) { PropertyDefinitionEnumeration pde = new PropertyDefinitionEnumeration(name, name); pds.getEnumeratedValues().add(pde); } } - } else if (propertyList.get(0) instanceof PropertyMap) { + } else if (propertyList.get(0) instanceof PropertyMap) { if (!isMap) { log.warn(" expected a List of simple, but got a list of Maps"); return false; } - String subPropName ; + String subPropName; subPropName = propName.substring(propName.indexOf("=") + 1);
for (Property tmp : propertyList) { PropertyMap pm = (PropertyMap) tmp; Property ps = pm.get(subPropName); - if (ps==null) { - log.warn("Option source expression for property " + pds.getName() + " and target configuration does not have a map element " + subPropName); + if (ps == null) { + log.warn("Option source expression for property " + pds.getName() + + " and target configuration does not have a map element " + subPropName); return false; } if (!(ps instanceof PropertySimple)) { @@ -2570,14 +2571,13 @@ public class ConfigurationManagerBean implements ConfigurationManagerLocal, Conf } PropertySimple propertySimple = (PropertySimple) ps; String name = propertySimple.getStringValue(); - if (name!=null) { + if (name != null) { PropertyDefinitionEnumeration pde = new PropertyDefinitionEnumeration(name, name); pds.getEnumeratedValues().add(pde); } } }
- return true; }
commit 690d4b1374b65ba6f7c0430e09664d9cbdc95c98 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 13:54:05 2011 -0400
when eclipse starts gwt dev mode with JPDA, have it set the rpcTimeout to 10 minutes
diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch index 0d61259..a32a17d 100644 --- a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA-Params.launch @@ -6,6 +6,6 @@ <listEntry value="org.eclipse.ui.externaltools.launchGroup"/> </listAttribute> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams=?enableLocators=true#Reports"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams=?enableLocators=true&rpcTimeout=600#Reports"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> </launchConfiguration> diff --git a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch index 959f956..c839e78 100644 --- a/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch +++ b/etc/eclipse-tools/maven/RHQ Maven Build - Run GWT DevMode-JPDA.launch @@ -6,6 +6,6 @@ <listEntry value="org.eclipse.ui.externaltools.launchGroup"/> </listAttribute> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${env_var:M2_HOME}/bin/${MAVEN_EXE}"/> -<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams=#Reports"/> +<stringAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS" value="-o -Dmaven.test.skip=true gwt:debug -DcoreGuiParams=?rpcTimeout=600#Reports"/> <stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/rhq/modules/enterprise/gui/coregui}"/> </launchConfiguration>
commit ab22c77d6430472144c26aacbd362781074a5b28 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 13:25:54 2011 -0400
fix the exception messages
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 d094a67..efddea7 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 @@ -184,7 +184,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme resourceId, label, configuration); if (configuration == null || configuration.getProperties().isEmpty()) { throw new RuntimeException( - "One or more null or empty member connection settings was returned by the Server."); + "The server did not return the configuration for one or more member resources."); } memberConfigurations.add(memberConfiguration); } @@ -212,11 +212,11 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme
public void onSuccess(Void result) { String configHistoryUrl = LinkManager.getResourceGroupTabLink(group.getId(), - ResourceDetailView.Tab.CONFIGURATION, ResourceDetailView.ConfigurationSubTab.HISTORY); + 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 - .view_group_resConfig_edit_saveInitiated_full(group.getResourceType().getName(), group - .getName()), Message.Severity.Info); + .view_group_resConfig_edit_saveInitiated_full(group.getResourceType().getName(), group + .getName()), Message.Severity.Info); CoreGUI.goToView(configHistoryView, message); } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/HistoryGroupResourceConfigurationSettings.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/HistoryGroupResourceConfigurationSettings.java index 37c0965..19b079d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/HistoryGroupResourceConfigurationSettings.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/HistoryGroupResourceConfigurationSettings.java @@ -139,7 +139,7 @@ public class HistoryGroupResourceConfigurationSettings extends LocatableVLayout resourceId, label, configuration); if (configuration == null || configuration.getProperties().isEmpty()) { throw new RuntimeException( - "One or more null or empty member connection settings was returned by the Server."); + "The server did not return the configuration for one or more member resources."); } memberConfigurations.add(memberConfiguration); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/GroupPluginConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/GroupPluginConfigurationEditView.java index 2850187..e5742da 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/GroupPluginConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/GroupPluginConfigurationEditView.java @@ -188,7 +188,7 @@ public class GroupPluginConfigurationEditView extends LocatableVLayout implement resourceId, label, configuration); if (configuration == null || configuration.getProperties().isEmpty()) { throw new RuntimeException( - "One or more null or empty member connection settings was returned by the Server."); + "The server did not return the connection settings for one or more member resources."); } memberConfigurations.add(memberConfiguration); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java index 7496928..c70d5d6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/inventory/HistoryGroupPluginConfigurationSettings.java @@ -138,7 +138,7 @@ public class HistoryGroupPluginConfigurationSettings extends LocatableVLayout { resourceId, label, configuration); if (configuration == null || configuration.getProperties().isEmpty()) { throw new RuntimeException( - "One or more null or empty member connection settings was returned by the Server."); + "The server did not return the connection settings for one or more member resources."); } memberConfigurations.add(memberConfiguration); }
commit f1b6abdf43d67e7b5c433293e69beb6590639b33 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 12:47:09 2011 -0400
[BZ 725930] fix the URL to the JON docs used for the Help > Online Documentation menu item in portal-war (https://bugzilla.redhat.com/show_bug.cgi?id=725930)
diff --git a/modules/enterprise/server/plugins/perspectives/core/perspective/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/perspectives/core/perspective/src/main/resources/META-INF/rhq-serverplugin.xml index 26806e9..928717f 100644 --- a/modules/enterprise/server/plugins/perspectives/core/perspective/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/perspectives/core/perspective/src/main/resources/META-INF/rhq-serverplugin.xml @@ -374,7 +374,7 @@ name="help.onlineDocumentation" displayName="Online Documentation" newWindow="true" - url="http://www.redhat.com/docs/en-US/JBoss_ON/%22%3E + url="http://docs.redhat.com/docs/en-US/JBoss_Operations_Network/%22%3E <position name="help" placement="firstChild" />
commit 5250bcedfd98490f79b394d5bcb73cd414dc3eca Author: John Sanda jsanda@redhat.com Date: Wed Aug 17 12:36:46 2011 -0400
Add support for filtering on directories
If a filter path denotes a directory and no pattern is specified, then it is assumed everything in that directory (including subdirectories) should be considered a match. FilterFileVisitor now has this logic with this commit.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java index 5e22f42..7d0313c 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -24,11 +24,12 @@ import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern;
+import org.apache.commons.io.FilenameUtils; + import org.rhq.core.domain.drift.Filter; import org.rhq.core.util.file.FileVisitor; import org.rhq.core.util.file.PathFilter;
-import static org.apache.commons.io.FilenameUtils.normalize; import static org.rhq.core.util.file.FileUtil.generateRegex;
/** @@ -62,6 +63,9 @@ import static org.rhq.core.util.file.FileUtil.generateRegex; * will not however match things like foo.war/ where foo.war is a directory (i.e., exploded * webapp) since matching is not done on directories. To match the contents of foo.war/ * you could use something like *.war/**. + * <br/><br/> + * If a filter path denotes a directory and if no pattern is specified, then it is assumed + * everything in the directory (including subdirectories) should be considered a match. */ public class FilterFileVisitor implements FileVisitor {
@@ -86,17 +90,46 @@ public class FilterFileVisitor implements FileVisitor { private List<PathFilter> convert(File basedir, List<Filter> filters) { List<PathFilter> pathFilters = new ArrayList<PathFilter>(filters.size()); for (Filter filter : filters) { - File path = new File(filter.getPath()); - if (path.isAbsolute()) { - pathFilters.add(new PathFilter(normalize(path.getAbsolutePath()), filter.getPattern())); - } else { - pathFilters.add(new PathFilter(normalize(new File(basedir, filter.getPath()).getAbsolutePath()), - filter.getPattern())); - } + pathFilters.add(normalize(basedir, filter)); } return pathFilters; }
+ /** + * Besides converting the {@link Filter} into a {@link PathFilter}, this method does a + * couple additional things. If the path is a relative, it is expanded into an absolute + * path. If the path denotes a directory and if no pattern is specified, it is assumed + * that everything under that directory including sub directories should be considered + * matches. + * + * @param basedir The base directory from which drift detection is being done + * @param filter The filter to convert and normalize + * @return The converted and normalized filter + */ + private PathFilter normalize(File basedir, Filter filter) { + File path = new File(filter.getPath()); + File filterPath; + String filterPattern; + + if (path.isAbsolute()) { + filterPath = path; + } else { + filterPath = new File(basedir, filter.getPath()); + } + + if (filterPath.isDirectory() && isEmpty(filter.getPattern())) { + filterPattern = "**/*"; + } else { + filterPattern = filter.getPattern(); + } + + return new PathFilter(FilenameUtils.normalize(filterPath.getAbsolutePath()), filterPattern); + } + + private boolean isEmpty(String s) { + return s == null || s.length() == 0; + } + @Override public void visit(File file) { if (includes.isEmpty() && excludes.isEmpty()) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java index bb8f4dc..80a86ea 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java @@ -178,6 +178,27 @@ public class FilterFileVisitorTest { "Relative paths should be expanded out to full paths"); }
+ @Test + public void includeEverythingWhenPathIsADirectoryAndNoPatternSpecified() throws Exception { + File deployDir = mkdir(basedir, "deploy"); + File serverEar = touch(deployDir, "server.ear"); + File myapp = mkdir(deployDir, "myapp.war"); + File indexHtml = touch(myapp, "index.html"); + + File confDir = mkdir(basedir, "conf"); + File serverConf = touch(confDir, "server.conf"); + + List<Filter> includes = asList(new Filter(deployDir.getAbsolutePath(), null)); + List<Filter> excludes = emptyList(); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(serverEar, indexHtml), visitor.visitedFiles, + "When a filter path specifies a directory and no pattern is specified, all files under that directory, " + + "including subdirectories should be considered a match."); + } + private File mkdir(File parent, String dirName) throws IOException { File dir = new File(parent, dirName); dir.mkdirs();
commit 5025c9410bdbcfa211e6ea21e6fac6a721916c57 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 12:21:26 2011 -0400
[BZ 730122] fix so ugly errors are not emitted when the user tries to view a group that does not exist or that they do not have authz to view, and make sure the wanring message that is emitted is user-friendly (https://bugzilla.redhat.com/show_bug.cgi?id=730122)
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 aa5c5b8..ca9075f 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 @@ -52,6 +52,7 @@ import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTabSelectedE 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.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.inventory.InventoryView; import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.AbstractTwoLevelTabSetView; import org.rhq.enterprise.gui.coregui.client.inventory.common.event.EventCompositeHistoryView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.configuration.GroupResourceConfigurationEditView; @@ -67,6 +68,7 @@ import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.operation.h import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.operation.schedule.GroupOperationScheduleListView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.summary.ActivityView; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -76,6 +78,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Ian Springer */ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<ResourceGroupComposite, ResourceGroupTitleBar> { + public static final String AUTO_CLUSTER_VIEW = "ResourceGroup/AutoCluster"; public static final String AUTO_GROUP_VIEW = "Resource/AutoGroup";
@@ -452,7 +455,6 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource final boolean isAutoGroup = isAutoGroup(); if (isAutoCluster) { criteria.addFilterVisible(false); - } else if (isAutoGroup) { criteria.addFilterVisible(false); criteria.addFilterPrivate(true); @@ -461,14 +463,15 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource GWTServiceLookup.getResourceGroupService().findResourceGroupCompositesByCriteria(criteria, new AsyncCallback<PageList<ResourceGroupComposite>>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_group_detail_failLoadComp(String.valueOf(groupId)), - caught); + Message message = new Message(MSG.view_group_detail_failLoadComp(String.valueOf(groupId)), + Message.Severity.Warning); + CoreGUI.goToView(InventoryView.VIEW_ID.getName(), message); }
public void onSuccess(PageList<ResourceGroupComposite> result) { if (result.isEmpty()) { - CoreGUI.getErrorHandler().handleError( - MSG.view_group_detail_failLoadComp(String.valueOf(groupId))); + //noinspection ThrowableInstanceNeverThrown + onFailure(new Exception("Group with id [" + groupId + "] does not exist.")); } else { groupComposite = result.get(0); loadResourceType(groupComposite, viewPath); @@ -574,4 +577,5 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource super.renderView(viewPath); } } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java index d00f0a6..086cbda 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTopView.java @@ -73,7 +73,7 @@ public class ResourceGroupTopView extends LocatableHLayout implements Bookmarkab detailView = new ResourceGroupDetailView(this.extendLocatorId("AutoClusterDetail"), ResourceGroupDetailView.AUTO_CLUSTER_VIEW); } else { - detailView = new ResourceGroupDetailView(this.extendLocatorId("groupDetail"), this.VIEW_ID.getName()); + detailView = new ResourceGroupDetailView(this.extendLocatorId("groupDetail"), VIEW_ID.getName()); } isAutoClusterView = isAutoClusterPath; this.setContent(detailView); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java index 2321fd3..0b2f45c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java @@ -257,7 +257,7 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka public void setSelectedGroup(final int groupId, boolean isAutoCluster) { ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(groupId); - criteria.addFilterVisible(Boolean.valueOf(!isAutoCluster)); + criteria.addFilterVisible(!isAutoCluster); criteria.fetchResourceType(true);
GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, @@ -269,6 +269,12 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka }
public void onSuccess(PageList<ResourceGroup> result) { + if (result.isEmpty()) { + // This means either that a group with the specified id does not exist or that the user does is + // not authorized to view the group. In either case, just return, and let + // ResourceGroupDetailView.loadSelectedItem() handle emitting an error message. + return; + } ResourceGroup group = result.get(0); ResourceGroupTreeView.this.currentGroup = group;
@@ -685,4 +691,5 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka }
} + } 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 27d834f..f97d6a8 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 @@ -607,14 +607,13 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo public void onFailure(Throwable caught) { Message message = new Message(MSG.view_inventory_resource_loadFailed(String.valueOf(resourceId)), Message.Severity.Warning); - CoreGUI.goToView(InventoryView.VIEW_ID.getName(), message); }
public void onSuccess(PageList<ResourceComposite> result) { if (result.isEmpty()) { //noinspection ThrowableInstanceNeverThrown - onFailure(new Exception(MSG.view_inventory_resource_loadFailed(String.valueOf(resourceId)))); + onFailure(new Exception("Resource with id [" + resourceId + "] does not exist.")); } else { final ResourceComposite resourceComposite = result.get(0); loadResourceType(resourceComposite, viewPath); 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 3523d7b..25544b8 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 @@ -1250,7 +1250,7 @@ view_groupCreateWizard_windowTitle = Create Group view_groupInventoryMembers_button_updateMembership = Update Membership... view_groupInventoryMembers_title_updateMembership = Update Membership view_group_detail_failLoad = Failed to load group for group with ID [{0}] -view_group_detail_failLoadComp = Failed to load group composite for group with ID [{0}] +view_group_detail_failLoadComp = Group with id [{0}] does not exist or is not accessible view_group_detail_failRecursiveChange = Failed to update the recursive setting for group [{0}] view_group_detail_recursiveChange = You successfully changed the recursive setting for group [{0}] view_group_inventory_activity_no_recent_metrics = This group has no recent metrics 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 c1c3dee..5ba4580 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 @@ -1014,7 +1014,7 @@ view_groupCreateWizard_windowTitle = Gruppe anlegen view_groupInventoryMembers_button_updateMembership = Mitgliedschaft aktualisieren... view_groupInventoryMembers_title_updateMembership = Mitgliedschaft aktualisieren view_group_detail_failLoad = Konnte die Gruppe mit der ID [{0}] nicht laden -view_group_detail_failLoadComp = Konnte die Gruppen-Composite fÃŒr die Gruppe mit der ID [{0}] nicht laden. +view_group_detail_failLoadComp = Group with id [{0}] does not exist or is not accessible view_group_detail_failRecursiveChange = Konnte die Einstellung ''Rekursiv'' fÃŒr die Gruppe [{0}] nicht aktualisieren view_group_detail_recursiveChange = Sie haben erfolgreich die ''Rekursiv''-Einstellung fÃŒr die Gruppe [{0}] geÀndert. view_group_meas_schedules_title = Group Metric Collection Schedules~ 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 61d2676..7912b39 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 @@ -1219,7 +1219,7 @@ view_groupCreateWizard_windowTitle = ã°ã«ãŒãäœæ view_groupInventoryMembers_button_updateMembership = ã¡ã³ããŒã·ããã®æŽæ°... view_groupInventoryMembers_title_updateMembership = ã¡ã³ããŒã·ããã®æŽæ° view_group_detail_failLoad = ID [{0}] ã®ä»ããã°ã«ãŒãã®ããŒãã«å€±æããŸãã -view_group_detail_failLoadComp = ID [{0}] ã®ä»ããã°ã«ãŒãã°ã«ãŒãåæã®ããŒãã«å€±æããŸãã +view_group_detail_failLoadComp = Group with id [{0}] does not exist or is not accessible view_group_detail_failRecursiveChange = ã°ã«ãŒã [{0}] ã®ååž°èšå®ã®æŽæ°ã«å€±æããŸãã view_group_detail_recursiveChange = ã°ã«ãŒã [{0}] ã®ååž°èšå®ã®å€æŽã«æåããŸãã view_group_inventory_activity_no_recent_metrics = ãã®ã°ã«ãŒãã¯æè¿ã®ã¡ããªãã¯ã¹ã¯ãããŸãã 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 4068998..25f20f9 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 @@ -1268,7 +1268,7 @@ view_groupCreateWizard_windowTitle = Create Group view_groupInventoryMembers_button_updateMembership = Update Membership... view_groupInventoryMembers_title_updateMembership = Update Membership view_group_detail_failLoad = Failed to load group for group with ID [{0}] -view_group_detail_failLoadComp = Failed to load group composite for group with ID [{0}] +view_group_detail_failLoadComp = Group with id [{0}] does not exist or is not accessible view_group_detail_failRecursiveChange = Failed to update the recursive setting for group [{0}] view_group_detail_recursiveChange = You successfully changed the recursive setting for group [{0}] view_group_inventory_activity_no_recent_metrics = This group has no recent metrics 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 4bda92e..33d7e2b 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 @@ -1227,7 +1227,7 @@ view_groupCreateWizard_windowTitle = \u521b\u5efa\u7ec4 view_groupInventoryMembers_button_updateMembership = \u66f4\u65b0\u6210\u5458\u5173\u7cfb\u4e2d... view_groupInventoryMembers_title_updateMembership = \u66f4\u65b0\u6210\u5458\u5173\u7cfb view_group_detail_failLoad = \u52a0\u8f7d\u7ec4ID\u4e3a[{0}]\u7684\u7ec4\u4fe1\u606f\u5931\u8d25 -view_group_detail_failLoadComp = \u52a0\u8f7d\u7ec4ID\u4e3a[{0}]\u7684\u6df7\u5408\u7ec4\u4fe1\u606f\u5931\u8d25 +view_group_detail_failLoadComp = Group with id [{0}] does not exist or is not accessible view_group_detail_failRecursiveChange = \u4fee\u6539\u7ec4[{0}]\u7684\u9012\u5f52\u8bbe\u7f6e\u5931\u8d25 view_group_detail_recursiveChange = \u6210\u529f\u7684\u4fee\u6539\u7ec4[{0}]\u7684\u9012\u5f52\u8bbe\u7f6e view_group_inventory_activity_no_recent_metrics = \u6b64\u7ec4\u6ca1\u6709\u6700\u65b0\u516c\u544a
commit 1103ffb344561d598dd53661fd4858e987a639f4 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 11:55:15 2011 -0400
[BZ 730112] fix so ugly errors are not emitted when the user tries to view a Resource that does not exist or that they do not have authz to view (https://bugzilla.redhat.com/show_bug.cgi?id=730112)
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 2dda201..27d834f 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 @@ -605,11 +605,10 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo GWTServiceLookup.getResourceService().findResourceCompositesByCriteria(criteria, new AsyncCallback<PageList<ResourceComposite>>() { public void onFailure(Throwable caught) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_inventory_resource_loadFailed(String.valueOf(resourceId)), - Message.Severity.Warning)); + Message message = new Message(MSG.view_inventory_resource_loadFailed(String.valueOf(resourceId)), + Message.Severity.Warning);
- CoreGUI.goToView(InventoryView.VIEW_ID.getName()); + CoreGUI.goToView(InventoryView.VIEW_ID.getName(), message); }
public void onSuccess(PageList<ResourceComposite> result) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java index 68ef419..279ec46 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java @@ -731,7 +731,12 @@ public class ResourceTreeView extends LocatableVLayout { new AsyncCallback<List<ResourceLineageComposite>>() {
public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_tree_common_loadFailed_root(), caught); + boolean resourceDoesNotExist = caught.getMessage().contains("ResourceNotFoundException"); + // If a Resource with the specified id does not exist, don't emit an error, since + // ResourceDetailView.loadSelectedItem() will take care of emitting one. + if (!resourceDoesNotExist) { + CoreGUI.getErrorHandler().handleError(MSG.view_tree_common_loadFailed_root(), caught); + } }
public void onSuccess(List<ResourceLineageComposite> result) { @@ -743,6 +748,11 @@ public class ResourceTreeView extends LocatableVLayout { for (ResourceLineageComposite r : result) { lineage.add(r.getResource()); if (r.isLocked()) { + if (r.getResource().getId() == selectedResourceId) { + // The selected Resource itself is locked. This means the user doesn't have authz to be + // viewing this Resource period, so just abort loading of the tree. + return; + } lockedData.add(r.getResource()); } }
commit fc6fa0e09d7eb15411749ad05c87a5cd3cdc0dee Merge: 5bdcd83 8f7e978 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 17 10:47:32 2011 -0400
Merge commit 'origin/drift' into drift-file-purge
Conflicts: modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java index 014d089,9a435e4..0c00861 --- 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 @@@ -104,8 -104,15 +104,16 @@@ public interface DriftManagerLocal exte * to help reclaim space on the backend. * * @param subject + * @param purgeMillis only those unused drift files that are older than this (in epoch millis) will be purged. * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); + + /** + * Returns the content associated with the specified hash as a string + * + * @param hash The hash the uniquely identifies the requested content + * @return The content as a string + */ + String getDriftFileBits(String hash); } diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java index 8105c82,48e2a33..7142ead --- 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 @@@ -121,8 -121,9 +121,10 @@@ public interface JPADriftServerLocal * to help reclaim space on the backend. * * @param subject + * @param purgeMillis * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); + + String getDriftFileBits(String hash); } diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java index c4118e1,856439d..7a960dd --- 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 @@@ -91,8 -91,15 +91,16 @@@ public interface DriftServerPluginFace * to help reclaim space on the backend. * * @param subject + * @param purgeMillis only those unused drift files that are older than this (in epoch millis) will be purged. * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); + + /** + * Returns the content associated with the specified hash as a string + * + * @param hash The hash the uniquely identifies the requested content + * @return The content as a string + */ + String getDriftFileBits(String hash); } diff --cc modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java index 44e85ca,99abc1c..1dadcb9 --- 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 @@@ -119,7 -119,12 +119,12 @@@ public class JPADriftServerPluginCompon }
@Override - public int purgeOrphanedDriftFiles(Subject subject) { - return getJPADriftServer().purgeOrphanedDriftFiles(subject); + public int purgeOrphanedDriftFiles(Subject subject, long purgeMillis) { + return getJPADriftServer().purgeOrphanedDriftFiles(subject, purgeMillis); } + + @Override + public String getDriftFileBits(String hash) { + return getJPADriftServer().getDriftFileBits(hash); + } }
commit d4c739e7b7bb35cd85f7acbb9b4b37de858cf558 Merge: 86bab7a 6cf655e Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 17 10:30:16 2011 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 6cf655e358a326de37d4287eb7a060c0caba3273 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 10:18:04 2011 -0400
a small optimization to make the code a bit more readable
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 e6cdef4..8f5dbc1 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 @@ -214,11 +214,11 @@ public class GWTServiceLookup { public SessionRpcRequestBuilder(int timeout) { super();
- this.timeout = (timeout <= 0) ? DEFAULT_RPC_TIMEOUT : timeout; - int rpcTimeout = CoreGUI.get().getRpcTimeout(); if (rpcTimeout > -1) { this.timeout = rpcTimeout; + } else { + this.timeout = (timeout <= 0) ? DEFAULT_RPC_TIMEOUT : timeout; }
if (CoreGUI.isDebugMode()) {
commit d4bf16e8f905b6b8db28070a01f459cadc483005 Author: Ian Springer ian.springer@redhat.com Date: Wed Aug 17 10:17:21 2011 -0400
[BZ 725883] in the config unmasking code, handle the case where a particular property exists in the config being unmasked but not in the reference unmasked config; otherwise, such a case would produce an NPE (https://bugzilla.redhat.com/show_bug.cgi?id=725883)
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/util/ConfigurationMaskingUtility.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/util/ConfigurationMaskingUtility.java index 0884fbb..6d18830 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/util/ConfigurationMaskingUtility.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/util/ConfigurationMaskingUtility.java @@ -55,9 +55,9 @@ import java.util.Map; public class ConfigurationMaskingUtility {
/** - * Mask the values of all simple properties of type PASSWORD in the configuration. The configuration does not - * need to be normalized; that is, properties defined by the configuration definition do not need to exist in the - * configuration. + * Mask the values of all simple properties of type PASSWORD in the configuration. The properties are masked by + * calling {@link PropertySimple#mask()}. The configuration does not need to be normalized; that is, properties + * defined by the configuration definition do not need to exist in the configuration. * * @param configuration the configuration to be masked * @param configurationDefinition the configuration definition corresponding to the specified configuration; this is @@ -67,8 +67,9 @@ public class ConfigurationMaskingUtility { public static void maskConfiguration(@NotNull Configuration configuration, @NotNull ConfigurationDefinition configurationDefinition) { - if (configurationDefinition == null) + if (configurationDefinition == null) { return; + }
Map<String, PropertyDefinition> childPropertyDefinitions = configurationDefinition.getPropertyDefinitions(); for (PropertyDefinition childPropertyDefinition : childPropertyDefinitions.values()) { @@ -141,6 +142,10 @@ public class ConfigurationMaskingUtility { // The property doesn't even exist, so there's nothing to unmask. return; } + if (unmaskedParentPropertyMap == null) { + // The parent map does not exist in the unmasked config, so no unmasking is possible. + return; + } if (property instanceof PropertySimple) { PropertySimple propertySimple = (PropertySimple) property; unmaskPropertySimple(propertySimple, unmaskedParentPropertyMap); @@ -178,6 +183,10 @@ public class ConfigurationMaskingUtility { }
private static void unmaskPropertyMap(AbstractPropertyMap propertyMap, PropertyMap unmaskedPropertyMap) { + if (unmaskedPropertyMap == null) { + // The map does not exist in the unmasked config, so no unmasking is possible. + return; + } Map<String, Property> memberProperties = propertyMap.getMap(); for (Property memberProperty : memberProperties.values()) { unmaskProperty(memberProperty.getName(), propertyMap, unmaskedPropertyMap);
commit 8f7e9786a3be02fa7d593ac89378bd289d8b35c2 Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 16 11:49:17 2011 -0400
opps.. used wrong prop name - forgot "Server"
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 45c9729..1202d66 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 @@ -527,8 +527,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Security -view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. 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 5114451..dab0660 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 @@ -458,8 +458,8 @@ view_admin_downloads_cli_md5 = MD5 PrÃŒfsumme des CLI view_admin_downloads_cli_version = Version des CLI view_admin_landing = In dieser Sektion können die globalen Einstellungen fÃŒr RHQ verwaltet werden. Dies schlieÃt Sicherheitseinstellungen und Plugins ein, sowie die Verwaltung der RHQ Server- und Agentplugins. view_admin_security = Sicherheit -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die Àlter sind als view_admin_systemSettings_AvailabilityPurge_name = Lösche VerfÃŒgbarkeitsdaten, die Àlter sind als view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die Àlter sind als 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 fe2b270..6d346b1 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 @@ -522,8 +522,8 @@ view_admin_measTemplates_title = ãã³ãã¬ãŒãã¡ããªãã¯åéã¹ã± view_admin_measTemplates_updateExisting_title = æ¢åã¹ã±ãžã¥ãŒã«ã®æŽæ° view_admin_measTemplates_updateExisting_tooltip = ãã®ããã¯ã¹ããã§ãã¯ãããšããã®ã¿ã€ãã®ãã¹ãŠã®ãªãœãŒã¹ã察象ã«éžæããã¡ããªãã¯ã¹ã®åéã¹ã±ãžã¥ãŒã«ãæŽæ°ããŸããããããããã§ãã¯ãããŠããªããã°ããã³ãã¬ãŒãã¹ã±ãžã¥ãŒã«ãå°æ¥çã«ã€ã³ãã³ããªã«è¿œå ããããã®ã¿ã€ãã®æ°èŠãªãœãŒã¹ã«é©çšãããã ãã§ãã view_admin_security = ã»ãã¥ãªã㣠-##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = ãããšãŒãžã§ã³ãããäœãåä¿¡ããªãã§ãã®æéãçµéãããªãã°ããã®ãšãŒãžã§ã³ãã¯ããŠã³ãããã®ãšèŠãªãããŸãããã®å€ã¯ååäœã§æå®ãããŸãã view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = 蚱容ãããæ倧ç¡éä¿¡æé view_admin_systemSettings_AlertPurge_desc = ããŒã¿ããŒã¹ããé€å»ãããåã®ã¢ã©ãŒããã¹ããªã®ä¿ææéãããã¯æ¥åäœã§æå®ãããŸãã 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 8cff968..ed95acd 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 @@ -538,8 +538,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Seguran\u00E7a -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. 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 2b71193..f954437 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 @@ -521,8 +521,8 @@ view_admin_measTemplates_title = \u6a21\u677f\u6307\u6807\u96c6\u8ba1\u5212\u4ef view_admin_measTemplates_updateExisting_title = \u66f4\u65b0\u5b58\u5728\u7684\u8ba1\u5212\u4efb\u52a1 view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = \u5b89\u5168 -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = \u4ee3\u7406\u6700\u591a\u5141\u8bb8\u9759\u9ed8\u65f6\u95f4 view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days.
commit acce52afcd73b6cbed3ab64ec16f7c83d61a32ad Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 16 11:43:42 2011 -0400
clean up active drift plugin system settings - make i18n messages, remove unused constant
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java index 5804f9d..01d0260 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java @@ -105,7 +105,6 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu String LDAPBindPW = "CAM_LDAP_BIND_PW";
String ACTIVE_DRIFT_PLUGIN = "ACTIVE_DRIFT_PLUGIN"; - String DRIFT_PLUGINS = "DRIFT_PLUGINS"; }
public SystemSettingsView(String locatorId) { @@ -309,11 +308,10 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu * be converted to the types the definition will expect - for example, * the JAAS setting will not be "LDAP" or "JDBC" as the server would know it, * rather the value will be "true" or "false" (i.e. is ldap enabled or not?) - * + * @param driftPlugins the set of drift server plugins that are currently deployed * @return system settings config def */ - private ConfigurationDefinition getSystemSettingsDefinition(Configuration config, - Map<String, String> driftPlugins) { + private ConfigurationDefinition getSystemSettingsDefinition(Configuration config, Map<String, String> driftPlugins) { ConfigurationDefinition def = new ConfigurationDefinition("sysset", MSG.view_adminConfig_systemSettings());
/////////////////////////////////// @@ -530,20 +528,19 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu /////////////////////////////////////////// // Drift Server Configuration Properties // /////////////////////////////////////////// - PropertyGroupDefinition driftGroup = new PropertyGroupDefinition("drift server"); - driftGroup.setDisplayName("Drift Server Configuration Settings"); + PropertyGroupDefinition driftGroup = new PropertyGroupDefinition("drift"); + driftGroup.setDisplayName(MSG.view_admin_systemSettings_group_drift()); driftGroup.setOrder(4); driftGroup.setDefaultHidden(false);
- PropertyDefinitionSimple activeDriftServer = new PropertyDefinitionSimple("ACTIVE_DRIFT_PLUGIN", - "The drift server plugin that manages the persistence of drift-related entities and content", true, - PropertySimpleType.STRING); - activeDriftServer.setDisplayName("Active Drift Server Plugin"); + PropertyDefinitionSimple activeDriftServer = new PropertyDefinitionSimple(Constant.ACTIVE_DRIFT_PLUGIN, MSG + .view_admin_systemSettings_ActiveDriftServerPlugin_desc(), true, PropertySimpleType.STRING); + activeDriftServer.setDisplayName(MSG.view_admin_systemSettings_ActiveDriftServerPlugin_name()); activeDriftServer.setPropertyGroupDefinition(driftGroup);
List<PropertyDefinitionEnumeration> options = new ArrayList<PropertyDefinitionEnumeration>(); for (Map.Entry<String, String> entry : driftPlugins.entrySet()) { - options.add(new PropertyDefinitionEnumeration(entry.getValue(), entry.getKey())) ; + options.add(new PropertyDefinitionEnumeration(entry.getValue(), entry.getKey())); }
activeDriftServer.setEnumeratedValues(options, false); 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 3523d7b..45c9729 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 @@ -527,6 +527,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Security +view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -580,6 +582,7 @@ view_admin_systemSettings_cannotLoadSettings = Cannot obtain the current system view_admin_systemSettings_fixBeforeSaving = Please fix the invalid values before saving view_admin_systemSettings_group_baseline = Automatic Baseline Configuration Properties view_admin_systemSettings_group_dataMgr = Data Manager Configuration Properties +view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = General Configuration Properties view_admin_systemSettings_group_ldap = LDAP Configuration Properties view_admin_systemSettings_saveFailure = Failed to save the system settings 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 c1c3dee..5114451 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 @@ -458,9 +458,12 @@ view_admin_downloads_cli_md5 = MD5 PrÃŒfsumme des CLI view_admin_downloads_cli_version = Version des CLI view_admin_landing = In dieser Sektion können die globalen Einstellungen fÃŒr RHQ verwaltet werden. Dies schlieÃt Sicherheitseinstellungen und Plugins ein, sowie die Verwaltung der RHQ Server- und Agentplugins. view_admin_security = Sicherheit +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die Àlter sind als view_admin_systemSettings_AvailabilityPurge_name = Lösche VerfÃŒgbarkeitsdaten, die Àlter sind als view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die Àlter sind als +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_saveFailure = Das Speichern der Systemeinstellungen ist fehlgeschlagen view_admin_systemSettings_savedSettings = Sie haben die Systemeinstellungen erfolgreich gespeichert view_admin_systemSettings_serverDetails_currentTable = Aktuelle Datenbanktablee fÃŒr Metrikdaten 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 61d2676..fe2b270 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 @@ -522,6 +522,8 @@ view_admin_measTemplates_title = ãã³ãã¬ãŒãã¡ããªãã¯åéã¹ã± view_admin_measTemplates_updateExisting_title = æ¢åã¹ã±ãžã¥ãŒã«ã®æŽæ° view_admin_measTemplates_updateExisting_tooltip = ãã®ããã¯ã¹ããã§ãã¯ãããšããã®ã¿ã€ãã®ãã¹ãŠã®ãªãœãŒã¹ã察象ã«éžæããã¡ããªãã¯ã¹ã®åéã¹ã±ãžã¥ãŒã«ãæŽæ°ããŸããããããããã§ãã¯ãããŠããªããã°ããã³ãã¬ãŒãã¹ã±ãžã¥ãŒã«ãå°æ¥çã«ã€ã³ãã³ããªã«è¿œå ããããã®ã¿ã€ãã®æ°èŠãªãœãŒã¹ã«é©çšãããã ãã§ãã view_admin_security = ã»ãã¥ãªã㣠+##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = ãããšãŒãžã§ã³ãããäœãåä¿¡ããªãã§ãã®æéãçµéãããªãã°ããã®ãšãŒãžã§ã³ãã¯ããŠã³ãããã®ãšèŠãªãããŸãããã®å€ã¯ååäœã§æå®ãããŸãã view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = 蚱容ãããæ倧ç¡éä¿¡æé view_admin_systemSettings_AlertPurge_desc = ããŒã¿ããŒã¹ããé€å»ãããåã®ã¢ã©ãŒããã¹ããªã®ä¿ææéãããã¯æ¥åäœã§æå®ãããŸãã @@ -575,6 +577,7 @@ view_admin_systemSettings_cannotLoadSettings = çŸåšã®ã·ã¹ãã èšå®ãå view_admin_systemSettings_fixBeforeSaving = ä¿ååã«ç¡å¹ãªå€ãä¿®æ£ããŠãã ãã view_admin_systemSettings_group_baseline = èªåããŒã¹ã©ã€ã³æ§æãããã㣠view_admin_systemSettings_group_dataMgr = ããŒã¿ãããŒãžã£ãŒæ§æãããã㣠+##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = å šäœæ§æãããã㣠view_admin_systemSettings_group_ldap = LDAPæ§æãããã㣠view_admin_systemSettings_saveFailure = ã·ã¹ãã èšå®ã®ä¿åã«å€±æããŸãã 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 4068998..8cff968 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 @@ -538,6 +538,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Seguran\u00E7a +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -591,6 +593,7 @@ view_admin_systemSettings_cannotLoadSettings = Cannot obtain the current system view_admin_systemSettings_fixBeforeSaving = Please fix the invalid values before saving view_admin_systemSettings_group_baseline = Automatic Baseline Configuration Properties view_admin_systemSettings_group_dataMgr = Data Manager Configuration Properties +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = General Configuration Properties view_admin_systemSettings_group_ldap = LDAP Configuration Properties view_admin_systemSettings_saveFailure = Failed to save the system settings 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 4bda92e..2b71193 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 @@ -521,6 +521,8 @@ view_admin_measTemplates_title = \u6a21\u677f\u6307\u6807\u96c6\u8ba1\u5212\u4ef view_admin_measTemplates_updateExisting_title = \u66f4\u65b0\u5b58\u5728\u7684\u8ba1\u5212\u4efb\u52a1 view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = \u5b89\u5168 +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = \u4ee3\u7406\u6700\u591a\u5141\u8bb8\u9759\u9ed8\u65f6\u95f4 view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -574,6 +576,7 @@ view_admin_systemSettings_cannotLoadSettings = \u65e0\u6cd5\u83b7\u5f97\u5f53\u5 view_admin_systemSettings_fixBeforeSaving = \u4fdd\u5b58\u524d\u8bf7\u4fee\u590d\u9519\u8bef view_admin_systemSettings_group_baseline = \u81ea\u52a8Baseline\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_group_dataMgr = \u6570\u636e\u7ba1\u7406\u5668\u57fa\u672c\u5c5e\u6027 +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = \u57fa\u672c\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_group_ldap = LDAP\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_saveFailure = \u4fdd\u5b58\u7cfb\u7edf\u5c5e\u6027\u5931\u8d25
commit 86bab7aae142bc806d9d60ef7cdd9690d1b96cab Merge: 3c15c6f f022730 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 17 09:22:56 2011 -0400
Merge branch 'drift'
commit f0227303da27805124adf2c60766faaa236c1f55 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 16 22:44:51 2011 -0400
Fast click resource tree nav work It remains to be seen if this gives us coverage from the problem but the main issue I found, and have tried to resolve is the following: After clicking a node in the tree, and prior to that detail view being able to establish its subtab views, the user navigates to another node in the tree. Navigating between resource and autogroup nodes seems to exacerbate the problem.
I've identified the point in the rendering of the detail view where, once completed, it should be safe to click in the tree. There were two approaches I tried locally to solve the issue. The first was to catch and swallow exceptions thrown due to quick nav. This worked well with one exception, it cause some widgets to fail being destroyed, get detached and then render in the top left corner of the GUI. I could not find a good way to lazily clean that up. The second, implemented here, is preventative. Disable the tree until we get past the safety point in rendering the detail view.
Whether this is irritatig or not remains to be seen, but at the moment I don't see an alternative nor does the disable period seem obtrusive. This is accomplished by using a listener approach, where the Top view registers a listener with the detail view, and re-enables the tree when the detail view says it has rendered.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java index eb6883a..5f1833f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.common.detail;
+import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -213,7 +214,15 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo
} else { // Same Resource - just switch tabs. - this.selectTab(this.tabName, this.subTabName, viewPath); + // + // until we finish the following work we're susceptible to fast-click issues in + // tree navigation. So, wait until after it's done to notify listeners thatthe view is + // safely rendered. Make sure to notify even on failure. + try { + this.selectTab(this.tabName, this.subTabName, viewPath); + } finally { + notifyViewRenderedListeners(); + } } }
@@ -225,6 +234,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo * @param viewPath the view path, which may have additional view items to be rendered */ public void selectTab(String tabName, String subtabName, ViewPath viewPath) { + try { TwoLevelTab tab = (tabName != null) ? this.tabSet.getTabByName(tabName) : null; SubTab subtab = null; @@ -334,4 +344,20 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo super.destroy(); }
+ public interface ViewRenderedListener { + void onViewRendered(); + } + + private List<ViewRenderedListener> viewRenderedListeners = new ArrayList<ViewRenderedListener>(); + + public void addViewRenderedListener(ViewRenderedListener listener) { + viewRenderedListeners.add(listener); + } + + protected void notifyViewRenderedListeners() { + for (ViewRenderedListener listener : viewRenderedListeners) { + listener.onViewRendered(); + } + } + } 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 fb52d42..aa5c5b8 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 @@ -516,14 +516,25 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypeLoadedCallback() { public void onTypesLoaded(ResourceType type) { - group.setResourceType(type); - updateTabContent(groupComposite); - selectTab(getTabName(), getSubTabName(), viewPath); + // until we finish the following work we're susceptible to fast-click issues in + // tree navigation. So, wait until after it's done to notify listeners that the view is + // safely rendered. Make sure to notify even on failure. + try { + group.setResourceType(type); + updateTabContent(groupComposite); + selectTab(getTabName(), getSubTabName(), viewPath); + } finally { + notifyViewRenderedListeners(); + } } }); } else { - updateTabContent(groupComposite); - selectTab(getTabName(), getSubTabName(), viewPath); + try { + updateTabContent(groupComposite); + selectTab(getTabName(), getSubTabName(), viewPath); + } finally { + notifyViewRenderedListeners(); + } } }
@@ -563,5 +574,4 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource super.renderView(viewPath); } } - } 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 705ce9b..2dda201 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 @@ -650,9 +650,16 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), new ResourceTypeRepository.TypeLoadedCallback() { public void onTypesLoaded(ResourceType type) { - resourceComposite.getResource().setResourceType(type); - updateTabContent(resourceComposite); - selectTab(getTabName(), getSubTabName(), viewPath); + // until we finish the following work we're susceptible to fast-click issues in + // tree navigation. So, wait until after it's done to notify listeners thatthe view is + // safely rendered. Make sure to notify even on failure. + try { + resourceComposite.getResource().setResourceType(type); + updateTabContent(resourceComposite); + selectTab(getTabName(), getSubTabName(), viewPath); + } finally { + notifyViewRenderedListeners(); + } } }); } @@ -667,5 +674,4 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo } return false; } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java index a1a80ee..04c55c1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTopView.java @@ -34,7 +34,7 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie
private Canvas contentCanvas; private ResourceTreeView treeView; - private ResourceDetailView detailView = new ResourceDetailView(extendLocatorId("Detail")); + private ResourceDetailView detailView; private ResourceGroupDetailView autoGroupDetailView;
public ResourceTopView(String locatorId) { @@ -49,7 +49,7 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie contentCanvas = new Canvas(); addMember(contentCanvas);
- setContent(detailView); + setToDetailView(); }
public void setContent(Canvas newContent) { @@ -60,27 +60,54 @@ public class ResourceTopView extends LocatableHLayout implements BookmarkableVie this.contentCanvas.markForRedraw(); }
+ private void setToDetailView() { + + this.detailView = new ResourceDetailView(extendLocatorId("Detail")); + this.detailView.addViewRenderedListener(new ResourceDetailView.ViewRenderedListener() { + + public void onViewRendered() { + // re-enable the tree, the detail view has (hopefully) been safely rendered + treeView.enable(); + } + }); + this.setContent(detailView); + this.autoGroupDetailView = null; + } + + private void setToAutoGroupView() { + this.autoGroupDetailView = new ResourceGroupDetailView(this.extendLocatorId("AutoGroupDetail"), + ResourceGroupDetailView.AUTO_GROUP_VIEW); + this.autoGroupDetailView.addViewRenderedListener(new ResourceGroupDetailView.ViewRenderedListener() { + + public void onViewRendered() { + // re-enable the tree, the autogroup view has (hopefully) been safely rendered + treeView.enable(); + } + }); + + this.setContent(this.autoGroupDetailView); + this.detailView = null; + } + public void renderView(ViewPath viewPath) { + // disable the tree until it's safe to click a new node to prevent fast-click issues + this.treeView.disable(); + if ("AutoGroup".equals(viewPath.getCurrent().getPath())) { if (null == autoGroupDetailView) { - this.autoGroupDetailView = new ResourceGroupDetailView(this.extendLocatorId("AutoGroupDetail"), - ResourceGroupDetailView.AUTO_GROUP_VIEW); - this.setContent(this.autoGroupDetailView); - this.detailView = null; + setToAutoGroupView(); } + this.treeView.renderView(viewPath); this.autoGroupDetailView.renderView(viewPath.next()); } else { - // Resource if (null == detailView) { - this.detailView = new ResourceDetailView(extendLocatorId("Detail")); - this.setContent(this.detailView); - this.autoGroupDetailView = null; + setToDetailView(); } + this.treeView.renderView(viewPath); this.detailView.renderView(viewPath); }
} - }
commit 6a5ccf58db335f2098e6396952b5ba33d5724d8d Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 16 16:03:03 2011 -0400
Fix a GWT Error (null issue) in the class setup
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tagging/TagEditorView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tagging/TagEditorView.java index ac289a2..1d2e38b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tagging/TagEditorView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tagging/TagEditorView.java @@ -96,6 +96,7 @@ public class TagEditorView extends LocatableLayout { this.readOnly = readOnly; this.callback = callback;
+ // create the following widgets once and re-use as needed tagTitleLabel = new HTMLFlow("<b>" + MSG.view_tags_tags() + ":</b>"); tagTitleLabel.setAutoWidth();
@@ -131,24 +132,27 @@ public class TagEditorView extends LocatableLayout { }
private void setup() { - // remove old members - removeMember(tagTitleLabel); + // destroy dated tagLayouts if (tagLayouts != null) { for (LocatableHLayout tagLayout : tagLayouts) { removeMember(tagLayout); tagLayout.destroy(); } } - if (addImg != null) { - removeMember(addImg); + // remove remaining members + for (Canvas canvas : getMembers()) { + removeMember(canvas); }
- // add new members + // [re]build + addMember(tagTitleLabel); + tagLayouts = createTagLayouts(); for (LocatableHLayout tagLayout : tagLayouts) { addMember(tagLayout); } + if (!readOnly) { addMember(addImg); tagInputDialog.place(addImg);
commit 3cf0155a88de78f3df2d3bd28195dccd18131645 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 16 16:01:53 2011 -0400
trivial - suppress unchecked warnings classwide for some Table classes
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java index 3223cad..8c4ee37 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java @@ -57,6 +57,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Greg Hinkle * @author John Mazzitelli */ +@SuppressWarnings("unchecked") public abstract class AbstractTableSection<DS extends RPCDataSource, ID> extends Table<DS> implements BookmarkableView {
private VLayout detailsHolder; 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 0572369..2ae4ee2 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 @@ -100,6 +100,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Greg Hinkle * @author Ian Springer */ +@SuppressWarnings("unchecked") public class Table<DS extends RPCDataSource> extends LocatableHLayout implements RefreshableView {
protected static final String FIELD_ID = "id"; @@ -644,7 +645,6 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements // 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. - @SuppressWarnings("unchecked") private static void addCriteria(Criteria dest, Criteria src) { Map otherMap = src.getValues(); Set otherKeys = otherMap.keySet();
commit b61ab9e248290c663f3bf4ff5955fdfb0c50d744 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 16 16:01:14 2011 -0400
GUI Stability - Tab Infra - Add current history token to TwoLevelTabSelectedEvent to ensure the current history at event time is applied consistently. - Set ToolStrip to LocatableToolStrip which has enhanced destruction capabality.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java index d1ed776..edac8e6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/SubTabLayout.java @@ -25,6 +25,7 @@ import java.util.Set;
import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; +import com.google.gwt.user.client.History; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.SelectionType; import com.smartgwt.client.widgets.Button; @@ -35,6 +36,7 @@ import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** @@ -65,7 +67,7 @@ public class SubTabLayout extends LocatableVLayout { setMargin(0); setPadding(0);
- buttonBar = new ToolStrip(); + buttonBar = new LocatableToolStrip(extendLocatorId("ButtonBar")); buttonBar.setBackgroundColor("grey"); buttonBar.setWidth100(); buttonBar.setBorder(null); @@ -291,7 +293,7 @@ public class SubTabLayout extends LocatableVLayout {
public void fireSubTabSelection() { TwoLevelTabSelectedEvent event = new TwoLevelTabSelectedEvent("?", getCurrentSubTab().getName(), -1, - getCurrentCanvas()); + getCurrentCanvas(), History.getToken()); hm.fireEvent(event); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSelectedEvent.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSelectedEvent.java index 5f2b2ab..9cbaa53 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSelectedEvent.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSelectedEvent.java @@ -30,16 +30,16 @@ public class TwoLevelTabSelectedEvent extends GwtEvent<TwoLevelTabSelectedHandle
private String id; private String subTabId; - private int tabNum; - private Canvas subTabPane; + private String historyToken;
- public TwoLevelTabSelectedEvent(String id, String subTabId, int tabNum, Canvas subTabPane) { + public TwoLevelTabSelectedEvent(String id, String subTabId, int tabNum, Canvas subTabPane, String historyToken) { this.id = id; this.subTabId = subTabId; this.tabNum = tabNum; this.subTabPane = subTabPane; + this.historyToken = historyToken; }
public String getId() { @@ -74,6 +74,13 @@ public class TwoLevelTabSelectedEvent extends GwtEvent<TwoLevelTabSelectedHandle this.subTabPane = subTabPane; }
+ public String getHistoryToken() { + return historyToken; + } + + public void setHistoryToken(String historyToken) { + this.historyToken = historyToken; + }
@Override public Type<TwoLevelTabSelectedHandler> getAssociatedType() { @@ -85,5 +92,4 @@ public class TwoLevelTabSelectedEvent extends GwtEvent<TwoLevelTabSelectedHandle handler.onTabSelected(this); }
- } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java index 6329f67..6978045 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/tab/TwoLevelTabSet.java @@ -23,6 +23,7 @@ import java.util.Map;
import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; +import com.google.gwt.user.client.History; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.tab.Tab; import com.smartgwt.client.widgets.tab.events.TabSelectedEvent; @@ -124,7 +125,8 @@ public class TwoLevelTabSet extends NamedTabSet implements TabSelectedHandler, T SubTab currentSubTab = tab.getLayout().getCurrentSubTab(); if (null != currentSubTab) { TwoLevelTabSelectedEvent event = new TwoLevelTabSelectedEvent(tab.getName(), tab.getLayout() - .getCurrentSubTab().getName(), tabSelectedEvent.getTabNum(), tab.getLayout().getCurrentCanvas()); + .getCurrentSubTab().getName(), tabSelectedEvent.getTabNum(), tab.getLayout().getCurrentCanvas(), + History.getToken()); m.fireEvent(event); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java index 047f5af..eb6883a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.smartgwt.client.types.Side; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.layout.Layout; @@ -140,9 +139,11 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo // we want to prevent user initiation of another tab change. To block users from clicking tabs we // disable the tab set. We re-enable the tabset when safe. (see this method and also selectTab()).
+ String historyToken = tabSelectedEvent.getHistoryToken(); + if (getSelectedItemId() == null) { this.tabSet.disable(); - CoreGUI.goToView(History.getToken()); + CoreGUI.goToView(historyToken);
} else { String tabId = tabSelectedEvent.getId(); @@ -153,7 +154,7 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo // If the selected tab or subtab is not already the current history item, the user clicked on the tab, rather // than going directly to the tab's URL. In this case, fire a history event to go to the tab and make it the // current history item. - if (!(History.getToken().equals(path) || History.getToken().startsWith(path + "/"))) { + if (!(historyToken.equals(path) || historyToken.startsWith(path + "/"))) { this.tabSet.disable(); CoreGUI.goToView(path);
commit b06d1811c26d285ca30101bcb3b8d775951da2b1 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 15 17:36:18 2011 -0400
Fast Click Problem Work Fast clicking in the UI has caused various exceptions. We think it may be due, in part, to a bad assumption made in various parts of the code. And that is that the current history token (History.getToken()) has not changed since the widget has been instantiated. If the widget is still initializing while the user navigates away the assumption may be invalid.
This is the first of at least two checkins removing the bad approach. This one works solely on changing portlet creation, which relied heavily on this technique, specifically in the resource and group portlets in the Activity subtabs.
The general approach is to push more information into the constructors/factories in the shape of EntityContext objects. The EntityContext itself has been beefed up slightly to be able to represent better AutoGroup and AutoCluster groups, as well as had a few convenience methods added.
Also: - Fixed a problem in Drift Facet/Subtab handling - Removed the assumption from portlets that bundles can only be deployed to platforms. -- Added new Bundle Facet
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/common/EntityContext.java b/modules/core/domain/src/main/java/org/rhq/core/domain/common/EntityContext.java index a18aa5c..c06c812 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/common/EntityContext.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/common/EntityContext.java @@ -41,7 +41,7 @@ public class EntityContext implements Serializable { Resource, // ResourceTemplate, // ResourceGroup, // - AutoGroup, // + AutoGroup, // TODO: Deprecated, used in portal war SubsystemView; }
@@ -52,9 +52,33 @@ public class EntityContext implements Serializable { public int parentResourceId; public int resourceTypeId;
+ // further decoration available for the ResourceGroup context + private boolean isAutoCluster = false; + private boolean isAutoGroup = false; + public EntityContext() { }
+ public boolean isResource() { + return Type.Resource == type; + } + + public boolean isResourceGroup() { + return Type.ResourceGroup == type; + } + + public boolean isAutoCluster() { + return Type.ResourceGroup == type && isAutoCluster; + } + + public boolean isAutoGroup() { + return Type.ResourceGroup == type && isAutoGroup; + } + + public boolean isSubsystemView() { + return Type.SubsystemView == type; + } + public Type getType() { return type; } @@ -109,6 +133,14 @@ public class EntityContext implements Serializable { return new EntityContext(null, groupId, null, null); }
+ public static EntityContext forGroup(int groupId, boolean isAutoCluster, boolean isAutoGroup) { + EntityContext context = new EntityContext(null, groupId, null, null); + context.isAutoCluster = isAutoCluster; + context.isAutoGroup = isAutoGroup; + return context; + } + + // TODO: deprecated public static EntityContext forAutoGroup(int parentResourceId, int resourceTypeId) { return new EntityContext(null, null, parentResourceId, resourceTypeId); } 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 1401f24..777d2fb 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,8 @@ 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(driftConfig) FROM rt.driftConfigurationTemplates driftConfig)," // drift + + " (SELECT COUNT(bundleConfig) FROM rt.bundleConfiguration bundleConfig)" // bundle + " ) " // + " FROM ResourceType rt " // + " WHERE rt.deleted = false AND ( rt.id = :resourceTypeId OR :resourceTypeId IS NULL )"), @@ -398,8 +399,7 @@ public class ResourceType implements Serializable, Comparable<ResourceType> { private BundleType bundleType;
@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)) + @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>();
// note that this is mapped to a Configuration entity, which is what it really is. However, our getter/setter diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceTypeFacet.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceTypeFacet.java index 93da489..972b3e4 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceTypeFacet.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceTypeFacet.java @@ -24,5 +24,5 @@ package org.rhq.core.domain.resource; * @author Ian Springer */ public enum ResourceTypeFacet { - MEASUREMENT, EVENT, PLUGIN_CONFIGURATION, CONFIGURATION, OPERATION, CONTENT, CALL_TIME, SUPPORT, DRIFT + MEASUREMENT, EVENT, PLUGIN_CONFIGURATION, CONFIGURATION, OPERATION, CONTENT, CALL_TIME, SUPPORT, DRIFT, BUNDLE } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java index fde4efe..5a8ab41 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java @@ -38,8 +38,9 @@ public class ResourceFacets implements Serializable { private static final long serialVersionUID = 1L;
public static ResourceFacets NONE = new ResourceFacets(-1, false, false, false, false, false, false, false, false, - false); - public static ResourceFacets ALL = new ResourceFacets(-1, true, true, true, true, true, true, true, true, true); + false, false); + public static ResourceFacets ALL = new ResourceFacets(-1, true, true, true, true, true, true, true, true, true, + true);
private int resourceTypeId; private boolean measurement; @@ -51,6 +52,7 @@ public class ResourceFacets implements Serializable { private boolean callTime; private boolean support; private boolean drift; + private boolean bundle; private Set<ResourceTypeFacet> facets;
// no-arg constructor required by GWT compiler @@ -58,7 +60,8 @@ public class ResourceFacets implements Serializable { }
public ResourceFacets(int resourceTypeId, boolean measurement, boolean event, boolean pluginConfiguration, - boolean configuration, boolean operation, boolean content, boolean callTime, boolean support, boolean drift) { + boolean configuration, boolean operation, boolean content, boolean callTime, boolean support, boolean drift, + boolean bundle) { this.resourceTypeId = resourceTypeId; this.measurement = measurement; this.event = event; @@ -69,11 +72,13 @@ public class ResourceFacets implements Serializable { this.callTime = callTime; this.support = support; this.drift = drift; + this.bundle = bundle; initEnum(); }
public ResourceFacets(int resourceTypeId, Number measurement, Number event, Number pluginConfiguration, - Number configuration, Number operation, Number content, Number callTime, Number support, Number drift) { + Number configuration, Number operation, Number content, Number callTime, Number support, Number drift, + Number bundle) { this.resourceTypeId = resourceTypeId; this.measurement = measurement.intValue() != 0; this.event = event.intValue() != 0; @@ -84,6 +89,7 @@ public class ResourceFacets implements Serializable { this.callTime = callTime.intValue() != 0; this.support = support.intValue() != 0; this.drift = drift.intValue() != 0; + this.bundle = bundle.intValue() != 0; initEnum(); }
@@ -175,6 +181,17 @@ public class ResourceFacets implements Serializable { }
/** + * Does this resource expose bundle deploy capability? If so, the Bundle sub-tab will be displayed in the GUI + * (TODO: this is not currently implemented but we have other needs for knowning whether a type supports + * bundle deployment. + * + * @return true if the resource allows bundle deployment, false otherwise + */ + public boolean isBundle() { + return bundle; + } + + /** * Returns an enum representation of the facets. * * @return an enum representation of the facets @@ -203,6 +220,7 @@ public class ResourceFacets implements Serializable { this.facets.add(ResourceTypeFacet.SUPPORT); if (drift) this.facets.add(ResourceTypeFacet.DRIFT); - + if (bundle) + this.facets.add(ResourceTypeFacet.BUNDLE); } } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java index 33d8890..47773b1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardView.java @@ -20,11 +20,10 @@ package org.rhq.enterprise.gui.coregui.client.dashboard;
import java.util.HashMap; import java.util.HashSet; -import java.util.Map; +import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.Set; -import java.util.TreeMap;
-import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.AnimationCallback; @@ -49,19 +48,14 @@ import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.criteria.ResourceGroupCriteria; import org.rhq.core.domain.dashboard.Dashboard; import org.rhq.core.domain.dashboard.DashboardPortlet; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceTypeFacet; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.group.GroupCategory; -import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite; -import org.rhq.core.domain.util.PageControl; -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.UserSessionManager; @@ -115,33 +109,58 @@ public class DashboardView extends LocatableVLayout { private MenuItem[] refreshMenuItems; private int refreshInterval = 0; private LocatableIMenuButton refreshMenuButton; - private HashMap<String, PortletViewFactory> portletMap = null; - private ResourceGroup group = null; + + private EntityContext context; private ResourceGroupComposite groupComposite = null; - private Resource resource = null; private ResourceComposite resourceComposite = null;
// this is used to prevent an odd smartgwt problem where onInit() can get called multiple times if // the view is set to a Tab's pane. private boolean isInitialized = false;
+ /** + * Convenience constructor for subsystem context. + * + * @param locatorId + * @param dashboardContainer + * @param storedDashboard + */ public DashboardView(String locatorId, DashboardContainer dashboardContainer, Dashboard storedDashboard) { + + this(locatorId, dashboardContainer, storedDashboard, EntityContext.forSubsystemView(), null); + } + + /** + * @param locatorId + * @param dashboardContainer + * @param storedDashboard + * @param context + * @param composite ResourceComposite, ResourceGroupComposite or null depending on context + */ + public DashboardView(String locatorId, DashboardContainer dashboardContainer, Dashboard storedDashboard, + EntityContext context, Object composite) { + super(locatorId);
this.dashboardContainer = dashboardContainer; this.storedDashboard = storedDashboard; - } + this.context = context;
- public DashboardView(String locatorId, DashboardContainer dashboardContainer, Dashboard storedDashboard, - ResourceGroupComposite groupCompositeValue, ResourceComposite resourceCompositeValue) { - this(locatorId, dashboardContainer, storedDashboard); - groupComposite = groupCompositeValue; - if (groupComposite != null) { - group = groupCompositeValue.getResourceGroup(); + switch (this.context.getType()) { + case Resource: { + if (null == composite) { + throw new IllegalArgumentException("null composite for resource context"); + } + this.resourceComposite = (ResourceComposite) composite; + break; + } + case ResourceGroup: { + if (null == composite) { + throw new IllegalArgumentException("null composite for group context"); + } + this.groupComposite = (ResourceGroupComposite) composite; + break; } - resourceComposite = resourceCompositeValue; - if (resourceComposite != null) { - resource = resourceComposite.getResource(); } }
@@ -197,65 +216,11 @@ public class DashboardView extends LocatableVLayout {
private DynamicForm buildEditForm() { editForm = new LocatableDynamicForm(extendLocatorId("Editor")); - final Map<String, String> groupKeyNameMap = new HashMap<String, String>(PortletFactory - .getRegisteredGroupPortletNameMap()); - //remove BundleDeployment and add back later if relevant. - groupKeyNameMap.remove(GroupBundleDeploymentsPortlet.KEY); - //if group, need to do asynch check for bundlePortlet to ensure only Platform members - if (groupComposite != null) { - final ResourceGroup group = groupComposite.getResourceGroup(); - ResourceGroupCriteria criteria = new ResourceGroupCriteria(); - criteria.addFilterId(group.getId()); - criteria.fetchExplicitResources(true); - criteria.setPageControl(new PageControl(0, 1)); - GWTServiceLookup.getResourceGroupService().findResourceGroupsByCriteria(criteria, - new AsyncCallback<PageList<ResourceGroup>>() { - @Override - public void onSuccess(PageList<ResourceGroup> results) { - if (!results.isEmpty()) { - ResourceGroup grp = results.get(0); - Set<Resource> explicitMembers = grp.getExplicitResources(); - Resource[] currentResources = new Resource[explicitMembers.size()]; - explicitMembers.toArray(currentResources); - //membership dynamically determined if all platforms then will be compatible. - if (group.getGroupCategory().equals(GroupCategory.COMPATIBLE)) { - if (currentResources[0].getResourceType().getCategory().equals( - ResourceCategory.PLATFORM)) { - //this portlet allowed to add bundle portlet monitoring - groupKeyNameMap.put(GroupBundleDeploymentsPortlet.KEY, - GroupBundleDeploymentsPortlet.NAME); - } - } - } - //now complet populating of portlet edit form. - populateBuildEditForm(groupKeyNameMap); - } - - @Override - public void onFailure(Throwable caught) { - Log.debug("Error retrieving information for group [" + group.getId() + "]:" - + caught.getMessage()); - } - }); - - } else {//otherwise default groupKeyNameMap is sufficient as won't be used. - populateBuildEditForm(groupKeyNameMap); - } - - return editForm; - } - - /** Responsible for populating the edit form widget. - * groupKepNameMap is updated for bundles. - * - * @param groupKeyNameMap - */ - private void populateBuildEditForm(Map<String, String> groupKeyNameMap) { editForm.setMargin(5); editForm.setAutoWidth(); editForm.setNumCols(canEditName() ? 12 : 10); - TextItem nameItem = null;
+ TextItem nameItem = null; if (dashboardContainer.supportsDashboardNameEdit()) { nameItem = new TextItem("name", MSG.common_title_dashboard_name()); nameItem.setValue(storedDashboard.getName()); @@ -278,11 +243,9 @@ public class DashboardView extends LocatableVLayout { numColItem.setValue(storedDashboard.getColumns());
ButtonItem addColumn = new ButtonItem("addColumn", MSG.common_title_add_column()); - addColumn.setAutoFit(true); addColumn.setStartRow(false); addColumn.setEndRow(false); - addColumn.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event) { portalLayout.addMember(new PortalColumn()); @@ -296,7 +259,6 @@ public class DashboardView extends LocatableVLayout { removeColumn.setAutoFit(true); removeColumn.setStartRow(false); removeColumn.setEndRow(false); - removeColumn.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {
@@ -315,50 +277,40 @@ public class DashboardView extends LocatableVLayout { } });
+ // build the menu of valid portlets for this context, sorted by portlet name final Menu addPortletMenu = new LocatableMenu(editForm.extendLocatorId("PortletMenu")); - HashMap<String, String> keyNameMap = new HashMap<String, String>(PortletFactory.getRegisteredPortletNameMap()); - // the assumption here is that the portlet names are unique. we want a sorted menu here, so create a - // sorted map from portlet name to portlet key and use that to generate the menu. It would be nice if you - // could just call Menu.sort() but it's not supported (yet?). - final TreeMap<String, String> nameKeyMap = new TreeMap<String, String>(); - for (String portletKey : keyNameMap.keySet()) { - nameKeyMap.put(keyNameMap.get(portletKey), portletKey); + LinkedHashMap<String, String> valueMap; + + switch (context.getType()) { + case SubsystemView: + valueMap = PortletFactory.getGlobalPortletMenuMap(); + break; + + case ResourceGroup: + valueMap = processPortletNameMapForGroup(this.groupComposite); + // In addition to the group-specific portlets, make the global portlets available + valueMap.putAll(PortletFactory.getGlobalPortletMenuMap()); + break; + + case Resource: + valueMap = processPortletNameMapForResource(this.resourceComposite); + // In addition to the resource-specific portlets, make the global portlets available + valueMap.putAll(PortletFactory.getGlobalPortletMenuMap()); + break; + + default: + throw new IllegalStateException("Unsupported context [" + context + "]"); } - - //if resourceGroup passed in then upate portlets list depending on grouptype and facets - if (this.group != null) { - - //filter out portlets not relevent for group(compat|mixed) or facets - groupKeyNameMap = processPortletNameMapForGroup(groupKeyNameMap, this.groupComposite); - - //add to default list of portlets. - for (String portletKey : groupKeyNameMap.keySet()) { - nameKeyMap.put(groupKeyNameMap.get(portletKey), portletKey); - } - } - - HashMap<String, String> resourceKeyNameMap = new HashMap<String, String>(PortletFactory - .getRegisteredResourcePortletNameMap()); - //if resource passed in then add additional portlets to list - if (this.resource != null) { - //trim out portlets that should not be visible - resourceKeyNameMap = processPortletNameMapForResource(resourceKeyNameMap, this.resourceComposite); - - for (String portletKey : resourceKeyNameMap.keySet()) { - nameKeyMap.put(resourceKeyNameMap.get(portletKey), portletKey); - } - } - - //build the addPortlet Menu item - // now use the reversed map for the menu generation - for (String portletName : nameKeyMap.keySet()) { + for (Iterator<String> i = valueMap.keySet().iterator(); i.hasNext();) { + String portletKey = i.next(); + String portletName = valueMap.get(portletKey); MenuItem menuItem = new MenuItem(portletName); - menuItem.setAttribute("portletKey", nameKeyMap.get(portletName)); + menuItem.setAttribute("portletKey", portletKey); addPortletMenu.addItem(menuItem); } + addPortlet = new LocatableIMenuButton(editForm.extendLocatorId("AddPortlet"), MSG.common_title_add_portlet(), addPortletMenu); - addPortlet.setIcon("[skin]/images/actions/add.png"); addPortlet.setAutoFit(true);
@@ -460,98 +412,112 @@ public class DashboardView extends LocatableVLayout { } else { editForm.setItems(addCanvas, numColItem, addColumn, removeColumn, picker, refreshCanvas); } + updateRefreshMenu(); this.refreshMenuButton.markForRedraw(); + markForRedraw(); + //attempt to initialize editForm.markForRedraw(); markForRedraw(); + + return editForm; }
- /**Process the portletName map to exclude portlets that should not be visible for this - * resource. + /** Return the relevant sorted value map for the resource */ - public static HashMap<String, String> processPortletNameMapForResource(HashMap<String, String> resourceKeyNameMap, - ResourceComposite composite) { - if ((composite != null) && (composite.getResource() != null) && (resourceKeyNameMap != null) - && !resourceKeyNameMap.isEmpty()) { - Resource resource = composite.getResource(); - //filter out portlets not relevent for facets + public static LinkedHashMap<String, String> processPortletNameMapForResource(ResourceComposite composite) { + + LinkedHashMap<String, String> resourceMenuMap = PortletFactory.getResourcePortletMenuMap(); + + if ((composite != null) && (composite.getResource() != null)) { + resourceMenuMap = new LinkedHashMap<String, String>(resourceMenuMap); + + // filter out portlets not relevent for facets Set<ResourceTypeFacet> facets = composite.getResourceFacets().getFacets(); if (!facets.isEmpty()) { - //Operation related portlets + // Operation related portlets if (!facets.contains(ResourceTypeFacet.OPERATION)) { - resourceKeyNameMap.remove(ResourceOperationsPortlet.KEY); + resourceMenuMap.remove(ResourceOperationsPortlet.KEY); } - //MEASUREMENT related portlets(METRICS) + // MEASUREMENT related portlets(METRICS) if (!facets.contains(ResourceTypeFacet.MEASUREMENT)) { - resourceKeyNameMap.remove(ResourceMetricsPortlet.KEY); - resourceKeyNameMap.remove(ResourceMetricsPortlet.KEY); + resourceMenuMap.remove(ResourceMetricsPortlet.KEY); + resourceMenuMap.remove(ResourceMetricsPortlet.KEY); } - //Content related portlets + // Content related portlets if (!facets.contains(ResourceTypeFacet.CONTENT)) { - resourceKeyNameMap.remove(ResourcePkgHistoryPortlet.KEY); + resourceMenuMap.remove(ResourcePkgHistoryPortlet.KEY); } - //Event related portlets + // Event related portlets if (!facets.contains(ResourceTypeFacet.EVENT)) { - resourceKeyNameMap.remove(ResourceEventsPortlet.KEY); + resourceMenuMap.remove(ResourceEventsPortlet.KEY); } - //Configuration related portlets + // Configuration related portlets if (!facets.contains(ResourceTypeFacet.CONFIGURATION)) { - resourceKeyNameMap.remove(ResourceConfigurationUpdatesPortlet.KEY); + resourceMenuMap.remove(ResourceConfigurationUpdatesPortlet.KEY); + } + // Bundle related portlets + if (!facets.contains(ResourceTypeFacet.BUNDLE)) { + resourceMenuMap.remove(ResourceBundleDeploymentsPortlet.KEY); } - } - //Bundle related portlet - if (!resource.getResourceType().getCategory().equals(ResourceCategory.PLATFORM)) { - resourceKeyNameMap.remove(ResourceBundleDeploymentsPortlet.KEY); } } - return resourceKeyNameMap; + + return resourceMenuMap; }
- /**Process the portletName map to exclude portlets that should not be visible for this - * group. All except BundleDeployment visibility is handled here. Bundle requires runtime check. + /** Return the relevant sorted value map for the group */ - public static Map<String, String> processPortletNameMapForGroup(Map<String, String> groupKeyNameMap, - ResourceGroupComposite composite) { - if ((composite != null) && (composite.getResourceGroup() != null) && (groupKeyNameMap != null) - && !groupKeyNameMap.isEmpty()) { + public static LinkedHashMap<String, String> processPortletNameMapForGroup(ResourceGroupComposite composite) { + + LinkedHashMap<String, String> groupMenuMap = PortletFactory.getGroupPortletMenuMap();
- //filter out portlets not relevent for facets + if ((composite != null) && (composite.getResourceGroup() != null)) { + groupMenuMap = new LinkedHashMap<String, String>(groupMenuMap); + + // filter out portlets not relevent for facets Set<ResourceTypeFacet> facets = composite.getResourceFacets().getFacets(); GroupCategory groupCategory = composite.getResourceGroup().getGroupCategory(); - //if not a compatible group may need to do some pruning. + + // if not a compatible group do some pruning. if (groupCategory != GroupCategory.COMPATIBLE) { - groupKeyNameMap.remove(GroupOperationsPortlet.KEY); - groupKeyNameMap.remove(GroupMetricsPortlet.KEY); - groupKeyNameMap.remove(GroupOobsPortlet.KEY); - groupKeyNameMap.remove(GroupPkgHistoryPortlet.KEY); - groupKeyNameMap.remove(GroupConfigurationUpdatesPortlet.KEY); + groupMenuMap.remove(GroupOperationsPortlet.KEY); + groupMenuMap.remove(GroupMetricsPortlet.KEY); + groupMenuMap.remove(GroupOobsPortlet.KEY); + groupMenuMap.remove(GroupPkgHistoryPortlet.KEY); + groupMenuMap.remove(GroupConfigurationUpdatesPortlet.KEY); + } else { - //for compatible may still need to do some pruning. + // for compatible may still need to do some pruning. if (!facets.isEmpty()) { - //Operations related portlets(Config,PkgHistory) + // Operations related portlets(Config,PkgHistory) if (!facets.contains(ResourceTypeFacet.OPERATION)) { - groupKeyNameMap.remove(GroupOperationsPortlet.KEY); + groupMenuMap.remove(GroupOperationsPortlet.KEY); } - //MEASUREMENT related portlets(METRICS) + // MEASUREMENT related portlets(METRICS) if (!facets.contains(ResourceTypeFacet.MEASUREMENT)) { - groupKeyNameMap.remove(GroupMetricsPortlet.KEY); - groupKeyNameMap.remove(GroupOobsPortlet.KEY); + groupMenuMap.remove(GroupMetricsPortlet.KEY); + groupMenuMap.remove(GroupOobsPortlet.KEY); } - //CONTENT related portlets(CONTENT) + // CONTENT related portlets(CONTENT) if (!facets.contains(ResourceTypeFacet.CONTENT)) { - groupKeyNameMap.remove(GroupPkgHistoryPortlet.KEY); + groupMenuMap.remove(GroupPkgHistoryPortlet.KEY); } - //CONFIGURATION related portlets(CONFIGURATION) + // CONFIGURATION related portlets(CONFIGURATION) if (!facets.contains(ResourceTypeFacet.CONFIGURATION)) { - groupKeyNameMap.remove(GroupConfigurationUpdatesPortlet.KEY); + groupMenuMap.remove(GroupConfigurationUpdatesPortlet.KEY); + } + // BUNDLE related portlets(BUNDLE) + if (!facets.contains(ResourceTypeFacet.BUNDLE)) { + groupMenuMap.remove(GroupBundleDeploymentsPortlet.KEY); } } } - } - return groupKeyNameMap; + + return groupMenuMap; }
private void loadPortletWindows() { @@ -560,7 +526,7 @@ public class DashboardView extends LocatableVLayout { for (DashboardPortlet storedPortlet : storedDashboard.getPortlets(i)) { String locatorId = getPortletLocatorId(portalLayout, storedPortlet);
- PortletWindow portletWindow = new PortletWindow(locatorId, this, storedPortlet); + PortletWindow portletWindow = new PortletWindow(locatorId, this, storedPortlet, context); portletWindow.setTitle(storedPortlet.getName()); portletWindow.setHeight(storedPortlet.getHeight()); portletWindow.setVisible(true); @@ -602,7 +568,7 @@ public class DashboardView extends LocatableVLayout { storedDashboard.addPortlet(storedPortlet);
String locatorId = getPortletLocatorId(portalLayout, storedPortlet); - final PortletWindow newPortletWindow = new PortletWindow(locatorId, this, storedPortlet); + final PortletWindow newPortletWindow = new PortletWindow(locatorId, this, storedPortlet, context); newPortletWindow.setTitle(portletName); newPortletWindow.setHeight(350); newPortletWindow.setVisible(false); @@ -729,12 +695,6 @@ public class DashboardView extends LocatableVLayout {
private void updatePortletWindows(Dashboard result) { if (result != null) { - if (portletMap == null) { - portletMap = new HashMap<String, PortletViewFactory>(); - for (String key : PortletFactory.getRegisteredPortletKeys()) { - portletMap.put(key, PortletFactory.getRegisteredPortletFactory(key)); - } - } for (PortletWindow portletWindow : portletWindows) { for (DashboardPortlet updatedPortlet : result.getPortlets()) { if (equalsDashboardPortlet(portletWindow.getStoredPortlet(), updatedPortlet)) { @@ -900,6 +860,10 @@ public class DashboardView extends LocatableVLayout { return storedDashboard; }
+ public EntityContext getContext() { + return context; + } + public ResourceGroupComposite getGroupComposite() { return groupComposite; } 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..d6957b1 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 @@ -18,15 +18,15 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard;
-import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.TreeMap;
import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.Label;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; @@ -65,141 +65,165 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** * @author Simeon Pinder - * @author Greg Hinkle + * @author Jay Shaughnessy */ public class PortletFactory {
- private static final HashMap<String, PortletViewFactory> registeredPortletFactoryMap; - private static final HashMap<String, String> registeredPortletNameMap; + private static final HashMap<String, PortletViewFactory> globalPortletFactoryMap; + // although portlet names are I18N, they are assumed to be unique. This maps portlet names to portlet keys, + // and the keyset is sorted for convenient display. + private static final TreeMap<String, String> globalPortletNameMap; + // although portlet names are I18N, they are assumed to be unique. This maps portlet keys to portlet names, + // and is suitable for a sorted Menu value map. + private static final LinkedHashMap<String, String> globalPortletMenuMap;
//Group portlet registrations, diff from default portlets as only applicable for specific group - private static final HashMap<String, PortletViewFactory> registeredGroupPortletFactoryMap; + private static final HashMap<String, PortletViewFactory> groupPortletFactoryMap; + private static final TreeMap<String, String> groupPortletNameMap; + private static final LinkedHashMap<String, String> groupPortletMenuMap; + //Resource portlet registrations, diff from default portlets as only applicable for specific resource - private static final HashMap<String, PortletViewFactory> registeredResourcePortletFactoryMap; - private static final HashMap<String, String> registeredGroupPortletNameMap; - private static final HashMap<String, String> registeredResourcePortletNameMap; - private static HashMap<String, String> registeredPortletIconMap; + private static final HashMap<String, PortletViewFactory> resourcePortletFactoryMap; + private static final TreeMap<String, String> resourcePortletNameMap; + private static final LinkedHashMap<String, String> resourcePortletMenuMap; + private static HashMap<String, String> portletIconMap;
static { - // ############# Global Dashboard ############################ - // defines portlet factory mappings for global Dashboard - registeredPortletFactoryMap = new HashMap<String, PortletViewFactory>(); - registeredPortletFactoryMap.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(RecentlyAddedResourcesPortlet.KEY, - RecentlyAddedResourcesPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(ResourceGraphPortlet.KEY, ResourceGraphPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(ResourceGroupGraphPortlet.KEY, ResourceGroupGraphPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(TagCloudPortlet.KEY, TagCloudPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(MashupPortlet.KEY, MashupPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(MessagePortlet.KEY, MessagePortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(OperationHistoryPortlet.KEY, OperationHistoryPortlet.Factory.INSTANCE); - registeredPortletFactoryMap.put(OperationSchedulePortlet.KEY, OperationSchedulePortlet.Factory.INSTANCE); - - // defines portlet name mappings for global Dashboard - registeredPortletNameMap = new HashMap<String, String>(registeredPortletFactoryMap.size()); - registeredPortletNameMap.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.NAME); - registeredPortletNameMap.put(RecentlyAddedResourcesPortlet.KEY, RecentlyAddedResourcesPortlet.NAME); - registeredPortletNameMap.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.NAME); - registeredPortletNameMap.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.NAME); - registeredPortletNameMap.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.NAME); - registeredPortletNameMap.put(ResourceGraphPortlet.KEY, ResourceGraphPortlet.NAME); - registeredPortletNameMap.put(ResourceGroupGraphPortlet.KEY, ResourceGroupGraphPortlet.NAME); - registeredPortletNameMap.put(TagCloudPortlet.KEY, TagCloudPortlet.NAME); - registeredPortletNameMap.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.NAME); - registeredPortletNameMap.put(MashupPortlet.KEY, MashupPortlet.NAME); - registeredPortletNameMap.put(MessagePortlet.KEY, MessagePortlet.NAME); - registeredPortletNameMap.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.NAME); - registeredPortletNameMap.put(OperationHistoryPortlet.KEY, OperationHistoryPortlet.NAME); - registeredPortletNameMap.put(OperationSchedulePortlet.KEY, OperationSchedulePortlet.NAME); - - //############## Group Activity Dashboard ############################################ - //defines mapping for Group Activity Dashboard - registeredGroupPortletFactoryMap = new HashMap<String, PortletViewFactory>(); - registeredGroupPortletFactoryMap.put(GroupAlertsPortlet.KEY, GroupAlertsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupMetricsPortlet.KEY, GroupMetricsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupOobsPortlet.KEY, GroupOobsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupEventsPortlet.KEY, GroupEventsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupOperationsPortlet.KEY, GroupOperationsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupPkgHistoryPortlet.KEY, GroupPkgHistoryPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupBundleDeploymentsPortlet.KEY, - GroupBundleDeploymentsPortlet.Factory.INSTANCE); - registeredGroupPortletFactoryMap.put(GroupConfigurationUpdatesPortlet.KEY, + // GLOBAL Portlets + + // Map portlet keys to portlet factories + globalPortletFactoryMap = new HashMap<String, PortletViewFactory>(); + globalPortletFactoryMap.put(InventorySummaryPortlet.KEY, InventorySummaryPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(RecentlyAddedResourcesPortlet.KEY, RecentlyAddedResourcesPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(PlatformSummaryPortlet.KEY, PlatformSummaryPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(AutodiscoveryPortlet.KEY, AutodiscoveryPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(RecentAlertsPortlet.KEY, RecentAlertsPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(ResourceGraphPortlet.KEY, ResourceGraphPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(ResourceGroupGraphPortlet.KEY, ResourceGroupGraphPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(TagCloudPortlet.KEY, TagCloudPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(FavoriteResourcesPortlet.KEY, FavoriteResourcesPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(MashupPortlet.KEY, MashupPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(MessagePortlet.KEY, MessagePortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(ProblemResourcesPortlet.KEY, ProblemResourcesPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(OperationHistoryPortlet.KEY, OperationHistoryPortlet.Factory.INSTANCE); + globalPortletFactoryMap.put(OperationSchedulePortlet.KEY, OperationSchedulePortlet.Factory.INSTANCE); + + // sorted map of portlet names to portlet keys + globalPortletNameMap = new TreeMap<String, String>(); + globalPortletNameMap.put(InventorySummaryPortlet.NAME, InventorySummaryPortlet.KEY); + globalPortletNameMap.put(RecentlyAddedResourcesPortlet.NAME, RecentlyAddedResourcesPortlet.KEY); + globalPortletNameMap.put(PlatformSummaryPortlet.NAME, PlatformSummaryPortlet.KEY); + globalPortletNameMap.put(AutodiscoveryPortlet.NAME, AutodiscoveryPortlet.KEY); + globalPortletNameMap.put(RecentAlertsPortlet.NAME, RecentAlertsPortlet.KEY); + globalPortletNameMap.put(ResourceGraphPortlet.NAME, ResourceGraphPortlet.KEY); + globalPortletNameMap.put(ResourceGroupGraphPortlet.NAME, ResourceGroupGraphPortlet.KEY); + globalPortletNameMap.put(TagCloudPortlet.NAME, TagCloudPortlet.KEY); + globalPortletNameMap.put(FavoriteResourcesPortlet.NAME, FavoriteResourcesPortlet.KEY); + globalPortletNameMap.put(MashupPortlet.NAME, MashupPortlet.KEY); + globalPortletNameMap.put(MessagePortlet.NAME, MessagePortlet.KEY); + globalPortletNameMap.put(ProblemResourcesPortlet.NAME, ProblemResourcesPortlet.KEY); + globalPortletNameMap.put(OperationHistoryPortlet.NAME, OperationHistoryPortlet.KEY); + globalPortletNameMap.put(OperationSchedulePortlet.NAME, OperationSchedulePortlet.KEY); + + globalPortletMenuMap = new LinkedHashMap<String, String>(globalPortletNameMap.size()); + for (Iterator<String> i = globalPortletNameMap.keySet().iterator(); i.hasNext();) { + String portletName = i.next(); + globalPortletMenuMap.put(globalPortletNameMap.get(portletName), portletName); + } + + // GROUP Portlets + + // Map portlet keys to portlet factories + groupPortletFactoryMap = new HashMap<String, PortletViewFactory>(); + groupPortletFactoryMap.put(GroupAlertsPortlet.KEY, GroupAlertsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupMetricsPortlet.KEY, GroupMetricsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupOobsPortlet.KEY, GroupOobsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupEventsPortlet.KEY, GroupEventsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupOperationsPortlet.KEY, GroupOperationsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupPkgHistoryPortlet.KEY, GroupPkgHistoryPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupBundleDeploymentsPortlet.KEY, GroupBundleDeploymentsPortlet.Factory.INSTANCE); + groupPortletFactoryMap.put(GroupConfigurationUpdatesPortlet.KEY, GroupConfigurationUpdatesPortlet.Factory.INSTANCE);
- //register group portlet names - registeredGroupPortletNameMap = new HashMap<String, String>(registeredGroupPortletFactoryMap.size()); - registeredGroupPortletNameMap.put(GroupAlertsPortlet.KEY, GroupAlertsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupMetricsPortlet.KEY, GroupMetricsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupOobsPortlet.KEY, GroupOobsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupEventsPortlet.KEY, GroupEventsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupOperationsPortlet.KEY, GroupOperationsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupPkgHistoryPortlet.KEY, GroupPkgHistoryPortlet.NAME); - registeredGroupPortletNameMap.put(GroupBundleDeploymentsPortlet.KEY, GroupBundleDeploymentsPortlet.NAME); - registeredGroupPortletNameMap.put(GroupConfigurationUpdatesPortlet.KEY, GroupConfigurationUpdatesPortlet.NAME); - - //############## Resource Activity Dashboard ############################################ - //defines mapping for Group Activity Dashboard - registeredResourcePortletFactoryMap = new HashMap<String, PortletViewFactory>(); - registeredResourcePortletFactoryMap.put(ResourceMetricsPortlet.KEY, ResourceMetricsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceEventsPortlet.KEY, ResourceEventsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceOobsPortlet.KEY, ResourceOobsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceAlertsPortlet.KEY, ResourceAlertsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceOperationsPortlet.KEY, - ResourceOperationsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourcePkgHistoryPortlet.KEY, - ResourcePkgHistoryPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceBundleDeploymentsPortlet.KEY, + // sorted map of portlet names to portlet keys + groupPortletNameMap = new TreeMap<String, String>(); + groupPortletNameMap.put(GroupAlertsPortlet.NAME, GroupAlertsPortlet.KEY); + groupPortletNameMap.put(GroupMetricsPortlet.NAME, GroupMetricsPortlet.KEY); + groupPortletNameMap.put(GroupOobsPortlet.NAME, GroupOobsPortlet.KEY); + groupPortletNameMap.put(GroupEventsPortlet.NAME, GroupEventsPortlet.KEY); + groupPortletNameMap.put(GroupOperationsPortlet.NAME, GroupOperationsPortlet.KEY); + groupPortletNameMap.put(GroupPkgHistoryPortlet.NAME, GroupPkgHistoryPortlet.KEY); + groupPortletNameMap.put(GroupBundleDeploymentsPortlet.NAME, GroupBundleDeploymentsPortlet.KEY); + groupPortletNameMap.put(GroupConfigurationUpdatesPortlet.NAME, GroupConfigurationUpdatesPortlet.KEY); + + groupPortletMenuMap = new LinkedHashMap<String, String>(groupPortletNameMap.size()); + for (Iterator<String> i = groupPortletNameMap.keySet().iterator(); i.hasNext();) { + String portletName = i.next(); + groupPortletMenuMap.put(groupPortletNameMap.get(portletName), portletName); + } + + // Resource Portlets + + // Map portlet keys to portlet factories + resourcePortletFactoryMap = new HashMap<String, PortletViewFactory>(); + resourcePortletFactoryMap.put(ResourceMetricsPortlet.KEY, ResourceMetricsPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourceEventsPortlet.KEY, ResourceEventsPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourceOobsPortlet.KEY, ResourceOobsPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourceAlertsPortlet.KEY, ResourceAlertsPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourceOperationsPortlet.KEY, ResourceOperationsPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourcePkgHistoryPortlet.KEY, ResourcePkgHistoryPortlet.Factory.INSTANCE); + resourcePortletFactoryMap.put(ResourceBundleDeploymentsPortlet.KEY, ResourceBundleDeploymentsPortlet.Factory.INSTANCE); - registeredResourcePortletFactoryMap.put(ResourceConfigurationUpdatesPortlet.KEY, + resourcePortletFactoryMap.put(ResourceConfigurationUpdatesPortlet.KEY, ResourceConfigurationUpdatesPortlet.Factory.INSTANCE);
- //register resource portlet names - registeredResourcePortletNameMap = new HashMap<String, String>(registeredResourcePortletFactoryMap.size()); - registeredResourcePortletNameMap.put(ResourceMetricsPortlet.KEY, ResourceMetricsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceEventsPortlet.KEY, ResourceEventsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceOobsPortlet.KEY, ResourceOobsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceOperationsPortlet.KEY, ResourceOperationsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourcePkgHistoryPortlet.KEY, ResourcePkgHistoryPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceAlertsPortlet.KEY, ResourceAlertsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceBundleDeploymentsPortlet.KEY, - ResourceBundleDeploymentsPortlet.NAME); - registeredResourcePortletNameMap.put(ResourceConfigurationUpdatesPortlet.KEY, - ResourceConfigurationUpdatesPortlet.NAME); + // sorted map of portlet names to portlet keys + resourcePortletNameMap = new TreeMap<String, String>(); + resourcePortletNameMap.put(ResourceMetricsPortlet.NAME, ResourceMetricsPortlet.KEY); + resourcePortletNameMap.put(ResourceEventsPortlet.NAME, ResourceEventsPortlet.KEY); + resourcePortletNameMap.put(ResourceOobsPortlet.NAME, ResourceOobsPortlet.KEY); + resourcePortletNameMap.put(ResourceOperationsPortlet.NAME, ResourceOperationsPortlet.KEY); + resourcePortletNameMap.put(ResourcePkgHistoryPortlet.NAME, ResourcePkgHistoryPortlet.KEY); + resourcePortletNameMap.put(ResourceAlertsPortlet.NAME, ResourceAlertsPortlet.KEY); + resourcePortletNameMap.put(ResourceBundleDeploymentsPortlet.NAME, ResourceBundleDeploymentsPortlet.KEY); + resourcePortletNameMap.put(ResourceConfigurationUpdatesPortlet.NAME, ResourceConfigurationUpdatesPortlet.KEY); + + resourcePortletMenuMap = new LinkedHashMap<String, String>(resourcePortletNameMap.size()); + for (Iterator<String> i = resourcePortletNameMap.keySet().iterator(); i.hasNext();) { + String portletName = i.next(); + resourcePortletMenuMap.put(resourcePortletNameMap.get(portletName), portletName); + }
//############## Portlet icon mappings ############################################ //register portlet names - registeredPortletIconMap = new HashMap<String, String>(registeredPortletFactoryMap.size()); - registeredPortletIconMap.put(GroupAlertsPortlet.KEY, ImageManager.getAlertIcon()); - registeredPortletIconMap.put(ResourceAlertsPortlet.KEY, ImageManager.getAlertIcon()); - registeredPortletIconMap.put(GroupMetricsPortlet.KEY, ImageManager.getMonitorIcon()); - registeredPortletIconMap.put(ResourceMetricsPortlet.KEY, ImageManager.getMonitorIcon()); - registeredPortletIconMap.put(GroupOobsPortlet.KEY, ImageManager.getMonitorFailedIcon()); - registeredPortletIconMap.put(ResourceOobsPortlet.KEY, ImageManager.getMonitorFailedIcon()); - registeredPortletIconMap.put(GroupEventsPortlet.KEY, ImageManager.getEventIcon()); - registeredPortletIconMap.put(ResourceEventsPortlet.KEY, ImageManager.getEventIcon()); - registeredPortletIconMap.put(GroupOperationsPortlet.KEY, ImageManager.getOperationIcon()); - registeredPortletIconMap.put(ResourceOperationsPortlet.KEY, ImageManager.getOperationIcon()); - registeredPortletIconMap.put(GroupPkgHistoryPortlet.KEY, ImageManager.getActivityPackageIcon()); - registeredPortletIconMap.put(ResourcePkgHistoryPortlet.KEY, ImageManager.getActivityPackageIcon()); - registeredPortletIconMap.put(GroupBundleDeploymentsPortlet.KEY, ImageManager.getBundleIcon()); - registeredPortletIconMap.put(ResourceBundleDeploymentsPortlet.KEY, ImageManager.getBundleIcon()); - registeredPortletIconMap.put(GroupConfigurationUpdatesPortlet.KEY, ImageManager.getConfigureIcon()); - registeredPortletIconMap.put(ResourceConfigurationUpdatesPortlet.KEY, ImageManager.getConfigureIcon()); + portletIconMap = new HashMap<String, String>(globalPortletFactoryMap.size()); + portletIconMap.put(GroupAlertsPortlet.KEY, ImageManager.getAlertIcon()); + portletIconMap.put(ResourceAlertsPortlet.KEY, ImageManager.getAlertIcon()); + portletIconMap.put(GroupMetricsPortlet.KEY, ImageManager.getMonitorIcon()); + portletIconMap.put(ResourceMetricsPortlet.KEY, ImageManager.getMonitorIcon()); + portletIconMap.put(GroupOobsPortlet.KEY, ImageManager.getMonitorFailedIcon()); + portletIconMap.put(ResourceOobsPortlet.KEY, ImageManager.getMonitorFailedIcon()); + portletIconMap.put(GroupEventsPortlet.KEY, ImageManager.getEventIcon()); + portletIconMap.put(ResourceEventsPortlet.KEY, ImageManager.getEventIcon()); + portletIconMap.put(GroupOperationsPortlet.KEY, ImageManager.getOperationIcon()); + portletIconMap.put(ResourceOperationsPortlet.KEY, ImageManager.getOperationIcon()); + portletIconMap.put(GroupPkgHistoryPortlet.KEY, ImageManager.getActivityPackageIcon()); + portletIconMap.put(ResourcePkgHistoryPortlet.KEY, ImageManager.getActivityPackageIcon()); + portletIconMap.put(GroupBundleDeploymentsPortlet.KEY, ImageManager.getBundleIcon()); + portletIconMap.put(ResourceBundleDeploymentsPortlet.KEY, ImageManager.getBundleIcon()); + portletIconMap.put(GroupConfigurationUpdatesPortlet.KEY, ImageManager.getConfigureIcon()); + portletIconMap.put(ResourceConfigurationUpdatesPortlet.KEY, ImageManager.getConfigureIcon()); }
- public static Portlet buildPortlet(String locatorId, PortletWindow portletWindow, DashboardPortlet storedPortlet) { + public static Portlet buildPortlet(String locatorId, PortletWindow portletWindow, DashboardPortlet storedPortlet, + EntityContext context) {
- PortletViewFactory viewFactory = registeredPortletFactoryMap.get(storedPortlet.getPortletKey()); + PortletViewFactory viewFactory = globalPortletFactoryMap.get(storedPortlet.getPortletKey()); if (viewFactory == null) {//check group view factory - viewFactory = registeredGroupPortletFactoryMap.get(storedPortlet.getPortletKey()); + viewFactory = groupPortletFactoryMap.get(storedPortlet.getPortletKey());
if (viewFactory == null) {//check resource view factory - viewFactory = registeredResourcePortletFactoryMap.get(storedPortlet.getPortletKey()); + viewFactory = resourcePortletFactoryMap.get(storedPortlet.getPortletKey());
if (viewFactory == null) { Message msg = new Message("Bad portlet: " + storedPortlet, Severity.Warning); @@ -224,7 +248,7 @@ public class PortletFactory { } }
- Portlet view = viewFactory.getInstance(locatorId); + Portlet view = viewFactory.getInstance(locatorId, context); view.configure(portletWindow, storedPortlet);
//add code to initiate refresh cycle for portlets @@ -235,89 +259,30 @@ public class PortletFactory { return view; }
- public static List<String> getRegisteredPortletKeys() { - - ArrayList<String> portletKeys = new ArrayList<String>(registeredPortletFactoryMap.keySet()); - return portletKeys; - } - - public static List<String> getRegisteredGroupPortletKeys() { - - ArrayList<String> portletKeys = new ArrayList<String>(registeredGroupPortletFactoryMap.keySet()); - return portletKeys; - } - - public static List<String> getRegisteredResourcePortletKeys() { - - ArrayList<String> portletKeys = new ArrayList<String>(registeredResourcePortletFactoryMap.keySet()); - return portletKeys; - } - - /** - * @return Unmodifiable Map of registered portlet keys to names + /** + * @return Unprotected, make a copy if you need to alter the map entries. */ - public static Map<String, String> getRegisteredPortletNameMap() { - return Collections.unmodifiableMap(registeredPortletNameMap); + public static LinkedHashMap<String, String> getGlobalPortletMenuMap() { + return globalPortletMenuMap; }
- /** - * @return Unmodifiable Map of registered portlet keys to names + /** + * @return Unprotected, make a copy if you need to alter the map entries. */ - public static Map<String, String> getRegisteredGroupPortletNameMap() { - - return Collections.unmodifiableMap(registeredGroupPortletNameMap); + public static LinkedHashMap<String, String> getGroupPortletMenuMap() { + return groupPortletMenuMap; }
- /** - * @return Unmodifiable Map of registered portlet keys to names + /** + * @return Unprotected, make a copy if you need to alter the map entries. */ - public static Map<String, String> getRegisteredResourcePortletNameMap() { - - return Collections.unmodifiableMap(registeredResourcePortletNameMap); - } - - public static String getRegisteredPortletName(String key) { - - return registeredPortletNameMap.get(key); - } - - public static String getRegisteredGroupPortletName(String key) { - - return registeredGroupPortletNameMap.get(key); - } - - public static String getRegisteredResourcePortletName(String key) { - - return registeredResourcePortletNameMap.get(key); + public static LinkedHashMap<String, String> getResourcePortletMenuMap() { + return resourcePortletMenuMap; }
public static String getRegisteredPortletIcon(String key) {
- return registeredPortletIconMap.get(key); - } - - public static PortletViewFactory getRegisteredPortletFactory(String key) { - PortletViewFactory portletFactory = null; - if ((key != null) & (!key.trim().isEmpty())) { - portletFactory = registeredPortletFactoryMap.get(key); - } - return portletFactory; - } - - public static PortletViewFactory getRegisteredGroupPortletFactory(String key) { - PortletViewFactory portletFactory = null; - if ((key != null) & (!key.trim().isEmpty())) { - portletFactory = registeredGroupPortletFactoryMap.get(key); - } - return portletFactory; - } - - public static PortletViewFactory getRegisteredResourcePortletFactory(String key) { - PortletViewFactory portletFactory = null; - if ((key != null) & (!key.trim().isEmpty())) { - portletFactory = registeredResourcePortletFactoryMap.get(key); - } - return portletFactory; + return portletIconMap.get(key); }
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletViewFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletViewFactory.java index c14e6ab..9ab5653 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletViewFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletViewFactory.java @@ -18,10 +18,12 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard;
+import org.rhq.core.domain.common.EntityContext; + /** - * @author Greg Hinkle + * @author Jay Shaughnessy */ public interface PortletViewFactory {
- Portlet getInstance(String locatorId); + Portlet getInstance(String locatorId, EntityContext context); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java index 530ed35..5fb06be 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/PortletWindow.java @@ -40,6 +40,7 @@ import com.smartgwt.client.widgets.events.MouseOverEvent; import com.smartgwt.client.widgets.events.MouseOverHandler;
import org.rhq.core.domain.authz.Permission; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.enterprise.gui.coregui.client.components.table.Table; @@ -65,6 +66,9 @@ public class PortletWindow extends LocatableWindow { // The actual portlet content view private Portlet view;
+ // The context applied to the portlet instance + private EntityContext context; + private static final ClickHandler NO_OP_HANDLER = new ClickHandler() { public void onClick(ClickEvent clickEvent) { } @@ -108,11 +112,14 @@ public class PortletWindow extends LocatableWindow { } };
- public PortletWindow(String locatorId, DashboardView dashboardView, DashboardPortlet dashboardPortlet) { + public PortletWindow(String locatorId, DashboardView dashboardView, DashboardPortlet dashboardPortlet, + EntityContext context) { super(locatorId);
this.dashboardView = dashboardView; this.storedPortlet = dashboardPortlet; + this.context = context; + setEdgeSize(2);
// if (!showFrame) { @@ -204,7 +211,7 @@ public class PortletWindow extends LocatableWindow { super.onInit();
// each portletWindow wraps a single portlet view, so just extend the window's locatorId with a static id - view = PortletFactory.buildPortlet(extendLocatorId("View"), this, storedPortlet); + view = PortletFactory.buildPortlet(extendLocatorId("View"), this, storedPortlet, context);
Canvas canvas = (Canvas) view; addItem(canvas); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupAlertsPortlet.java index 337989b..de50f2d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupAlertsPortlet.java @@ -18,8 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.groups;
-import com.google.gwt.user.client.History; - import org.rhq.core.domain.common.EntityContext; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; @@ -55,25 +53,13 @@ public class GroupAlertsPortlet extends AbstractRecentAlertsPortlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- /* (non-Javadoc) - * TODO: This factory ASSUMES the user is currently navigated to a group detail view, and generates a portlet - * for that group. It will fail in other scenarios. This mechanism should be improved such that the - * factory method can take an EntityContext explicitly indicating, in this case, the group. - * @see org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory#getInstance(java.lang.String) - */ - public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
- String currentPage = History.getToken(); - int groupId = -1; - String[] elements = currentPage.split("/"); - // process for groups and auto groups Ex. ResourceGroup/10111 or ResourceGroup/AutoCluster/10321 - try { - groupId = Integer.valueOf(elements[1]); - } catch (NumberFormatException nfe) { - groupId = Integer.valueOf(elements[2]); + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); }
- return new GroupAlertsPortlet(locatorId, groupId); + return new GroupAlertsPortlet(locatorId, context.getGroupId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupBundleDeploymentsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupBundleDeploymentsPortlet.java index 944b674..b7176a9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupBundleDeploymentsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupBundleDeploymentsPortlet.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.List;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; @@ -36,6 +35,7 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.bundle.BundleDeployment; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.GroupBundleDeploymentCriteria; @@ -88,11 +88,9 @@ public class GroupBundleDeploymentsPortlet extends LocatableVLayout implements C CONFIG_INCLUDE.add(Constant.RESULT_COUNT); }
- public GroupBundleDeploymentsPortlet(String locatorId) { + public GroupBundleDeploymentsPortlet(String locatorId, int groupId) { super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - int groupId = AbstractActivityView.groupIdLookup(currentPage); + this.groupId = groupId; }
@@ -140,8 +138,13 @@ public class GroupBundleDeploymentsPortlet extends LocatableVLayout implements C public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupBundleDeploymentsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupBundleDeploymentsPortlet(locatorId, context.getGroupId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java index ee1fbc5..653df07 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java @@ -24,7 +24,6 @@ import java.util.HashMap; import java.util.List;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; @@ -36,6 +35,7 @@ import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.SelectItem;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.ConfigurationUpdateStatus; import org.rhq.core.domain.configuration.PropertySimple; @@ -61,7 +61,6 @@ import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.PortletConfigura import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.common.detail.summary.AbstractActivityView; -import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.ResourceGroupDetailView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.configuration.GroupResourceConfigurationDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.configuration.HistoryGroupResourceConfigurationTable; import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility; @@ -80,7 +79,9 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement // A default displayed, persisted name for the portlet public static final String NAME = MSG.view_portlet_defaultName_group_config_updates();
- private int groupId = -1; + // context provides whether this is a standard group, autocluster or autogroup + private EntityContext context; + protected LocatableCanvas recentConfigurationContent = new LocatableCanvas( extendLocatorId("RecentConfigurationUpdates"));
@@ -109,7 +110,6 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement private ResourceGroupComposite groupComposite; protected boolean portletConfigInitialized = false; protected boolean currentlyLoading = false; - protected String baseViewPath = ""; private GroupConfigurationHistoryCriteriaTable groupHistoryTable;
protected static HashMap<String, String> updatedMapping = new HashMap<String, String>(); @@ -117,16 +117,9 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement updatedMapping.putAll(PortletConfigurationEditorComponent.CONFIG_PROPERTY_INITIALIZATION); }
- public GroupConfigurationUpdatesPortlet(String locatorId, int groupId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - this.groupId = groupId; - baseViewPath = AbstractActivityView.groupPathLookup(currentPage); - } - - public GroupConfigurationUpdatesPortlet(String locatorId) { + public GroupConfigurationUpdatesPortlet(String locatorId, EntityContext context) { super(locatorId); + this.context = context; }
/**Defines layout for the portlet page. @@ -234,25 +227,13 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- /* (non-Javadoc) - * TODO: This factory ASSUMES the user is currently navigated to a group detail view, and generates a portlet - * for that group. It will fail in other scenarios. This mechanism should be improved such that the - * factory method can take an EntityContext explicitly indicating, in this case, the group. - * @see org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory#getInstance(java.lang.String) - */ - public final Portlet getInstance(String locatorId) { - - String currentPage = History.getToken(); - int groupId = -1; - String[] elements = currentPage.split("/"); - // process for groups and auto groups Ex. ResourceGroup/10111 or ResourceGroup/AutoCluster/10321 - try { - groupId = Integer.valueOf(elements[1]); - } catch (NumberFormatException nfe) { - groupId = Integer.valueOf(elements[2]); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); }
- return new GroupConfigurationUpdatesPortlet(locatorId, groupId); + return new GroupConfigurationUpdatesPortlet(locatorId, context); } }
@@ -299,18 +280,16 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement //populate composite data //locate resourceGroupRef ResourceGroupCriteria criteria = new ResourceGroupCriteria(); - criteria.addFilterId(this.groupId); + criteria.addFilterId(context.getGroupId()); criteria.fetchConfigurationUpdates(false); criteria.fetchExplicitResources(false); criteria.fetchGroupDefinition(false); criteria.fetchOperationHistories(false);
// for autoclusters and autogroups we need to add more criteria - final boolean isAutoCluster = isAutoCluster(); - final boolean isAutoGroup = isAutoGroup(); - if (isAutoCluster) { + if (context.isAutoCluster()) { criteria.addFilterVisible(false); - } else if (isAutoGroup) { + } else if (context.isAutoGroup()) { criteria.addFilterVisible(false); criteria.addFilterPrivate(true); } @@ -320,7 +299,7 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement new AsyncCallback<PageList<ResourceGroupComposite>>() { @Override public void onFailure(Throwable caught) { - Log.debug("Error retrieving resource group composite for group [" + groupId + "]:" + Log.debug("Error retrieving resource group composite for group [" + context.getGroupId() + "]:" + caught.getMessage()); currentlyLoading = false; } @@ -337,7 +316,7 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement //TODO: spinder: move this up into the pageControl. criteria.addSortStatus(PageOrdering.DESC); List<Integer> filterResourceGroupIds = new ArrayList<Integer>(); - filterResourceGroupIds.add(groupId); + filterResourceGroupIds.add(context.getGroupId()); criteria.addFilterResourceGroupIds(filterResourceGroupIds);
groupHistoryTable = new GroupConfigurationHistoryCriteriaTable(extendLocatorId("Table"), @@ -353,7 +332,7 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement
//update table for portlet display. groupHistoryTable.setDataSource(new GroupConfigurationUdpatesCriteriaDataSource(portletConfig, - groupId)); + context.getGroupId())); groupHistoryTable.setShowHeader(false); groupHistoryTable.setShowFooterRefresh(false);
@@ -368,18 +347,6 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement }); }
- private boolean isAutoGroup() { - return ResourceGroupDetailView.AUTO_GROUP_VIEW.equals(getBaseViewPath()); - } - - private boolean isAutoCluster() { - return ResourceGroupDetailView.AUTO_CLUSTER_VIEW.equals(getBaseViewPath()); - } - - public String getBaseViewPath() { - return baseViewPath; - } - class GroupConfigurationHistoryCriteriaTable extends HistoryGroupResourceConfigurationTable {
public GroupConfigurationHistoryCriteriaTable(String locatorId, ResourceGroupComposite groupComposite) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupEventsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupEventsPortlet.java index 9b5fb96..945b7ed 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupEventsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupEventsPortlet.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; @@ -33,6 +32,7 @@ import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.StaticTextItem;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; @@ -89,11 +89,8 @@ public class GroupEventsPortlet extends LocatableVLayout implements CustomSettin protected LocatableCanvas recentEventsContent = new LocatableCanvas(extendLocatorId("RecentEvents")); protected boolean currentlyLoading = false;
- public GroupEventsPortlet(String locatorId) { + public GroupEventsPortlet(String locatorId, int groupId) { super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - int groupId = AbstractActivityView.groupIdLookup(currentPage); this.groupId = groupId; }
@@ -143,8 +140,13 @@ public class GroupEventsPortlet extends LocatableVLayout implements CustomSettin public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupEventsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupEventsPortlet(locatorId, context.getGroupId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupMetricsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupMetricsPortlet.java index e45fbab..3eee947 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupMetricsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupMetricsPortlet.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.ContentsType; @@ -42,6 +41,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.ResourceGroupCriteria; @@ -110,13 +110,9 @@ public class GroupMetricsPortlet extends LocatableVLayout implements CustomSetti CONFIG_INCLUDE.add(Constant.METRIC_RANGE_UNIT); }
- public GroupMetricsPortlet(String locatorId) { + public GroupMetricsPortlet(String locatorId, int groupId) { super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - int groupId = AbstractActivityView.groupIdLookup(currentPage); this.groupId = groupId; - baseViewPath = AbstractActivityView.groupPathLookup(currentPage); }
@Override @@ -164,8 +160,13 @@ public class GroupMetricsPortlet extends LocatableVLayout implements CustomSetti public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupMetricsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupMetricsPortlet(locatorId, context.getGroupId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOobsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOobsPortlet.java index aa1fdca..155b892 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOobsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOobsPortlet.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.List;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; @@ -37,6 +36,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; @@ -87,11 +87,8 @@ public class GroupOobsPortlet extends LocatableVLayout implements CustomSettings CONFIG_INCLUDE.add(Constant.RESULT_COUNT); }
- public GroupOobsPortlet(String locatorId) { + public GroupOobsPortlet(String locatorId, int groupId) { super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - int groupId = AbstractActivityView.groupIdLookup(currentPage); this.groupId = groupId; }
@@ -139,8 +136,13 @@ public class GroupOobsPortlet extends LocatableVLayout implements CustomSettings public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupOobsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupOobsPortlet(locatorId, context.getGroupId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java index 9606874..901c38d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java @@ -23,7 +23,6 @@ import java.util.Arrays; import java.util.List;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; @@ -36,6 +35,7 @@ import com.smartgwt.client.widgets.form.events.SubmitValuesEvent; import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.SelectItem;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.GroupOperationHistoryCriteria; @@ -110,16 +110,10 @@ public class GroupOperationsPortlet extends LocatableVLayout implements CustomSe protected LocatableCanvas recentOperationsContent = new LocatableCanvas(extendLocatorId("RecentOperations")); protected String locatorId;
- public GroupOperationsPortlet(String locatorId) { + public GroupOperationsPortlet(String locatorId, int groupId) { super(locatorId); this.locatorId = locatorId; - //figure out which page we're loading - String currentPage = History.getToken(); - //String[] elements = currentPage.split("/"); - int groupId = AbstractActivityView.groupIdLookup(currentPage); this.groupId = groupId; - //populate basepath - baseViewPath = AbstractActivityView.groupPathLookup(currentPage); }
@Override @@ -299,8 +293,13 @@ public class GroupOperationsPortlet extends LocatableVLayout implements CustomSe public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupOperationsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupOperationsPortlet(locatorId, context.getGroupId()); } }
@@ -354,7 +353,6 @@ class GroupOperationsCriteriaHistoryListView extends GroupOperationHistoryListVi
private ResourceGroupComposite composite;
- @SuppressWarnings("unchecked") public GroupOperationsCriteriaHistoryListView(String locatorId, GroupOperationsCriteriaDataSource dataSource, String title, Criteria criteria, ResourceGroupComposite composite) { super(locatorId, composite); @@ -363,7 +361,6 @@ class GroupOperationsCriteriaHistoryListView extends GroupOperationHistoryListVi setShowFooterRefresh(false); //disable footer refresh }
- @SuppressWarnings("unchecked") public void setDatasource(GroupOperationsCriteriaDataSource datasource) { super.setDataSource(datasource); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupPkgHistoryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupPkgHistoryPortlet.java index 742c0a7..a3352a9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupPkgHistoryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupPkgHistoryPortlet.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.List;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; @@ -34,6 +33,7 @@ import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.content.InstalledPackageHistory; @@ -85,11 +85,8 @@ public class GroupPkgHistoryPortlet extends LocatableVLayout implements CustomSe CONFIG_INCLUDE.add(Constant.RESULT_COUNT); }
- public GroupPkgHistoryPortlet(String locatorId) { + public GroupPkgHistoryPortlet(String locatorId, int groupId) { super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - int groupId = AbstractActivityView.groupIdLookup(currentPage); this.groupId = groupId; }
@@ -137,8 +134,13 @@ public class GroupPkgHistoryPortlet extends LocatableVLayout implements CustomSe public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new GroupPkgHistoryPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.ResourceGroup != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new GroupPkgHistoryPortlet(locatorId, context.getGroupId()); } }
@@ -232,8 +234,8 @@ public class GroupPkgHistoryPortlet extends LocatableVLayout implements CustomSe StaticTextItem iconItem = AbstractActivityView.newTextItemIcon( "subsystems/content/Package_16.png", null); String title = history.getPackageVersion().getFileName() + ":"; - String destination = "/rhq/resource/content/audit-trail-item.xhtml?id=" + groupId - + "&selectedHistoryId=" + history.getId(); + //String destination = "/rhq/resource/content/audit-trail-item.xhtml?id=" + groupId + // + "&selectedHistoryId=" + history.getId(); //spinder 4/27/11: diabling links as they point into portal.war content pages // LinkItem link = AbstractActivityView.newLinkItem(title, destination); StaticTextItem link = AbstractActivityView.newTextItem(title); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/groups/graph/ResourceGroupGraphPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/groups/graph/ResourceGroupGraphPortlet.java index 9ac2534..87d1199 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/groups/graph/ResourceGroupGraphPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/groups/graph/ResourceGroupGraphPortlet.java @@ -31,6 +31,7 @@ import com.smartgwt.client.widgets.form.fields.CanvasItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.SpacerItem;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.resource.group.GroupCategory; @@ -193,7 +194,7 @@ public class ResourceGroupGraphPortlet extends ResourceGroupMetricGraphView impl public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new ResourceGroupGraphPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java index e5631ca..9ff9d84 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/queue/AutodiscoveryPortlet.java @@ -29,6 +29,7 @@ import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.events.ChangeEvent; import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.AutoRefreshPortlet; @@ -186,7 +187,7 @@ public class AutodiscoveryPortlet extends ResourceAutodiscoveryView implements C public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new AutodiscoveryPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java index 2e01daf..b9f7e31 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/FavoriteResourcesPortlet.java @@ -33,6 +33,7 @@ import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.events.FieldStateChangedEvent; import com.smartgwt.client.widgets.grid.events.FieldStateChangedHandler;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; @@ -121,7 +122,7 @@ public class FavoriteResourcesPortlet extends ResourceSearchView implements Auto public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new FavoriteResourcesPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/ResourceGraphPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/ResourceGraphPortlet.java index 820cf4f..ad18fcb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/ResourceGraphPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/inventory/resource/graph/ResourceGraphPortlet.java @@ -29,6 +29,7 @@ import com.smartgwt.client.widgets.form.events.SubmitValuesHandler; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.components.lookup.ResourceLookupComboBoxItem; @@ -173,7 +174,7 @@ public class ResourceGraphPortlet extends ResourceMetricGraphView implements Cus public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new ResourceGraphPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java index a7e322d..b78a036 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/platform/PlatformSummaryPortlet.java @@ -34,6 +34,7 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.layout.HLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.measurement.MeasurementData; @@ -46,7 +47,6 @@ 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.LinkManager; -import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; @@ -383,7 +383,7 @@ public class PlatformSummaryPortlet extends LocatableListGrid implements Portlet public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) { return new PlatformSummaryPortlet(locatorId); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java index 51e12b6..fbff45f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/RecentAlertsPortlet.java @@ -39,7 +39,7 @@ public class RecentAlertsPortlet extends AbstractRecentAlertsPortlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new RecentAlertsPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/RecentDriftsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/RecentDriftsPortlet.java index 89f370d..ebee689 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/RecentDriftsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/RecentDriftsPortlet.java @@ -39,7 +39,7 @@ public class RecentDriftsPortlet extends AbstractRecentDriftsPortlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new RecentDriftsPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java index d6b61d2..0ee9dd1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/imported/RecentlyAddedResourcesPortlet.java @@ -35,6 +35,7 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.tree.TreeGrid;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.components.HeaderLabel; @@ -231,7 +232,7 @@ public class RecentlyAddedResourcesPortlet extends LocatableVLayout implements C public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new RecentlyAddedResourcesPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationHistoryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationHistoryPortlet.java index 90aedd8..c26f829 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationHistoryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationHistoryPortlet.java @@ -40,7 +40,7 @@ public class OperationHistoryPortlet extends AbstractOperationHistoryPortlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new OperationHistoryPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationSchedulePortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationSchedulePortlet.java index b26405b..effb922 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationSchedulePortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/OperationSchedulePortlet.java @@ -35,6 +35,7 @@ import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.layout.VStack;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; @@ -301,7 +302,7 @@ public class OperationSchedulePortlet extends LocatableVLayout implements Custom public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new OperationSchedulePortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java index f3738d4..6c25762 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/problems/ProblemResourcesPortlet.java @@ -41,6 +41,7 @@ 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.configuration.PropertySimple; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; @@ -291,7 +292,7 @@ public class ProblemResourcesPortlet extends Table<ProblemResourcesDataSource> i public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new ProblemResourcesPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceAlertsPortlet.java index c43068f..9d7b079 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceAlertsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceAlertsPortlet.java @@ -18,8 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource;
-import com.google.gwt.user.client.History; - import org.rhq.core.domain.common.EntityContext; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; @@ -52,19 +50,13 @@ public class ResourceAlertsPortlet extends AbstractRecentAlertsPortlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- /* (non-Javadoc) - * TODO: This factory ASSUMES the user is currently navigated to a resource detail view, and generates a portlet - * for that resource. It will fail in other scenarios. This mechanism should be improved such that the - * factory method can take an EntityContext explicitly indicating, in this case, the resource. - * @see org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory#getInstance(java.lang.String) - */ - public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
- String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int resourceId = Integer.valueOf(elements[1]); + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + }
- return new ResourceAlertsPortlet(locatorId, resourceId); + return new ResourceAlertsPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceBundleDeploymentsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceBundleDeploymentsPortlet.java index be2dc7c..a66652a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceBundleDeploymentsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceBundleDeploymentsPortlet.java @@ -19,7 +19,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.LinkItem; @@ -27,6 +26,7 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.bundle.BundleDeployment; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.ResourceBundleDeploymentCriteria; @@ -57,20 +57,22 @@ public class ResourceBundleDeploymentsPortlet extends GroupBundleDeploymentsPort
private int resourceId = -1;
- public ResourceBundleDeploymentsPortlet(String locatorId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int currentResourceIdentifier = Integer.valueOf(elements[1]); - this.resourceId = currentResourceIdentifier; + public ResourceBundleDeploymentsPortlet(String locatorId, int resourceId) { + super(locatorId, -1); + + this.resourceId = resourceId; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new ResourceBundleDeploymentsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourceBundleDeploymentsPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java index f9b2d9d..5fb7aeb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceConfigurationUpdatesPortlet.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource; import java.util.ArrayList;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@ -29,6 +28,7 @@ import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGridRecord;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.ConfigurationUpdateStatus; import org.rhq.core.domain.configuration.PropertySimple; @@ -69,31 +69,20 @@ public class ResourceConfigurationUpdatesPortlet extends GroupConfigurationUpdat private ResourceConfigurationHistoryCriteriaView resourceHistoryTable;
public ResourceConfigurationUpdatesPortlet(String locatorId, int resourceId) { - super(locatorId); + super(locatorId, null); this.resourceId = resourceId; - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - baseViewPath = elements[0]; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- /* (non-Javadoc) - * TODO: This factory ASSUMES the user is currently navigated to a group detail view, and generates a portlet - * for that group. It will fail in other scenarios. This mechanism should be improved such that the - * factory method can take an EntityContext explicitly indicating, in this case, the group. - * @see org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory#getInstance(java.lang.String) - */ - public final Portlet getInstance(String locatorId) { - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int currentResourceIdentifier = Integer.valueOf(elements[1]); - int resourceId = currentResourceIdentifier; - - return new ResourceConfigurationUpdatesPortlet(locatorId, resourceId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourceConfigurationUpdatesPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceEventsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceEventsPortlet.java index eb52924..d7219dc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceEventsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceEventsPortlet.java @@ -23,11 +23,11 @@ import java.util.List; import java.util.Map;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.StaticTextItem;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; @@ -58,19 +58,21 @@ public class ResourceEventsPortlet extends GroupEventsPortlet {
private int resourceId = -1;
- public ResourceEventsPortlet(String locatorId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - this.resourceId = Integer.valueOf(elements[1]); + public ResourceEventsPortlet(String locatorId, int resourceId) { + super(locatorId, -1); + this.resourceId = resourceId; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new ResourceEventsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourceEventsPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceMetricsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceMetricsPortlet.java index 0adf94b..94f3ee8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceMetricsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceMetricsPortlet.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.Set;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.ContentsType; import com.smartgwt.client.widgets.Canvas; @@ -38,6 +37,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.ResourceCriteria; @@ -75,21 +75,21 @@ public class ResourceMetricsPortlet extends GroupMetricsPortlet {
private int resourceId = -1;
- public ResourceMetricsPortlet(String locatorId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int currentResourceIdentifier = Integer.valueOf(elements[1]); - this.resourceId = currentResourceIdentifier; - baseViewPath = elements[0]; + public ResourceMetricsPortlet(String locatorId, int resourceId) { + super(locatorId, -1); + this.resourceId = resourceId; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new ResourceMetricsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourceMetricsPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOobsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOobsPortlet.java index a2dc372..71ba768 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOobsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOobsPortlet.java @@ -19,7 +19,6 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.LinkItem; @@ -28,6 +27,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.dashboard.DashboardPortlet; @@ -57,19 +57,21 @@ public class ResourceOobsPortlet extends GroupOobsPortlet {
private int resourceId = -1;
- public ResourceOobsPortlet(String locatorId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - this.resourceId = Integer.valueOf(elements[1]); + public ResourceOobsPortlet(String locatorId, int resourceId) { + super(locatorId, -1); + this.resourceId = resourceId; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new ResourceOobsPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourceOobsPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOperationsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOperationsPortlet.java index 7862175..ce04aa9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOperationsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourceOperationsPortlet.java @@ -18,8 +18,6 @@ */ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource;
-import com.google.gwt.user.client.History; - import org.rhq.core.domain.common.EntityContext; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; @@ -40,22 +38,20 @@ public class ResourceOperationsPortlet extends AbstractOperationHistoryPortlet { super(locatorId, EntityContext.forResource(resourceId)); }
+ public ResourceOperationsPortlet(String locatorId, EntityContext context) { + super(locatorId, context); + } + public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- /* (non-Javadoc) - * TODO: This factory ASSUMES the user is currently navigated to a resource detail view, and generates a portlet - * for that resource. It will fail in other scenarios. This mechanism should be improved such that the - * factory method can take an EntityContext explicitly indicating, in this case, the resource. - * @see org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory#getInstance(java.lang.String) - */ - public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
- String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int resourceId = Integer.valueOf(elements[1]); + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + }
- return new ResourceOperationsPortlet(locatorId, resourceId); + return new ResourceOperationsPortlet(locatorId, context); }
} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java index 0d91bd2..c229656 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/resource/ResourcePkgHistoryPortlet.java @@ -19,12 +19,12 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource;
import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.layout.VLayout;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.content.InstalledPackageHistory; @@ -55,20 +55,21 @@ public class ResourcePkgHistoryPortlet extends GroupPkgHistoryPortlet {
private int resourceId = -1;
- public ResourcePkgHistoryPortlet(String locatorId) { - super(locatorId); - //figure out which page we're loading - String currentPage = History.getToken(); - String[] elements = currentPage.split("/"); - int currentResourceIdentifier = Integer.valueOf(elements[1]); - this.resourceId = currentResourceIdentifier; + public ResourcePkgHistoryPortlet(String locatorId, int resourceId) { + super(locatorId, -1); + this.resourceId = resourceId; }
public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { - return new ResourcePkgHistoryPortlet(locatorId); + public final Portlet getInstance(String locatorId, EntityContext context) { + + if (EntityContext.Type.Resource != context.getType()) { + throw new IllegalArgumentException("Context [" + context + "] not supported by portlet"); + } + + return new ResourcePkgHistoryPortlet(locatorId, context.getResourceId()); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java index 823c7d8..948ea70 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/InventorySummaryPortlet.java @@ -35,6 +35,7 @@ import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.resource.InventorySummary; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -179,7 +180,7 @@ public class InventorySummaryPortlet extends LocatableVLayout implements AutoRef public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) { return new InventorySummaryPortlet(locatorId); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java index 05503de..15cfbf1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/summary/TagCloudPortlet.java @@ -25,6 +25,7 @@ package org.rhq.enterprise.gui.coregui.client.dashboard.portlets.summary; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.Portlet; import org.rhq.enterprise.gui.coregui.client.dashboard.PortletViewFactory; @@ -56,7 +57,7 @@ public class TagCloudPortlet extends TagCloudView implements Portlet { public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new TagCloudPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java index e624433..e0513ef 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MashupPortlet.java @@ -26,6 +26,7 @@ import com.smartgwt.client.types.ContentsType; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; @@ -82,7 +83,7 @@ public class MashupPortlet extends LocatableHTMLPane implements ConfigurablePort public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) {
return new MashupPortlet(locatorId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java index 26b85a3..cfd967d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/util/MessagePortlet.java @@ -26,6 +26,7 @@ import com.smartgwt.client.types.ContentsType; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.HTMLFlow;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; @@ -60,8 +61,8 @@ public class MessagePortlet extends LocatableHTMLPane implements ConfigurablePor public void configure(PortletWindow portletWindow, DashboardPortlet storedPortlet) { String contents = storedPortlet.getConfiguration().getSimpleValue(MESSAGE_PROPERTY, null); if (contents != null) { - if (UserSessionManager.getSessionSubject().getId() != UsersDataSource.ID_RHQADMIN && - !contents.equals(DEFAULT_MESSAGE)) { + if (UserSessionManager.getSessionSubject().getId() != UsersDataSource.ID_RHQADMIN + && !contents.equals(DEFAULT_MESSAGE)) { // To avoid XSS attacks, don't allow non-superusers to enter HTML. // TODO (ips, 04/06/11): Sanitize this, rather than escaping it, once we upgrade to GWT 2.1 or later. contents = StringUtility.escapeHtml(contents); @@ -89,7 +90,7 @@ public class MessagePortlet extends LocatableHTMLPane implements ConfigurablePor public static final class Factory implements PortletViewFactory { public static PortletViewFactory INSTANCE = new Factory();
- public final Portlet getInstance(String locatorId) { + public final Portlet getInstance(String locatorId, EntityContext context) { return new MessagePortlet(locatorId); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java index cc51b5d..b51419d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java @@ -620,41 +620,6 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R .contains(ResourceTypeFacet.EVENT))); }
- /* Utility method to extract groupId from - * - */ - public static int groupIdLookup(String currentPage) { - int groupId = -1; - if ((currentPage != null) && (!currentPage.trim().isEmpty())) { - String[] elements = currentPage.split("/"); - //process for groups and auto groups Ex. ResourceGroup/10111 or ResourceGroup/AutoCluster/10321 - try { - groupId = Integer.valueOf(elements[1]); - } catch (NumberFormatException nfe) { - groupId = Integer.valueOf(elements[2]); - } - } - return groupId; - } - - /* Utility method to extract group base path from current page - * - */ - public static String groupPathLookup(String currentPage) { - String groupBasePath = ""; - if ((currentPage != null) && (!currentPage.trim().isEmpty())) { - String[] elements = currentPage.split("/"); - //process for groups and auto groups Ex. ResourceGroup/10111 , ResourceGroup/AutoCluster/10321 , Resource/AutoGroup/10141 - try { - Integer.valueOf(elements[1]); - groupBasePath = elements[0]; - } catch (NumberFormatException nfe) { - groupBasePath = elements[0] + "/" + elements[1]; - } - } - return groupBasePath; - } - public static class ChartViewWindow extends LocatableWindow {
public ChartViewWindow(String locatorId, String title) { 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 8d5d477..fb52d42 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 @@ -258,7 +258,8 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource updateSubTab(this.summaryTab, this.summaryActivity, true, true, new ViewFactory() { @Override public Canvas createView() { - return new ActivityView(summaryActivity.extendLocatorId("View"), groupComposite); + return new ActivityView(summaryActivity.extendLocatorId("View"), groupComposite, isAutoCluster(), + isAutoGroup()); } }); // TODO (ips): Add Timeline subtab? diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/ActivityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/ActivityView.java index c6b36b0..39d1b92 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/ActivityView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/ActivityView.java @@ -33,6 +33,7 @@ import com.smartgwt.client.widgets.events.ClickHandler;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.DashboardCriteria; import org.rhq.core.domain.criteria.ResourceGroupCriteria; @@ -53,7 +54,6 @@ import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardContainer; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardView; -import org.rhq.enterprise.gui.coregui.client.dashboard.PortletFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.groups.GroupAlertsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.groups.GroupBundleDeploymentsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.groups.GroupConfigurationUpdatesPortlet; @@ -77,6 +77,8 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer private static final String DASHBOARD_NAME_PREFIX = "GroupDashboard_";
private ResourceGroupComposite groupComposite; + private boolean isAutoGroup; + private boolean isAutoCluster;
private DashboardGWTServiceAsync dashboardService = GWTServiceLookup.getDashboardService();
@@ -98,9 +100,12 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer private int rowRight = 0; private boolean displayLeft = false;
- public ActivityView(String locatorId, ResourceGroupComposite groupComposite) { + public ActivityView(String locatorId, ResourceGroupComposite groupComposite, boolean isAutoCluster, + boolean isAutoGroup) { super(locatorId); this.groupComposite = groupComposite; + this.isAutoCluster = isAutoCluster; + this.isAutoGroup = isAutoGroup; }
@Override @@ -144,7 +149,10 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer Canvas[] members = getMembers(); removeMembers(members); //pass in the group information - dashboardView = new DashboardView(extendLocatorId(dashboard.getName()), this, dashboard, groupComposite, null); + EntityContext context = EntityContext.forGroup(groupComposite.getResourceGroup().getId(), isAutoCluster, + isAutoGroup); + dashboardView = new DashboardView(extendLocatorId(dashboard.getName()), this, dashboard, context, + groupComposite); addMember(dashboardView);
footer = new LocatableToolStrip(extendLocatorId("Footer")); @@ -203,11 +211,7 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer dashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, "#F1F2F3"));
//figure out which portlets to display and how - Map<String, String> groupKeyNameMap = new HashMap<String, String>(PortletFactory - .getRegisteredGroupPortletNameMap()); - //remove BundleDeployment and add back later if relevant. - groupKeyNameMap.remove(GroupBundleDeploymentsPortlet.KEY); - groupKeyNameMap = DashboardView.processPortletNameMapForGroup(groupKeyNameMap, groupComposite); + Map<String, String> groupKeyNameMap = DashboardView.processPortletNameMapForGroup(groupComposite);
//initiate asynch call to execute and then update the dashboard with bundle deployment portlet if necessary ResourceGroupCriteria criteria = new ResourceGroupCriteria(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView.java index ca227e2..c50bb71 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ActivityView.java @@ -13,6 +13,7 @@ import com.smartgwt.client.widgets.events.ClickHandler;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.DashboardCriteria; import org.rhq.core.domain.dashboard.Dashboard; @@ -28,7 +29,6 @@ import org.rhq.enterprise.gui.coregui.client.PermissionsLoader; import org.rhq.enterprise.gui.coregui.client.UserSessionManager; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardContainer; import org.rhq.enterprise.gui.coregui.client.dashboard.DashboardView; -import org.rhq.enterprise.gui.coregui.client.dashboard.PortletFactory; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource.ResourceAlertsPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource.ResourceConfigurationUpdatesPortlet; import org.rhq.enterprise.gui.coregui.client.dashboard.portlets.resource.ResourceMetricsPortlet; @@ -112,8 +112,8 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer Canvas[] members = getMembers(); removeMembers(members); //pass in the resource information - dashboardView = new DashboardView(extendLocatorId(dashboard.getName()), this, dashboard, null, - resourceComposite); + dashboardView = new DashboardView(extendLocatorId(dashboard.getName()), this, dashboard, EntityContext + .forResource(resourceComposite.getResource().getId()), resourceComposite); addMember(dashboardView);
footer = new LocatableToolStrip(extendLocatorId("Footer")); @@ -173,9 +173,7 @@ public class ActivityView extends LocatableVLayout implements DashboardContainer dashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, "#F1F2F3"));
//figure out which portlets to display and how - HashMap<String, String> resKeyNameMap = new HashMap<String, String>(PortletFactory - .getRegisteredResourcePortletNameMap()); - resKeyNameMap = DashboardView.processPortletNameMapForResource(resKeyNameMap, resourceComposite); + HashMap<String, String> resKeyNameMap = DashboardView.processPortletNameMapForResource(resourceComposite); int colLeft = 0; int colRight = 1; int rowLeft = 0; diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java index e337f0e..7c5fe15 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java @@ -377,7 +377,8 @@ public class ResourceTypeManagerBean implements ResourceTypeManagerLocal, Resour query.setParameter("resourceTypeId", resourceTypeId); List<ResourceFacets> facets = query.getResultList(); if (facets.size() != 1) { - return new ResourceFacets(resourceTypeId, false, false, false, false, false, false, false, false, false); + return new ResourceFacets(resourceTypeId, false, false, false, false, false, false, false, false, false, + false); } return facets.get(0); }
commit 3c15c6fd75e86c4959b7e80af70a76dcb8735be3 Author: Ian Springer ian.springer@redhat.com Date: Tue Aug 16 14:16:40 2011 -0400
[BZ 729961] compile the pt and zh GWT locales in coregui by default (https://bugzilla.redhat.com/show_bug.cgi?id=729961)
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index ca14c97..de77f3f 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -65,9 +65,11 @@ up gwt compilation. --> <gwt.draftCompile>false</gwt.draftCompile>
- <!-- Comma-separated list of the locales that should be included during GWT compilation. Currently supported - locales (i.e. locales for which we have localized message bundles) are "en", "de", and "ja". --> - <gwt.locale>en,de,ja</gwt.locale> + <!-- Comma-separated list of the locales that should be included during GWT compilation. The specified locales + should each have two corresponding message bundle properties files under + src/main/resources/org/rhq/enterprise/gui/coregui/client/. For example, the "ja" locale has + Messages_ja.properties and MessageConstants_ja.properties. --> + <gwt.locale>en,de,ja,pt,zh</gwt.locale> </properties>
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index fdfbcde..0f3e736 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -114,10 +114,10 @@ in which the corresponding GWT i18n interface class resides.
The gwt.locale property is substituted by the Maven resources plugin - during the resources phase. The default value (defined in coregui/pom.xml) - is "en,de,ja", which are the languages for which we currently have localized - messages. To override this value, specify the gwt.locale property on the - mvn command line (e.g. -Dgwt.locale=en) or in your ~/.m2/settings.xml. + during the resources phase. The default value for gwt.locale, defined in + coregui/pom.xml, includes all of the locales for which we currently have + message bundles. To override this value, specify the gwt.locale property on the + mvn command line (e.g. -Dgwt.locale=default) or in your ~/.m2/settings.xml. --> <extend-property name="locale" values="${gwt.locale}" /> <!-- If the user's locale is not supported, fallback to "en", rather than the "default" locale. -->
commit 71cb904e3916b1a32372bf9505058c6e66edfc0c Author: John Sanda jsanda@redhat.com Date: Tue Aug 16 13:20:34 2011 -0400
Adding drift server method for retrieving file content
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java index d326790..7eb875d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java @@ -31,6 +31,8 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.Table;
/** @@ -45,7 +47,12 @@ import javax.persistence.Table; */ @Entity @Table(name = "RHQ_DRIFT_FILE") +@NamedQueries({ + @NamedQuery(name = JPADriftFileBits.QUERY_FIND_BY_ID, query = "FROM JPADriftFileBits WHERE hashId = :hashId") +}) public class JPADriftFileBits extends AbstractJPADriftFile implements Serializable { + public static final String QUERY_FIND_BY_ID = "JPADriftFileBits.findById"; + private static final long serialVersionUID = 1L;
// this is a hash/digest that should uniquely identify the content diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index c5bb3ec..d2f2bc5 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -106,6 +106,12 @@ <version>${project.version}</version> </dependency>
+ <dependency> + <groupId>com.googlecode.java-diff-utils</groupId> + <artifactId>diffutils</artifactId> + <version>1.2.1</version> + </dependency> + <!--================ Test Deps ================-->
<!-- Note, the test deps are intentionally placed above the other scoped deps because of classpath 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 be4d2f6..1200a0d 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,9 +18,6 @@ */ package org.rhq.enterprise.server.drift;
-import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; -import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; - import java.io.File; import java.io.InputStream;
@@ -52,10 +49,10 @@ 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.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; -import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.RHQConstants; @@ -70,6 +67,9 @@ import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner; import org.rhq.enterprise.server.util.LookupUtil;
+import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; +import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + /** * The SLSB supporting Drift management to clients. * @@ -338,6 +338,13 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + @TransactionAttribute(NOT_SUPPORTED) + public String getDriftFileBits(String hash) { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.getDriftFileBits(hash); + } + + @Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) {
// before we do anything, make sure the drift config name is valid 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 cc515d3..9a435e4 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 @@ -107,4 +107,12 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR * @return number of orphaned drife files that were removed */ int purgeOrphanedDriftFiles(Subject subject); + + /** + * Returns the content associated with the specified hash as a string + * + * @param hash The hash the uniquely identifies the requested content + * @return The content as a string + */ + String getDriftFileBits(String hash); } 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 bf5be07..858051f 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 @@ -50,4 +50,12 @@ public interface DriftManagerRemote { */ PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) throws Exception;
+ /** + * Returns the content associated with the specified hash as a string + * + * @param hash The hash the uniquely identifies the requested content + * @return The content as a string + */ + String getDriftFileBits(String hash); + } 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 c55032e..74f03c2 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,14 +19,13 @@ */ package org.rhq.enterprise.server.drift;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; - import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; @@ -69,6 +68,7 @@ import org.rhq.core.domain.util.PageList; import org.rhq.core.util.StopWatch; import org.rhq.core.util.ZipUtil; import org.rhq.core.util.file.FileUtil; +import org.rhq.core.util.stream.StreamUtil; import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.agentclient.AgentClient; import org.rhq.enterprise.server.auth.SubjectManagerLocal; @@ -76,6 +76,8 @@ import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + /** * The SLSB method implementation needed to support the JPA (RHQ Default) Drift Server Plugin. * @@ -389,4 +391,18 @@ public class JPADriftServerBean implements JPADriftServerLocal { + "its contents are no longer needed. It can be deleted."); } } + + @Override + public String getDriftFileBits(String hash) { + // TODO add security + try { + JPADriftFileBits content = (JPADriftFileBits) entityManager.createNamedQuery( + JPADriftFileBits.QUERY_FIND_BY_ID).setParameter("hashId", hash).getSingleResult(); + byte[] bytes = StreamUtil.slurp(content.getBlob().getBinaryStream()); + return new String(bytes); + } catch (SQLException e) { + e.printStackTrace(); + 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 3f4f0f0..48e2a33 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 @@ -124,4 +124,6 @@ public interface JPADriftServerLocal { * @return number of orphaned drife files that were removed */ int purgeOrphanedDriftFiles(Subject subject); + + String getDriftFileBits(String hash); } 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 29e65e5..856439d 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 @@ -94,4 +94,12 @@ public interface DriftServerPluginFacet { * @return number of orphaned drife files that were removed */ int purgeOrphanedDriftFiles(Subject subject); + + /** + * Returns the content associated with the specified hash as a string + * + * @param hash The hash the uniquely identifies the requested content + * @return The content as a string + */ + String getDriftFileBits(String hash); } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java new file mode 100644 index 0000000..b0616ac --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/JPADriftServerBeanTest.java @@ -0,0 +1,70 @@ +/* + * 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.server.drift; + +import javax.persistence.EntityManager; + +import org.hibernate.Hibernate; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.rhq.core.domain.drift.JPADriftFileBits; +import org.rhq.enterprise.server.test.AbstractEJB3Test; +import org.rhq.enterprise.server.util.LookupUtil; +import org.rhq.test.TransactionCallback; + +import static org.rhq.core.domain.drift.DriftFileStatus.LOADED; +import static org.rhq.test.JPAUtils.executeInTransaction; + +public class JPADriftServerBeanTest extends AbstractEJB3Test { + + @BeforeMethod + public void initDB() { + executeInTransaction(new TransactionCallback() { + @Override + public void execute() throws Exception { + EntityManager em = getEntityManager(); + em.createQuery("delete from JPADriftFileBits").executeUpdate(); + } + }); + } + + @Test + public void saveAndLoadFileContent() throws Exception { + String string = "Testing saving and loading content"; + + final JPADriftFileBits content = new JPADriftFileBits("a1b2c3"); + content.setStatus(LOADED); + content.setDataSize((long) string.length()); + content.setData(Hibernate.createBlob(string.getBytes())); + + executeInTransaction(new TransactionCallback() { + @Override + public void execute() throws Exception { + EntityManager em = getEntityManager(); + em.persist(content); + } + }); + JPADriftServerLocal driftServer = LookupUtil.getJPADriftServer(); + + assertEquals("Failed to load content", string, driftServer.getDriftFileBits(content.getHashId())); + } + +} 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 d0db7d0..c641694 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 @@ -19,8 +19,6 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; - import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; @@ -66,6 +64,8 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; import org.rhq.enterprise.server.resource.ResourceManagerLocal;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; + public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
//private final Log log = LogFactory.getLog(MongoDBDriftServer.class); @@ -227,6 +227,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC return 0; }
+ @Override + public String getDriftFileBits(String hash) { + return null; + } + Map<Integer, Resource> loadResourceMap(Subject subject, Integer[] resourceIds) { ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterIds(resourceIds); 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 4d228bb..99abc1c 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 @@ -19,8 +19,6 @@ */ package org.rhq.enterprise.server.plugins.drift;
-import static org.rhq.enterprise.server.util.LookupUtil.getJPADriftServer; - import java.io.File;
import org.apache.commons.logging.Log; @@ -41,6 +39,8 @@ import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent; import org.rhq.enterprise.server.plugin.pc.ServerPluginContext; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
+import static org.rhq.enterprise.server.util.LookupUtil.getJPADriftServer; + /** * A drift server-side plugin component that the server uses to process drift files. * @@ -122,4 +122,9 @@ public class JPADriftServerPluginComponent implements DriftServerPluginFacet, Se public int purgeOrphanedDriftFiles(Subject subject) { return getJPADriftServer().purgeOrphanedDriftFiles(subject); } + + @Override + public String getDriftFileBits(String hash) { + return getJPADriftServer().getDriftFileBits(hash); + } } diff --git a/modules/test-utils/src/main/java/org/rhq/test/JPAUtils.java b/modules/test-utils/src/main/java/org/rhq/test/JPAUtils.java index cff3343..6e887c5 100644 --- a/modules/test-utils/src/main/java/org/rhq/test/JPAUtils.java +++ b/modules/test-utils/src/main/java/org/rhq/test/JPAUtils.java @@ -60,10 +60,18 @@ public class JPAUtils { } catch (SystemException e) { throw new RuntimeException("Failed to rollback transaction", e); } - throw new RuntimeException(t.getCause()); + Throwable rootCause = getRootCause(t); + throw new RuntimeException(rootCause); } }
+ private static Throwable getRootCause(Throwable t) { + while ((t.getCause() != null) && (t != t.getCause())) { + t = t.getCause(); + } + return t; + } + public static void clearDB() { executeInTransaction(new TransactionCallback() { @Override
commit 5bdcd83af54cd10ff4b78bfba66db7330a11abd5 Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 16 11:52:35 2011 -0400
add the system setting "drift file purge" which lets you indicate how old an orphaned drift file must be before it gets purged
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index c2a4c7f..aa20853 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -16,7 +16,7 @@ </scm> <properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.113</db.schema.version> + <db.schema.version>2.114</db.schema.version> <rhq.ds.type-mapping>${rhq.test.ds.type-mapping}</rhq.ds.type-mapping> <rhq.ds.db-name>${rhq.test.ds.db-name}</rhq.ds.db-name> <rhq.ds.connection-url>${rhq.test.ds.connection-url}</rhq.ds.connection-url> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml index 0675792..6af4dd7 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml @@ -129,6 +129,10 @@ <data ID="57" PROPERTY_KEY="ACTIVE_DRIFT_PLUGIN" PROPERTY_VALUE="drift-jpa" DEFAULT_PROPERTY_VALUE="drift-jpa" FREAD_ONLY="FALSE"/>
+ <!-- purge drift files older than 7 days by default --> + <data ID="58" PROPERTY_KEY="DRIFT_FILE_PURGE" PROPERTY_VALUE="604800000" + DEFAULT_PROPERTY_VALUE="604800000" FREAD_ONLY="FALSE"/> + </table>
</dbsetup> diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index 8dcc549..1315d9f 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3616,6 +3616,16 @@ </statement> </schema-directSQL> </schemaSpec> + + <schemaSpec version="2.114"> + <schema-directSQL> + <statement desc="Adding drift file purge system setting"> + INSERT INTO rhq_system_config (id, property_key, property_value, default_property_value) + VALUES (58, 'DRIFT_FILE_PURGE', '604800000', '604800000') + </statement> + </schema-directSQL> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java index e426a78..2e18fed 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java @@ -61,11 +61,14 @@ public class JPADriftFile extends AbstractJPADriftFile implements Serializable, * * Therefore, we need to define a native query that we know works. This should be periodically executed * in order to purge unused drift files. + * + * Note that we also add the AND clause to also check for CTIME. */ public static final String NATIVE_DELETE_ORPHANED_DRIFT_FILES = "" // + "DELETE FROM RHQ_DRIFT_FILE " // + " WHERE (HASH_ID NOT IN (SELECT OLD_DRIFT_FILE FROM RHQ_DRIFT)) " // - + " AND (HASH_ID NOT IN (SELECT NEW_DRIFT_FILE FROM RHQ_DRIFT)) "; + + " AND (HASH_ID NOT IN (SELECT NEW_DRIFT_FILE FROM RHQ_DRIFT)) " // + + " AND CTIME < ?";
// this is a hash/digest that should uniquely identify the content @Id diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java index 01d0260..a489ce3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java @@ -87,6 +87,7 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu String TraitPurge = "TRAIT_PURGE"; String RtDataPurge = "RT_DATA_PURGE"; String EventPurge = "EVENT_PURGE"; + String DriftFilePurge = "DRIFT_FILE_PURGE"; String DataReindex = "DATA_REINDEX_NIGHTLY"; String BaselineFrequency = "CAM_BASELINE_FREQUENCY"; String BaselineDataSet = "CAM_BASELINE_DATASET"; @@ -153,8 +154,8 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu value = convertMillisToHours(value); } else if (Constant.AvailabilityPurge.equals(name) || Constant.AlertPurge.equals(name) || Constant.TraitPurge.equals(name) || Constant.RtDataPurge.equals(name) - || Constant.EventPurge.equals(name) || Constant.BaselineFrequency.equals(name) - || Constant.BaselineDataSet.equals(name)) { + || Constant.EventPurge.equals(name) || Constant.DriftFilePurge.equals(name) + || Constant.BaselineFrequency.equals(name) || Constant.BaselineDataSet.equals(name)) { value = convertMillisToDays(value); } else if (Constant.EnableAgentAutoUpdate.equals(name)) { if (value.trim().length() == 0) { @@ -250,6 +251,7 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu } else if (Constant.AvailabilityPurge.equals(simple.getName()) || Constant.AlertPurge.equals(simple.getName()) || Constant.TraitPurge.equals(simple.getName()) || Constant.RtDataPurge.equals(simple.getName()) || Constant.EventPurge.equals(simple.getName()) + || Constant.DriftFilePurge.equals(simple.getName()) || Constant.BaselineFrequency.equals(simple.getName()) || Constant.BaselineDataSet.equals(simple.getName())) { value = convertDaysToMillis(value); @@ -416,6 +418,14 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu eventPurge.setDefaultValue("14"); def.put(eventPurge);
+ PropertyDefinitionSimple driftFilePurge = new PropertyDefinitionSimple(Constant.DriftFilePurge, MSG + .view_admin_systemSettings_DriftFilePurge_desc(), true, PropertySimpleType.INTEGER); + driftFilePurge.setDisplayName(MSG.view_admin_systemSettings_DriftFilePurge_name()); + driftFilePurge.setPropertyGroupDefinition(dataManagerGroup); + driftFilePurge.addConstraints(new IntegerRangeConstraint(Long.valueOf(1), null)); + driftFilePurge.setDefaultValue("7"); + def.put(driftFilePurge); + PropertyDefinitionSimple dataReindex = new PropertyDefinitionSimple(Constant.DataReindex, MSG .view_admin_systemSettings_DataReindex_desc(), true, PropertySimpleType.BOOLEAN); dataReindex.setDisplayName(MSG.view_admin_systemSettings_DataReindex_name()); @@ -634,8 +644,10 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu form.setValue(dbProductVersion.getName(), details.get(ServerDetails.Detail.DATABASE_PRODUCT_VERSION)); form.setValue(dbDriverName.getName(), details.get(ServerDetails.Detail.DATABASE_DRIVER_NAME)); form.setValue(dbDriverVersion.getName(), details.get(ServerDetails.Detail.DATABASE_DRIVER_VERSION)); - form.setValue(currentMeasRawTable.getName(), details.get(ServerDetails.Detail.CURRENT_MEASUREMENT_TABLE)); - form.setValue(nextMeasTableRotation.getName(), details.get(ServerDetails.Detail.NEXT_MEASUREMENT_TABLE_ROTATION)); + form.setValue(currentMeasRawTable.getName(), details + .get(ServerDetails.Detail.CURRENT_MEASUREMENT_TABLE)); + form.setValue(nextMeasTableRotation.getName(), details + .get(ServerDetails.Detail.NEXT_MEASUREMENT_TABLE_ROTATION)); }
@Override 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 1202d66..738325e 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 @@ -545,6 +545,8 @@ view_admin_systemSettings_DataMaintenance_desc = How often database maintenance view_admin_systemSettings_DataMaintenance_name = Database Maintenance Period view_admin_systemSettings_DataReindex_desc = If enabled, certain database tables will be re-indexed periodically. view_admin_systemSettings_DataReindex_name = Reindex Data Tables Nightly +view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days. +view_admin_systemSettings_DriftFilePurge_name = Delete Unused Drift Files Older Than view_admin_systemSettings_EnableAgentAutoUpdate_desc = Determines if the server will allow agents to auto-update themselves. You will not be able to download agent distributions from the server if this is disabled. view_admin_systemSettings_EnableAgentAutoUpdate_name = Enable Agent Auto-Updates view_admin_systemSettings_EnableDebugMode_desc = If enabled, the server will enter debug mode. 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 dab0660..30200c8 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 @@ -462,6 +462,8 @@ view_admin_security = Sicherheit ##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die Àlter sind als view_admin_systemSettings_AvailabilityPurge_name = Lösche VerfÃŒgbarkeitsdaten, die Àlter sind als +##view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days. +##view_admin_systemSettings_DriftFilePurge_name = Delete Unused Drift Files Older Than view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die Àlter sind als ##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_saveFailure = Das Speichern der Systemeinstellungen ist fehlgeschlagen 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 6d346b1..e06d91f 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 @@ -540,6 +540,8 @@ view_admin_systemSettings_DataMaintenance_desc = ããŒã¿ããŒã¹ã®ä¿å®ã view_admin_systemSettings_DataMaintenance_name = ããŒã¿ããŒã¹ä¿å®æé view_admin_systemSettings_DataReindex_desc = ããæå¹ã§ããã°ãããŒã¿ããŒã¹ããŒãã«ã¯å®æçã«ã€ã³ããã¯ã¹ãåçæãããŸãã view_admin_systemSettings_DataReindex_name = ããŒã¿ããŒãã«ã®å€éã§ã®ã€ã³ããã¯ã¹åçæ +##view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days. +##view_admin_systemSettings_DriftFilePurge_name = Delete Unused Drift Files Older Than view_admin_systemSettings_EnableAgentAutoUpdate_desc = ãµãŒããŒããšãŒãžã§ã³ããèªåæŽæ°ããããšãèš±ããã©ããã決å®ããŸãããããããç¡å¹ã«ãããŠããã®ã§ããã°ããµãŒããŒãããšãŒãžã§ã³ãã®ãã£ã¹ããªãã¥ãŒã·ã§ã³ãããŠã³ããŒãããããšã¯ã§ããŸããã view_admin_systemSettings_EnableAgentAutoUpdate_name = ãšãŒãžã§ã³ãã®èªåæŽæ°ãæå¹ã«ãã view_admin_systemSettings_EnableDebugMode_desc = æå¹ã§ããã°ããµãŒããŒã¯ãããã°ã¢ãŒãã«å ¥ããŸã 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 ed95acd..2554833 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 @@ -556,6 +556,8 @@ view_admin_systemSettings_DataMaintenance_desc = How often database maintenance view_admin_systemSettings_DataMaintenance_name = Database Maintenance Period view_admin_systemSettings_DataReindex_desc = If enabled, certain database tables will be re-indexed periodically. view_admin_systemSettings_DataReindex_name = Reindex Data Tables Nightly +##view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days. +##view_admin_systemSettings_DriftFilePurge_name = Delete Unused Drift Files Older Than view_admin_systemSettings_EnableAgentAutoUpdate_desc = Determines if the server will allow agents to auto-update themselves. You will not be able to download agent distributions from the server if this is disabled. view_admin_systemSettings_EnableAgentAutoUpdate_name = Enable Agent Auto-Updates view_admin_systemSettings_EnableDebugMode_desc = If enabled, the server will enter debug mode. 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 f954437..034fe18 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 @@ -539,6 +539,8 @@ view_admin_systemSettings_DataMaintenance_desc = How often database maintenance view_admin_systemSettings_DataMaintenance_name = \u6570\u636e\u5e93\u7ef4\u62a4\u671f\u95f4 view_admin_systemSettings_DataReindex_desc = \u5982\u679c\u542f\u7528,\u67d0\u4e9b\u6570\u636e\u8868\u4f1a\u5b9a\u671f\u88ab\u7d22\u5f15. view_admin_systemSettings_DataReindex_name = \u6bcf\u665a\u91cd\u65b0\u7d22\u5f15\u6570\u636e\u8868 +##view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days. +##view_admin_systemSettings_DriftFilePurge_name = Delete Unused Drift Files Older Than view_admin_systemSettings_EnableAgentAutoUpdate_desc = Determines if the server will allow agents to auto-update themselves. You will not be able to download agent distributions from the server if this is disabled. view_admin_systemSettings_EnableAgentAutoUpdate_name = \u542f\u7528\u4ee3\u7406\u81ea\u52a8\u5347\u7ea7 view_admin_systemSettings_EnableDebugMode_desc = \u5982\u679c\u542f\u7528,\u670d\u52a1\u5668\u5c06\u8fdb\u5165debug\u6a21\u5f0f. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/RHQConstants.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/RHQConstants.java index db51c99..bbd1a0d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/RHQConstants.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/RHQConstants.java @@ -91,6 +91,9 @@ public class RHQConstants { // How long do we keep event data public static final String EventPurge = "EVENT_PURGE";
+ // How long do we keep orphaned drift files + public static final String DriftFilePurge = "DRIFT_FILE_PURGE"; + // How long do we keep trait data public static final String TraitPurge = "TRAIT_PURGE";
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 be4d2f6..fd339e2 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 @@ -332,9 +332,9 @@ public class DriftManagerBean implements DriftManagerLocal {
@Override @TransactionAttribute(NOT_SUPPORTED) - public int purgeOrphanedDriftFiles(Subject subject) { + public int purgeOrphanedDriftFiles(Subject subject, long purgeMillis) { DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - return driftServerPlugin.purgeOrphanedDriftFiles(subject); + return driftServerPlugin.purgeOrphanedDriftFiles(subject, purgeMillis); }
@Override 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 cc515d3..014d089 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 @@ -104,7 +104,8 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR * to help reclaim space on the backend. * * @param subject + * @param purgeMillis only those unused drift files that are older than this (in epoch millis) will be purged. * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); } 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 c55032e..a06ece0 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 @@ -100,8 +100,9 @@ public class JPADriftServerBean implements JPADriftServerLocal {
@Override @TransactionAttribute(REQUIRES_NEW) - public int purgeOrphanedDriftFiles(Subject subject) { + public int purgeOrphanedDriftFiles(Subject subject, long purgeMillis) { Query q = entityManager.createNativeQuery(JPADriftFile.NATIVE_DELETE_ORPHANED_DRIFT_FILES); + q.setParameter(1, purgeMillis); int count = q.executeUpdate(); log.debug("purged [" + count + "] drift files that were orphaned (that is, no longer referenced by drift)"); return count; 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 3f4f0f0..8105c82 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 @@ -121,7 +121,8 @@ public interface JPADriftServerLocal { * to help reclaim space on the backend. * * @param subject + * @param purgeMillis * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); } 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 29e65e5..c4118e1 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 @@ -91,7 +91,8 @@ public interface DriftServerPluginFacet { * to help reclaim space on the backend. * * @param subject + * @param purgeMillis only those unused drift files that are older than this (in epoch millis) will be purged. * @return number of orphaned drife files that were removed */ - int purgeOrphanedDriftFiles(Subject subject); + int purgeOrphanedDriftFiles(Subject subject, long purgeMillis); } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java index 3423540..0cc04f4 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java @@ -121,7 +121,7 @@ public class DataPurgeJob extends AbstractStatefulJob { purgeOrphanedAlertNotifications(LookupUtil.getAlertNotificationManager()); purgeMeasurementTraitData(LookupUtil.getMeasurementDataManager(), systemConfig); purgeAvailabilityData(LookupUtil.getAvailabilityManager(), systemConfig); - purgeOrphanedDriftFiles(LookupUtil.getDriftManager()); + purgeOrphanedDriftFiles(LookupUtil.getDriftManager(), systemConfig); }
private void purgeMeasurementTraitData(MeasurementDataManagerLocal measurementDataManager, Properties systemConfig) { @@ -254,13 +254,16 @@ public class DataPurgeJob extends AbstractStatefulJob { } }
- private void purgeOrphanedDriftFiles(DriftManagerLocal driftManager) { + private void purgeOrphanedDriftFiles(DriftManagerLocal driftManager, Properties systemConfig) { long timeStart = System.currentTimeMillis(); LOG.info("Drift file orphan purge starting at " + new Date(timeStart)); int orphansPurged = 0;
try { - orphansPurged = driftManager.purgeOrphanedDriftFiles(LookupUtil.getSubjectManager().getOverlord()); + long threshold = timeStart - Long.parseLong(systemConfig.getProperty(RHQConstants.DriftFilePurge)); + LOG.info("Purging orphaned drift files older than " + new Date(threshold)); + orphansPurged = driftManager.purgeOrphanedDriftFiles(LookupUtil.getSubjectManager().getOverlord(), + threshold); } catch (Exception e) { LOG.error("Failed to purge orphaned drift files. Cause: " + e, e); } finally { 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 d0db7d0..d007c38 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 @@ -222,7 +222,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC }
@Override - public int purgeOrphanedDriftFiles(Subject subject) { + public int purgeOrphanedDriftFiles(Subject subject, long purgeMillis) { // TODO implement me! return 0; } 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 4d228bb..44e85ca 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 @@ -119,7 +119,7 @@ public class JPADriftServerPluginComponent implements DriftServerPluginFacet, Se }
@Override - public int purgeOrphanedDriftFiles(Subject subject) { - return getJPADriftServer().purgeOrphanedDriftFiles(subject); + public int purgeOrphanedDriftFiles(Subject subject, long purgeMillis) { + return getJPADriftServer().purgeOrphanedDriftFiles(subject, purgeMillis); } }
commit 8028438c2a0db943586ca3d200f937e628326de0 Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 16 11:49:17 2011 -0400
opps.. used wrong prop name - forgot "Server"
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 45c9729..1202d66 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 @@ -527,8 +527,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Security -view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. 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 5114451..dab0660 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 @@ -458,8 +458,8 @@ view_admin_downloads_cli_md5 = MD5 PrÃŒfsumme des CLI view_admin_downloads_cli_version = Version des CLI view_admin_landing = In dieser Sektion können die globalen Einstellungen fÃŒr RHQ verwaltet werden. Dies schlieÃt Sicherheitseinstellungen und Plugins ein, sowie die Verwaltung der RHQ Server- und Agentplugins. view_admin_security = Sicherheit -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die Àlter sind als view_admin_systemSettings_AvailabilityPurge_name = Lösche VerfÃŒgbarkeitsdaten, die Àlter sind als view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die Àlter sind als 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 fe2b270..6d346b1 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 @@ -522,8 +522,8 @@ view_admin_measTemplates_title = ãã³ãã¬ãŒãã¡ããªãã¯åéã¹ã± view_admin_measTemplates_updateExisting_title = æ¢åã¹ã±ãžã¥ãŒã«ã®æŽæ° view_admin_measTemplates_updateExisting_tooltip = ãã®ããã¯ã¹ããã§ãã¯ãããšããã®ã¿ã€ãã®ãã¹ãŠã®ãªãœãŒã¹ã察象ã«éžæããã¡ããªãã¯ã¹ã®åéã¹ã±ãžã¥ãŒã«ãæŽæ°ããŸããããããããã§ãã¯ãããŠããªããã°ããã³ãã¬ãŒãã¹ã±ãžã¥ãŒã«ãå°æ¥çã«ã€ã³ãã³ããªã«è¿œå ããããã®ã¿ã€ãã®æ°èŠãªãœãŒã¹ã«é©çšãããã ãã§ãã view_admin_security = ã»ãã¥ãªã㣠-##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = ãããšãŒãžã§ã³ãããäœãåä¿¡ããªãã§ãã®æéãçµéãããªãã°ããã®ãšãŒãžã§ã³ãã¯ããŠã³ãããã®ãšèŠãªãããŸãããã®å€ã¯ååäœã§æå®ãããŸãã view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = 蚱容ãããæ倧ç¡éä¿¡æé view_admin_systemSettings_AlertPurge_desc = ããŒã¿ããŒã¹ããé€å»ãããåã®ã¢ã©ãŒããã¹ããªã®ä¿ææéãããã¯æ¥åäœã§æå®ãããŸãã 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 8cff968..ed95acd 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 @@ -538,8 +538,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Seguran\u00E7a -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. 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 2b71193..f954437 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 @@ -521,8 +521,8 @@ view_admin_measTemplates_title = \u6a21\u677f\u6307\u6807\u96c6\u8ba1\u5212\u4ef view_admin_measTemplates_updateExisting_title = \u66f4\u65b0\u5b58\u5728\u7684\u8ba1\u5212\u4efb\u52a1 view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = \u5b89\u5168 -##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. -##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin +##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftServerPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = \u4ee3\u7406\u6700\u591a\u5141\u8bb8\u9759\u9ed8\u65f6\u95f4 view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days.
commit 7cab4f7bbd7b15f0f96297f3970bc8d3956014cb Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 16 11:43:42 2011 -0400
clean up active drift plugin system settings - make i18n messages, remove unused constant
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java index 5804f9d..01d0260 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java @@ -105,7 +105,6 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu String LDAPBindPW = "CAM_LDAP_BIND_PW";
String ACTIVE_DRIFT_PLUGIN = "ACTIVE_DRIFT_PLUGIN"; - String DRIFT_PLUGINS = "DRIFT_PLUGINS"; }
public SystemSettingsView(String locatorId) { @@ -309,11 +308,10 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu * be converted to the types the definition will expect - for example, * the JAAS setting will not be "LDAP" or "JDBC" as the server would know it, * rather the value will be "true" or "false" (i.e. is ldap enabled or not?) - * + * @param driftPlugins the set of drift server plugins that are currently deployed * @return system settings config def */ - private ConfigurationDefinition getSystemSettingsDefinition(Configuration config, - Map<String, String> driftPlugins) { + private ConfigurationDefinition getSystemSettingsDefinition(Configuration config, Map<String, String> driftPlugins) { ConfigurationDefinition def = new ConfigurationDefinition("sysset", MSG.view_adminConfig_systemSettings());
/////////////////////////////////// @@ -530,20 +528,19 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu /////////////////////////////////////////// // Drift Server Configuration Properties // /////////////////////////////////////////// - PropertyGroupDefinition driftGroup = new PropertyGroupDefinition("drift server"); - driftGroup.setDisplayName("Drift Server Configuration Settings"); + PropertyGroupDefinition driftGroup = new PropertyGroupDefinition("drift"); + driftGroup.setDisplayName(MSG.view_admin_systemSettings_group_drift()); driftGroup.setOrder(4); driftGroup.setDefaultHidden(false);
- PropertyDefinitionSimple activeDriftServer = new PropertyDefinitionSimple("ACTIVE_DRIFT_PLUGIN", - "The drift server plugin that manages the persistence of drift-related entities and content", true, - PropertySimpleType.STRING); - activeDriftServer.setDisplayName("Active Drift Server Plugin"); + PropertyDefinitionSimple activeDriftServer = new PropertyDefinitionSimple(Constant.ACTIVE_DRIFT_PLUGIN, MSG + .view_admin_systemSettings_ActiveDriftServerPlugin_desc(), true, PropertySimpleType.STRING); + activeDriftServer.setDisplayName(MSG.view_admin_systemSettings_ActiveDriftServerPlugin_name()); activeDriftServer.setPropertyGroupDefinition(driftGroup);
List<PropertyDefinitionEnumeration> options = new ArrayList<PropertyDefinitionEnumeration>(); for (Map.Entry<String, String> entry : driftPlugins.entrySet()) { - options.add(new PropertyDefinitionEnumeration(entry.getValue(), entry.getKey())) ; + options.add(new PropertyDefinitionEnumeration(entry.getValue(), entry.getKey())); }
activeDriftServer.setEnumeratedValues(options, false); 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 3523d7b..45c9729 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 @@ -527,6 +527,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Security +view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -580,6 +582,7 @@ view_admin_systemSettings_cannotLoadSettings = Cannot obtain the current system view_admin_systemSettings_fixBeforeSaving = Please fix the invalid values before saving view_admin_systemSettings_group_baseline = Automatic Baseline Configuration Properties view_admin_systemSettings_group_dataMgr = Data Manager Configuration Properties +view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = General Configuration Properties view_admin_systemSettings_group_ldap = LDAP Configuration Properties view_admin_systemSettings_saveFailure = Failed to save the system settings 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 c1c3dee..5114451 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 @@ -458,9 +458,12 @@ view_admin_downloads_cli_md5 = MD5 PrÃŒfsumme des CLI view_admin_downloads_cli_version = Version des CLI view_admin_landing = In dieser Sektion können die globalen Einstellungen fÃŒr RHQ verwaltet werden. Dies schlieÃt Sicherheitseinstellungen und Plugins ein, sowie die Verwaltung der RHQ Server- und Agentplugins. view_admin_security = Sicherheit +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die Àlter sind als view_admin_systemSettings_AvailabilityPurge_name = Lösche VerfÃŒgbarkeitsdaten, die Àlter sind als view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die Àlter sind als +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_saveFailure = Das Speichern der Systemeinstellungen ist fehlgeschlagen view_admin_systemSettings_savedSettings = Sie haben die Systemeinstellungen erfolgreich gespeichert view_admin_systemSettings_serverDetails_currentTable = Aktuelle Datenbanktablee fÃŒr Metrikdaten 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 61d2676..fe2b270 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 @@ -522,6 +522,8 @@ view_admin_measTemplates_title = ãã³ãã¬ãŒãã¡ããªãã¯åéã¹ã± view_admin_measTemplates_updateExisting_title = æ¢åã¹ã±ãžã¥ãŒã«ã®æŽæ° view_admin_measTemplates_updateExisting_tooltip = ãã®ããã¯ã¹ããã§ãã¯ãããšããã®ã¿ã€ãã®ãã¹ãŠã®ãªãœãŒã¹ã察象ã«éžæããã¡ããªãã¯ã¹ã®åéã¹ã±ãžã¥ãŒã«ãæŽæ°ããŸããããããããã§ãã¯ãããŠããªããã°ããã³ãã¬ãŒãã¹ã±ãžã¥ãŒã«ãå°æ¥çã«ã€ã³ãã³ããªã«è¿œå ããããã®ã¿ã€ãã®æ°èŠãªãœãŒã¹ã«é©çšãããã ãã§ãã view_admin_security = ã»ãã¥ãªã㣠+##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = ãããšãŒãžã§ã³ãããäœãåä¿¡ããªãã§ãã®æéãçµéãããªãã°ããã®ãšãŒãžã§ã³ãã¯ããŠã³ãããã®ãšèŠãªãããŸãããã®å€ã¯ååäœã§æå®ãããŸãã view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = 蚱容ãããæ倧ç¡éä¿¡æé view_admin_systemSettings_AlertPurge_desc = ããŒã¿ããŒã¹ããé€å»ãããåã®ã¢ã©ãŒããã¹ããªã®ä¿ææéãããã¯æ¥åäœã§æå®ãããŸãã @@ -575,6 +577,7 @@ view_admin_systemSettings_cannotLoadSettings = çŸåšã®ã·ã¹ãã èšå®ãå view_admin_systemSettings_fixBeforeSaving = ä¿ååã«ç¡å¹ãªå€ãä¿®æ£ããŠãã ãã view_admin_systemSettings_group_baseline = èªåããŒã¹ã©ã€ã³æ§æãããã㣠view_admin_systemSettings_group_dataMgr = ããŒã¿ãããŒãžã£ãŒæ§æãããã㣠+##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = å šäœæ§æãããã㣠view_admin_systemSettings_group_ldap = LDAPæ§æãããã㣠view_admin_systemSettings_saveFailure = ã·ã¹ãã èšå®ã®ä¿åã«å€±æããŸãã 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 4068998..8cff968 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 @@ -538,6 +538,8 @@ view_admin_measTemplates_title = Template Metric Collection Schedules view_admin_measTemplates_updateExisting_title = Update Existing Schedules view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = Seguran\u00E7a +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = Agent Max Quiet Time Allowed view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -591,6 +593,7 @@ view_admin_systemSettings_cannotLoadSettings = Cannot obtain the current system view_admin_systemSettings_fixBeforeSaving = Please fix the invalid values before saving view_admin_systemSettings_group_baseline = Automatic Baseline Configuration Properties view_admin_systemSettings_group_dataMgr = Data Manager Configuration Properties +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = General Configuration Properties view_admin_systemSettings_group_ldap = LDAP Configuration Properties view_admin_systemSettings_saveFailure = Failed to save the system settings 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 4bda92e..2b71193 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 @@ -521,6 +521,8 @@ view_admin_measTemplates_title = \u6a21\u677f\u6307\u6807\u96c6\u8ba1\u5212\u4ef view_admin_measTemplates_updateExisting_title = \u66f4\u65b0\u5b58\u5728\u7684\u8ba1\u5212\u4efb\u52a1 view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future. view_admin_security = \u5b89\u5168 +##view_admin_systemSettings_ActiveDriftPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content. +##view_admin_systemSettings_ActiveDriftPlugin_name = Active Drift Server Plugin view_admin_systemSettings_AgentMaxQuietTimeAllowed_desc = If this amount of time passes without hearing from an agent, that quiet agent will be considered down. This value is specified in minutes. view_admin_systemSettings_AgentMaxQuietTimeAllowed_name = \u4ee3\u7406\u6700\u591a\u5141\u8bb8\u9759\u9ed8\u65f6\u95f4 view_admin_systemSettings_AlertPurge_desc = How old alert history items must be before being purged from the database. This is specified in days. @@ -574,6 +576,7 @@ view_admin_systemSettings_cannotLoadSettings = \u65e0\u6cd5\u83b7\u5f97\u5f53\u5 view_admin_systemSettings_fixBeforeSaving = \u4fdd\u5b58\u524d\u8bf7\u4fee\u590d\u9519\u8bef view_admin_systemSettings_group_baseline = \u81ea\u52a8Baseline\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_group_dataMgr = \u6570\u636e\u7ba1\u7406\u5668\u57fa\u672c\u5c5e\u6027 +##view_admin_systemSettings_group_drift = Drift Server Configuration Settings view_admin_systemSettings_group_general = \u57fa\u672c\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_group_ldap = LDAP\u914d\u7f6e\u5c5e\u6027 view_admin_systemSettings_saveFailure = \u4fdd\u5b58\u7cfb\u7edf\u5c5e\u6027\u5931\u8d25
commit 9645f3ed8eb7374452dfc4998e0c476aac1957ed Merge: 2f858f7 99ec567 Author: Heiko W. Rupp hwr@redhat.com Date: Tue Aug 16 15:20:00 2011 +0200
Merge branch 'as7plugin'
commit 99ec567c4ac3141036f4a21ae03d5b792a7f2fb0 Author: Heiko W. Rupp hwr@redhat.com Date: Tue Aug 16 15:02:18 2011 +0200
BZ 730940 and BZ 729934 Fix some possible NPEs with child resource creation.
Basically createResource() is overloaded and the plugin code needs to better distinguish if the create happens via package upload or configuration
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java index e5e8a36..0eb49db 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java @@ -270,7 +270,7 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi @Override public CreateResourceReport createResource(CreateResourceReport report) {
- if (context.getContentContext() != null) { // Content deployment + if (report.getPackageDetails() != null) { // Content deployment return deployContent(report); } else { report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION); @@ -303,7 +303,7 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi * @param report Create resource report that tells us what to do * @return report that tells us what has been done. */ - private CreateResourceReport deployContent(CreateResourceReport report) { + protected CreateResourceReport deployContent(CreateResourceReport report) { ContentContext cctx = context.getContentContext(); ResourcePackageDetails details = report.getPackageDetails();
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java index c35f9fe..2119a52 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerComponent.java @@ -70,8 +70,11 @@ public class HostControllerComponent extends BaseServerComponent implements Oper @Override public CreateResourceReport createResource(CreateResourceReport report) {
- // TODO check for types of children -- this is server group only at the moment. + // If Content is to be deployed, call the deployContent method + if (report.getPackageDetails()!=null) + return super.deployContent(report);
+ // TODO check for types of children -- this is server group only at the moment. String name = report.getUserSpecifiedResourceName(); Address address = new Address(path); address.add("server-group",name); @@ -94,7 +97,7 @@ public class HostControllerComponent extends BaseServerComponent implements Oper op.addAdditionalProperty("socket-binding-group",socketBindingGroup); PropertySimple offset = rc.getSimple("socket-binding-port-offset"); if (offset!=null && offset.getStringValue()!=null) - op.addAdditionalProperty("socket-binding-port-offset",offset); + op.addAdditionalProperty("socket-binding-port-offset",offset.getIntegerValue()); // TODO add jvm info
Result res = getASConnection().execute(op);
commit 484761369161fba23cf5ac228392e77d352075a9 Merge: bf35e3c 2f858f7 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 16 12:22:50 2011 +0200
Merge remote-tracking branch 'origin/master' into feature/config-sync
commit 2e01c5d41794d1b1524579ee65e0af2b08771d6b Merge: 251d440 2f858f7 Author: John Sanda jsanda@redhat.com Date: Mon Aug 15 21:57:06 2011 -0400
Merge branch 'master' into drift
Conflicts: modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderImpl.java modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriterImpl.java modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetReaderImplTest.java modules/common/drift/src/test/java/org/rhq/common/drift/ChangeSetWriterImplTest.java modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfiguration.java modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.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/test/java/org/rhq/core/pc/drift/ChangeSetManagerImplTest.java modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftDataSource.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/ResourceDriftChangeSetsTreeView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/DriftGWTServiceImpl.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerBean.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftManagerLocal.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/drift/DriftManagerBeanTest.java modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java
commit 251d440074e04fbbf66032b849d82906f47650f1 Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 15 16:30:45 2011 -0400
provide the ability to detect drift and delete from config menu
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 212e183..cdaf5af 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 @@ -173,6 +173,20 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid protected abstract String getNodeDetailsLink(TreeNode node);
/** + * Deletes the given drift configuration. + * + * @param doomedDriftConfig the drift config to remove + */ + protected abstract void deleteDriftConfiguration(DriftConfiguration 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); + + /** * 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 @@ -194,17 +208,28 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid // separator contextMenu.addItem(new MenuItemSeparator());
- // item that links to the history details + // item that deletes the config MenuItem deleteItem = new MenuItem(MSG.common_button_delete()); deleteItem.setIcon(Window.getImgURL(ImageManager.getRemoveIcon())); deleteItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { - // TODO: delete the change set + DriftConfiguration driftConfig = node.getDriftConfiguration(); + deleteDriftConfiguration(driftConfig); } }); contextMenu.addItem(deleteItem);
- // item that links to the history details + // item that initiates a drift detection scan + MenuItem detectNowItem = new MenuItem(MSG.view_drift_button_detectNow()); + detectNowItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + DriftConfiguration driftConfig = node.getDriftConfiguration(); + detectDrift(driftConfig); + } + }); + contextMenu.addItem(detectNowItem); + + // item that links to the config details MenuItem detailsItem = new MenuItem(MSG.common_title_details()); detailsItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { @@ -294,6 +319,8 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid }
static class DriftConfigurationTreeNode extends TreeNode { + public static final String ATTR_DRIFT_CONFIG_OBJECT = "object"; + public DriftConfigurationTreeNode(DriftConfiguration driftConfig) { setIsFolder(true); if (driftConfig.isEnabled()) { @@ -304,6 +331,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid setShowOpenIcon(true); setID(String.valueOf(driftConfig.getId())); setName(buildNodeName(driftConfig)); // we sort on this column + setAttribute(ATTR_DRIFT_CONFIG_OBJECT, driftConfig); }
public int getDriftConfigurationId() { @@ -311,6 +339,10 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid return Integer.parseInt(idAttrib); }
+ public DriftConfiguration getDriftConfiguration() { + return (DriftConfiguration) getAttributeAsObject(ATTR_DRIFT_CONFIG_OBJECT); + } + @Override public String getTitle() { return super.getName(); 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 ec0bca7..0df6df4 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 @@ -19,10 +19,15 @@
package org.rhq.enterprise.gui.coregui.client.drift;
+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.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.LinkManager; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * @author John Mazzitelli @@ -58,4 +63,37 @@ public class ResourceDriftChangeSetsTreeView extends AbstractDriftChangeSetsTree return null; }
+ @Override + protected void deleteDriftConfiguration(DriftConfiguration doomedDriftConfig) { + GWTServiceLookup.getDriftService().deleteDriftConfigurationsByContext(context, + new String[] { doomedDriftConfig.getName() }, 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(); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteConfigs(), caught); + } + }); + } + + @Override + protected void detectDrift(DriftConfiguration driftConfig) { + 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); + } + }); + } + }
commit b7b3ab933d1a53ee3691f5d7794575319d132764 Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 15 14:27:17 2011 -0400
fix the drift config edit view so it is read-only for name/basedir/includes/excludes. change change set tree context menus
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 a409e1f..dfdc54a 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 @@ -80,24 +80,59 @@ public class DriftConfigurationDefinition implements Serializable { private static final ConfigurationDefinition INSTANCE = new ConfigurationDefinition("GLOBAL_DRIFT_CONFIG_DEF", "The drift configuration definition");
+ /** + * For drift configurations that have already been created, this definition can be used for editing those existing configuration. + * Existing drift configurations cannot have their name changed nor can their base directory or includes/excludes be altered. + */ + private static final ConfigurationDefinition INSTANCE_FOR_EXISTING_CONFIGS = new ConfigurationDefinition( + "GLOBAL_DRIFT_CONFIG_DEF", "The drift configuration definition"); + + /** + * Returns a configuration definition suitable for showing a new configuration form - that is, + * a configuration that has not yet been created. + * This will allow all fields to be editable. + * If you need a configuration definition to show an existing configuration, use the definition + * returned by {@link #getInstanceForExistingConfiguration()}. + * + * @return configuration definition + */ public static ConfigurationDefinition getInstance() { return INSTANCE; }
+ /** + * Returns a configuration definition suitable for showing an existing drift configuration. + * This will set certain fields as read-only - those fields which the user is not allowed to + * edit on exiting drift configurations (which includes name, basedir and includes/excludes filters). + * + * @return configuration definition + */ + public static ConfigurationDefinition getInstanceForExistingConfiguration() { + return INSTANCE_FOR_EXISTING_CONFIGS; + } + static { //INSTANCE.setId(1); INSTANCE.setConfigurationFormat(ConfigurationFormat.STRUCTURED); - - INSTANCE.put(createName()); - INSTANCE.put(createEnabled()); - INSTANCE.put(createBasedir()); - INSTANCE.put(createInterval()); - INSTANCE.put(createIncludes()); - INSTANCE.put(createExcludes()); + INSTANCE.put(createName(INSTANCE, false)); + INSTANCE.put(createEnabled(INSTANCE)); + INSTANCE.put(createBasedir(INSTANCE, false)); + INSTANCE.put(createInterval(INSTANCE)); + INSTANCE.put(createIncludes(INSTANCE, false)); + INSTANCE.put(createExcludes(INSTANCE, false)); + + //INSTANCE_FOR_EXISTING_CONFIGS.setId(1); + INSTANCE_FOR_EXISTING_CONFIGS.setConfigurationFormat(ConfigurationFormat.STRUCTURED); + INSTANCE_FOR_EXISTING_CONFIGS.put(createName(INSTANCE_FOR_EXISTING_CONFIGS, true)); + INSTANCE_FOR_EXISTING_CONFIGS.put(createEnabled(INSTANCE_FOR_EXISTING_CONFIGS)); + INSTANCE_FOR_EXISTING_CONFIGS.put(createBasedir(INSTANCE_FOR_EXISTING_CONFIGS, true)); + INSTANCE_FOR_EXISTING_CONFIGS.put(createInterval(INSTANCE_FOR_EXISTING_CONFIGS)); + INSTANCE_FOR_EXISTING_CONFIGS.put(createIncludes(INSTANCE_FOR_EXISTING_CONFIGS, true)); + INSTANCE_FOR_EXISTING_CONFIGS.put(createExcludes(INSTANCE_FOR_EXISTING_CONFIGS, true));
}
- private static PropertyDefinitionSimple createName() { + private static PropertyDefinitionSimple createName(ConfigurationDefinition configDef, boolean readOnly) { String name = PROP_NAME; String description = "The drift configuration name"; boolean required = true; @@ -106,11 +141,11 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(1); pd.setDisplayName("Drift Configuration Name"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0); pd.setAllowCustomEnumeratedValue(false); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef);
RegexConstraint constrait = new RegexConstraint(); constrait.setDetails(PROP_NAME_REGEX_PATTERN); @@ -119,7 +154,7 @@ public class DriftConfigurationDefinition implements Serializable { return pd; }
- private static PropertyDefinitionSimple createEnabled() { + private static PropertyDefinitionSimple createEnabled(ConfigurationDefinition configDef) { String name = PROP_ENABLED; String description = "Enables or disables the drift configuration"; boolean required = true; @@ -132,31 +167,31 @@ public class DriftConfigurationDefinition implements Serializable { pd.setSummary(true); pd.setOrder(1); pd.setAllowCustomEnumeratedValue(false); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef); pd.setDefaultValue(String.valueOf(DEFAULT_ENABLED)); return pd; }
- private static PropertyDefinitionMap createBasedir() { + private static PropertyDefinitionMap createBasedir(ConfigurationDefinition configDef, boolean readOnly) { String name = PROP_BASEDIR; String description = "The root directory from which snapshots will be generated during drift monitoring."; boolean required = true;
- PropertyDefinitionSimple valueContext = createBasedirValueContext(); - PropertyDefinitionSimple valueName = createBasedirValueName(); + PropertyDefinitionSimple valueContext = createBasedirValueContext(readOnly); + PropertyDefinitionSimple valueName = createBasedirValueName(readOnly);
PropertyDefinitionMap pd = new PropertyDefinitionMap(name, description, required, valueContext, valueName); //pd.setId(3); pd.setDisplayName("Base Directory"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(2); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef);
return pd; }
- private static PropertyDefinitionSimple createBasedirValueContext() { + private static PropertyDefinitionSimple createBasedirValueContext(boolean readOnly) { String name = PROP_BASEDIR_VALUECONTEXT; String description = "Identifies where the named value can be found."; boolean required = true; @@ -165,7 +200,7 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(4); pd.setDisplayName("Value Context"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0);
@@ -199,7 +234,7 @@ public class DriftConfigurationDefinition implements Serializable { return pd; }
- private static PropertyDefinitionSimple createBasedirValueName() { + private static PropertyDefinitionSimple createBasedirValueName(boolean readOnly) { String name = PROP_BASEDIR_VALUENAME; String description = "The name of the value as found in the context"; boolean required = true; @@ -208,14 +243,14 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(5); pd.setDisplayName("Value Name"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(1); pd.setAllowCustomEnumeratedValue(false); return pd; }
- private static PropertyDefinitionSimple createInterval() { + private static PropertyDefinitionSimple createInterval(ConfigurationDefinition configDef) { String name = PROP_INTERVAL; String description = "The frequency in seconds in which drift monitoring should run. Defaults to 1800 seconds (i.e. 30 minutes)"; boolean required = false; @@ -228,46 +263,46 @@ public class DriftConfigurationDefinition implements Serializable { pd.setSummary(true); pd.setOrder(3); pd.setAllowCustomEnumeratedValue(false); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef); pd.setDefaultValue(String.valueOf(DEFAULT_INTERVAL)); return pd; }
- private static PropertyDefinitionList createIncludes() { + private static PropertyDefinitionList createIncludes(ConfigurationDefinition configDef, boolean readOnly) { String name = PROP_INCLUDES; String description = "A set of patterns that specify files and/or directories to include."; boolean required = false;
- PropertyDefinitionMap map = createInclude(); + PropertyDefinitionMap map = createInclude(readOnly);
PropertyDefinitionList pd = new PropertyDefinitionList(name, description, required, map); //pd.setId(7); pd.setDisplayName("Includes"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(4); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef); return pd; }
- private static PropertyDefinitionMap createInclude() { + private static PropertyDefinitionMap createInclude(boolean readOnly) { String name = PROP_INCLUDES_INCLUDE; String description = "A pattern that specifies a file or directory to include."; boolean required = true;
- PropertyDefinitionSimple path = createIncludePath(); - PropertyDefinitionSimple pattern = createIncludePattern(); + PropertyDefinitionSimple path = createIncludePath(readOnly); + PropertyDefinitionSimple pattern = createIncludePattern(readOnly);
PropertyDefinitionMap pd = new PropertyDefinitionMap(name, description, required, path, pattern); //pd.setId(8); pd.setDisplayName("Include"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0); return pd; }
- private static PropertyDefinitionSimple createIncludePath() { + private static PropertyDefinitionSimple createIncludePath(boolean readOnly) { String name = PROP_PATH; String description = "A file system path that can be a directory or a file. The path is assumed to be relative to the base directory of the drift configuration."; boolean required = true; @@ -276,14 +311,14 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(9); pd.setDisplayName("Path"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0); pd.setAllowCustomEnumeratedValue(false); return pd; }
- private static PropertyDefinitionSimple createIncludePattern() { + private static PropertyDefinitionSimple createIncludePattern(boolean readOnly) { String name = PROP_PATTERN; String description = "Pathname pattern that must match for the items in the directory path to be included."; boolean required = false; @@ -292,48 +327,48 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(10); pd.setDisplayName("Pattern"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(1); pd.setAllowCustomEnumeratedValue(false); return pd; }
- private static PropertyDefinitionList createExcludes() { + private static PropertyDefinitionList createExcludes(ConfigurationDefinition configDef, boolean readOnly) { String name = PROP_EXCLUDES; String description = "A set of patterns that specify files and/or directories to exclude."; boolean required = false;
- PropertyDefinitionMap map = createExclude(); + PropertyDefinitionMap map = createExclude(readOnly);
PropertyDefinitionList pd = new PropertyDefinitionList(name, description, required, map); //pd.setId(11); pd.setDisplayName("Excludes"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(5); - pd.setConfigurationDefinition(INSTANCE); + pd.setConfigurationDefinition(configDef); return pd; }
- private static PropertyDefinitionMap createExclude() { + private static PropertyDefinitionMap createExclude(boolean readOnly) { String name = PROP_EXCLUDES_EXCLUDE; String description = "A pattern that specifies a file or directory to exclude."; boolean required = true;
- PropertyDefinitionSimple path = createExcludePath(); - PropertyDefinitionSimple pattern = createExcludePattern(); + PropertyDefinitionSimple path = createExcludePath(readOnly); + PropertyDefinitionSimple pattern = createExcludePattern(readOnly);
PropertyDefinitionMap pd = new PropertyDefinitionMap(name, description, required, path, pattern); //pd.setId(12); pd.setDisplayName("Exclude"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0); return pd; }
- private static PropertyDefinitionSimple createExcludePath() { + private static PropertyDefinitionSimple createExcludePath(boolean readOnly) { String name = PROP_PATH; String description = "A file system path that can be a directory or a file. The path is assumed to be relative to the base directory of the drift configuration."; boolean required = true; @@ -342,14 +377,14 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(13); pd.setDisplayName("Path"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(0); pd.setAllowCustomEnumeratedValue(false); return pd; }
- private static PropertyDefinitionSimple createExcludePattern() { + private static PropertyDefinitionSimple createExcludePattern(boolean readOnly) { String name = PROP_PATTERN; String description = "Pathname pattern that must match for the items in the directory path to be excluded."; boolean required = false; @@ -358,7 +393,7 @@ public class DriftConfigurationDefinition implements Serializable { PropertyDefinitionSimple pd = new PropertyDefinitionSimple(name, description, required, type); //pd.setId(14); pd.setDisplayName("Pattern"); - pd.setReadOnly(false); + pd.setReadOnly(readOnly); pd.setSummary(true); pd.setOrder(1); pd.setAllowCustomEnumeratedValue(false); 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 646c32f..9dbdcfe 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 @@ -459,7 +459,7 @@ public class LinkManager { return "#Resource/" + resourceId + "/Drift/History/" + driftId; }
- public static String getDriftConfigLink(int resourceId, int driftConfigId) { - return "#Resource/" + resourceId + "/Drift/Config/" + driftConfigId; + 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/drift/AbstractDriftChangeSetsTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/AbstractDriftChangeSetsTreeView.java index 2cccb4b..212e183 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 @@ -27,6 +27,7 @@ import com.google.gwt.core.client.RunAsyncCallback; import com.smartgwt.client.data.Record; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.types.SortDirection; +import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.events.DataArrivedEvent; import com.smartgwt.client.widgets.grid.events.DataArrivedHandler; @@ -40,18 +41,13 @@ import com.smartgwt.client.widgets.tree.TreeNode; import com.smartgwt.client.widgets.tree.events.NodeContextClickEvent; import com.smartgwt.client.widgets.tree.events.NodeContextClickHandler;
-import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; 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.DriftConfigurationDefinition; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; -import org.rhq.enterprise.gui.coregui.client.PopupWindow; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; -import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid;
@@ -100,11 +96,15 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid
TreeNode eventNode = event.getNode();
- if (eventNode instanceof ChangeSetTreeNode) { - Menu menu = buildChangeSetTreeNodeContextMenu((ChangeSetTreeNode) eventNode); - menu.showContextMenu(); + Menu menu = null; + if (eventNode instanceof DriftConfigurationTreeNode) { + menu = buildDriftConfigurationTreeNodeContextMenu((DriftConfigurationTreeNode) eventNode); + } else if (eventNode instanceof ChangeSetTreeNode) { + menu = buildChangeSetTreeNodeContextMenu((ChangeSetTreeNode) eventNode); } else if (eventNode instanceof DriftTreeNode) { - Menu menu = buildDriftTreeNodeContextMenu((DriftTreeNode) eventNode); + menu = buildDriftTreeNodeContextMenu((DriftTreeNode) eventNode); + } + if (menu != null) { menu.showContextMenu(); } } @@ -173,6 +173,53 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid protected abstract String getNodeDetailsLink(TreeNode node);
/** + * 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) { + + Menu contextMenu = new Menu(); + + // title + String titleName = node.getTitle(); + if (titleName.length() > 50) { + // make sure the title isn't really long so the menu is not abnormally wide + titleName = "..." + titleName.substring(titleName.length() - 50); + } + MenuItem titleItem = new MenuItem(titleName); + titleItem.setEnabled(false); + contextMenu.setItems(titleItem); + + // separator + contextMenu.addItem(new MenuItemSeparator()); + + // item that links to the history details + MenuItem deleteItem = new MenuItem(MSG.common_button_delete()); + deleteItem.setIcon(Window.getImgURL(ImageManager.getRemoveIcon())); + deleteItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + // TODO: delete the change set + } + }); + contextMenu.addItem(deleteItem); + + // item that links to the history details + MenuItem detailsItem = new MenuItem(MSG.common_title_details()); + detailsItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + String link = getNodeDetailsLink(node); + if (link != null) { + CoreGUI.goToView(link); + } + } + }); + contextMenu.addItem(detailsItem); + + return contextMenu; + } + + /** * Builds the right-mouse-click context menu for the given drift node * @param node the drift node whose menu is to be displayed * @return the context menu to display @@ -227,51 +274,14 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid // separator contextMenu.addItem(new MenuItemSeparator());
- // item that links to the history details - MenuItem deleteItem = new MenuItem(MSG.common_button_delete()); - deleteItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - // TODO: delete the change set - } - }); - contextMenu.addItem(deleteItem); - // item that shows the drift configuration - MenuItem configItem = new MenuItem(MSG.view_drift_changeset_tree_showConfiguration()); - configItem.addClickHandler(new ClickHandler() { - public void onClick(MenuItemClickEvent event) { - showDriftConfiguration(node.getChangeSetId()); - } - }); - contextMenu.addItem(configItem); + MenuItem idItem = new MenuItem(MSG.common_title_id() + "=" + node.getChangeSetId()); + idItem.setEnabled(false); + contextMenu.addItem(idItem);
return contextMenu; }
- protected void showDriftConfiguration(final String changeSetId) { - ConfigurationDefinition def = DriftConfigurationDefinition.getInstance(); - Configuration config = new Configuration(); - ConfigurationEditor editor = new ConfigurationEditor(extendLocatorId("driftConfigEditor"), def, config); - editor.setReadOnly(true); - PopupWindow window = new PopupWindow("details", editor); - window.show(); - - // DriftChangeSetCriteria criteria = new BasicDriftChangeSetCriteria(); - // criteria.addFilterId(changeSetId); - // criteria.fetchDriftConfiguration(true); - // GWTServiceLookup.getDriftService().findDriftChangeSetCompositesByCriteria(criteria, - // new AsyncCallback<PageList<DriftChangeSet>>() { - // public void onSuccess(PageList<DriftChangeSet> result) { - // // TODO - // } - // - // public void onFailure(Throwable t) { - // CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadConfigFailure(changeSetId), - // t); - // } - // }); - } - /** * We override this because we know all of our nodes will have titles. Without this, * I could not get the title of change set nodes to show - it always fell back to using @@ -296,6 +306,11 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid setName(buildNodeName(driftConfig)); // we sort on this column }
+ public int getDriftConfigurationId() { + String idAttrib = getAttribute("id"); + return Integer.parseInt(idAttrib); + } + @Override public String getTitle() { return super.getName(); 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 index 53a68fd..375f2af 100644 --- 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 @@ -120,7 +120,7 @@ public class DriftConfigurationEditView extends LocatableVLayout implements Prop public void onSuccess(final DriftConfiguration result) {
editor = new ConfigurationEditor(extendLocatorId("Editor"), DriftConfigurationDefinition - .getInstance(), result.getConfiguration()); + .getInstanceForExistingConfiguration(), result.getConfiguration()); editor.setOverflow(Overflow.AUTO); editor.addPropertyValueChangeListener(DriftConfigurationEditView.this); editor.setReadOnly(!hasWriteAccess); 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 fd61d35..ec0bca7 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 @@ -50,6 +50,10 @@ 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); + return path; } return null; } 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 fa309a2..3523d7b 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 @@ -1126,7 +1126,6 @@ view_drift_changeSets = Change Sets view_drift_changeSets_resourceViewTitle = Resource Drift Change Sets view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. -view_drift_changeset_tree_showConfiguration = Show Configuration view_drift_delete_configConfirm = Delete the selected drift configuration(s)? view_drift_delete_configConfirmAll = Delete all drift configurations? view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. 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 259e807..c1c3dee 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 @@ -944,7 +944,6 @@ view_dashboards_title = Dashboard ##view_drift_changeSets_resourceViewTitle = Resource Drift Change Sets ##view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] ##view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. -##view_drift_changeset_tree_showConfiguration = Show Configuration ##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? ##view_drift_delete_configConfirmAll = Delete all drift configurations? ##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. 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 44e5478..61d2676 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 @@ -1109,7 +1109,6 @@ view_dashboards_title = ããã·ã¥ããŒã ##view_drift_changeSets_resourceViewTitle = Resource Drift Change Sets ##view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] ##view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. -##view_drift_changeset_tree_showConfiguration = Show Configuration ##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? ##view_drift_delete_configConfirmAll = Delete all drift configurations? ##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations.
commit a2496100fccef1e064ea3ee45c89e339c2ce93a2 Author: John Sanda jsanda@redhat.com Date: Mon Aug 15 13:49:26 2011 -0400
Adding javadocs
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java index a8bc319..5e22f42 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -31,6 +31,38 @@ import org.rhq.core.util.file.PathFilter; import static org.apache.commons.io.FilenameUtils.normalize; import static org.rhq.core.util.file.FileUtil.generateRegex;
+/** + * A file visitor that peforms filtering using specified filters. When a file matches a + * filter this visitor delegates to another {@link FileVisitor} object. The filtering rules + * are as follows: + * <p/> + * <ul> + * <li>When no filters are specified, are files are considered matches.</li> + * <li> + * When one or more includes filters is specified and no excludes filters are + * specified, only files matching at least one of the includes filter(s) are + * considered matches. + * </li> + * <li> + * When one or more excludes filters is specified and no includes filters are + * specified, only files that do not match any of the excludes filters are + * considered matches. + * </li> + * <li> + * When both includes and excludes filters are specified, only files that match at + * at least one of the includes and do not match any of the excludes are considered + * matches. + * </li> + * </ul> + * <br/><br/> + * Note that the filtering is done on files and not on directories. This is a subtle yet + * important distinction. Suppose we have the following filter pattern, *.war, that we apply + * to the deploy directory of our JBoss application server. That filter will match things + * like foo.war, foo-123.war, or more precisely, any file that ends with .war. The pattern + * will not however match things like foo.war/ where foo.war is a directory (i.e., exploded + * webapp) since matching is not done on directories. To match the contents of foo.war/ + * you could use something like *.war/**. + */ public class FilterFileVisitor implements FileVisitor {
private List<PathFilter> includes; 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 761b941..204ba1c 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 @@ -347,6 +347,42 @@ public class FileUtil { } }
+ /** + * Takes a list of filters and compiles them into a regular expression that can be used + * for matching or filtering paths. The pattern syntax supports regular expressions as + * well as the syntax used in Ant's file/path selectors. Here are some example patterns + * that can be specified in a filter: + * <p/> + * <table border="1"> + * <tr> + * <td>Pattern</td> + * <td>Description</td> + * </tr> + * <tr> + * <td>/etc/yum.conf</td> + * <td>exact match of the path</td> + * </tr> + * <tr> + * <td>/etc/*.conf</td> + * <td>match any file /etc that has a .conf suffix</td> + * </tr> + * <tr> + * <td>deploy/myapp-?.war</td> + * <td>Match any file in the deploy directory that starts with myapp- followed any one character and + * ending with a suffix of .war</td> + * </tr> + * <tr> + * <td>jboss/server/**/*.war</td> + * <td>Matches all .war files under the server directory. Sub directories are included as well such + * that jboss/server/default/myapp.war jboss/server/production/myapp.war and + * jboss/server/default/myapp.ear/myapp.war all match</td> + * </tr> + * </table> + * + * @param filters Compiled into a regular expression + * @return A Pattern object that is a compilation of regular expressions built from + * the specified path filters + */ public static Pattern generateRegex(List<PathFilter> filters) { boolean first = true; StringBuilder regex = new StringBuilder(); diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java index 59265eb..31659bd 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java @@ -218,8 +218,6 @@ public class FileUtilTest { Pattern regex;
regex = assertPatternsRegex("(/basedir/(test1\.txt))", new PathFilter("/basedir", "test1.txt")); - //regex = Pattern.compile("/basedir/test1\.txt"); - //regex = Pattern.compile("(/basedir/(test1\.txt))");
assert regex.matcher("/basedir/test1.txt").matches(); assert !regex.matcher("/basedir/test2.txt").matches();
commit 1c241d9bac7b75b235862d07a80f5e068a3f6bd3 Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 15 12:40:27 2011 -0400
we store drift config templates now, we can do the TODO now
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java index 71f0f73..fde4efe 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java @@ -201,9 +201,8 @@ public class ResourceFacets implements Serializable { this.facets.add(ResourceTypeFacet.CALL_TIME); if (support) this.facets.add(ResourceTypeFacet.SUPPORT); - // TODO, add this back when we actually start storing drift config templates: - // if (drift) - this.facets.add(ResourceTypeFacet.DRIFT); + if (drift) + this.facets.add(ResourceTypeFacet.DRIFT);
} } \ No newline at end of file
commit 16a6fd8f9a4cbc8f4eadbb8a6480d59964e44dab Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 15 11:07:43 2011 -0400
change error message
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 c486401..be4d2f6 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 @@ -360,8 +360,8 @@ public class DriftManagerBean implements DriftManagerLocal { boolean isUpdated = false; for (DriftConfiguration dc : resource.getDriftConfigurations()) { if (dc.getName().equals(driftConfig.getName())) { - // compare the includes/excludes filters only - if they are different, abort. - // you cannot update drift config that changes includes/excludes from the original. + // 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()); @@ -369,7 +369,7 @@ public class DriftManagerBean implements DriftManagerLocal { break; } else { throw new IllegalArgumentException( - "You cannot change an existing drift configuration's includes/excludes filters."); + "You cannot change an existing drift configuration's base directory or includes/excludes filters."); } } }
commit fb77b1259520a6924f5f4dbe74b1acd532c1c8e7 Author: Heiko W. Rupp hwr@redhat.com Date: Mon Aug 15 16:51:34 2011 +0200
Add creating web connectors, fix the ssl connection part to not create errors, remove two unused classes.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java index 787db6b..cf5b100 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java @@ -153,7 +153,7 @@ public class ASConnection {
//the following code is in place to help keep-alive http connection re-use to occur. if (conn != null) {//on error conditions it's still necessary to read the response so JDK knows can reuse - //the http connections behind the scenes. + //the http connections behind the scenes. es = conn.getErrorStream(); if (es != null) { BufferedReader dr = new BufferedReader(new InputStreamReader(es)); @@ -232,6 +232,9 @@ public class ASConnection { public Result execute(Operation op, boolean isComplex) { JsonNode node = executeRaw(op);
+ if (node==null) { + log.warn("Operation [" + op + "] returned null"); + } try { Result res; if (isComplex) diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java index 131c1a0..e5e8a36 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java @@ -270,10 +270,43 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi @Override public CreateResourceReport createResource(CreateResourceReport report) {
+ if (context.getContentContext() != null) { // Content deployment + return deployContent(report); + } else { + report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION); + Address createAddress = new Address(address); + createAddress.add(report.getPluginConfiguration().getSimpleValue("path",""),report.getUserSpecifiedResourceName()); + Operation op = new Operation("add",createAddress); + for (Property prop : report.getResourceConfiguration().getProperties()) { + if (prop instanceof PropertySimple) { + PropertySimple ps = (PropertySimple) prop; + String value = ps.getStringValue(); + op.addAdditionalProperty(prop.getName(), value); + } + // TODO more types + } + Result result = getASConnection().execute(op); + if (result.isSuccess()) { + report.setStatus(CreateResourceStatus.SUCCESS); + report.setResourceKey(address.getPath()); + report.setResourceName(report.getUserSpecifiedResourceName()); + } else { + report.setStatus(CreateResourceStatus.FAILURE); + report.setErrorMessage(result.getFailureDescription()); + } + } + return report; + }
+ /** + * Deploy content to the remote server - this is one half of #createResource + * @param report Create resource report that tells us what to do + * @return report that tells us what has been done. + */ + private CreateResourceReport deployContent(CreateResourceReport report) { + ContentContext cctx = context.getContentContext(); ResourcePackageDetails details = report.getPackageDetails();
- ContentContext cctx = context.getContentContext(); ContentServices contentServices = cctx.getContentServices(); String resourceTypeName = report.getResourceType().getName();
@@ -298,14 +331,12 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi fileName=fileName.substring("C:\fakepath\".length()); }
- String tmpName = fileName; // TODO figure out the tmp-name biz with the AS guys
JsonNode resultNode = uploadResult.get("result"); String hash = resultNode.get("BYTES_VALUE").getTextValue();
return runDeploymentMagicOnServer(report, fileName, tmpName, hash); - }
/** diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarComponent.java deleted file mode 100644 index 7382a6d..0000000 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarComponent.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2010 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.modules.plugins.jbossas7; - -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.pluginapi.inventory.DeleteResourceFacet; -import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.inventory.ResourceContext; - -/** - * Monitoring of war files - * - * @author Heiko W. Rupp - */ -public class WarComponent implements ResourceComponent<BaseComponent>, DeleteResourceFacet { - - ResourceContext<BaseComponent> context; - - public void start(ResourceContext<BaseComponent> context) throws InvalidPluginConfigurationException, Exception { - this.context = context; - } - - public void stop() { - } - - public AvailabilityType getAvailability() { - return AvailabilityType.UP; - } - - public void deleteResource() throws Exception { -// -// DomainDeploymentManager deploymentManager = client.getDeploymentManager(); -// DeploymentPlanBuilder builder = deploymentManager.newDeploymentPlan(); -// -// String name = context.getResourceKey(); // key and name are the same at the moment -// -// UndeployDeploymentPlanBuilder udpb = builder.undeploy(name); -// RemoveDeploymentPlanBuilder rdpb = udpb.andRemoveUndeployed(); -// rdpb.build(); - } -} diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarDiscovery.java deleted file mode 100644 index adadcba..0000000 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/WarDiscovery.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2010 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.modules.plugins.jbossas7; - -import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; -import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; - -import java.util.HashSet; -import java.util.Set; - -/** - * Discover war files - * - * @author Heiko W. Rupp - */ -public class WarDiscovery implements ResourceDiscoveryComponent<BaseComponent> { - - public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<BaseComponent> context) - throws InvalidPluginConfigurationException, Exception { - - Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(); - - BaseComponent baseComponent = context.getParentResourceComponent(); - - return details; - } -} diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml index ecf541d..67edbff 100644 --- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml @@ -195,6 +195,7 @@ <event name="logEntry" description="an entry in a log file"/>
<resource-configuration> +<!-- <c:group name="attribute:schema-locations" displayName="Schema locations">
<c:list-property name="schema-locations" displayName="Schema locations" readOnly="true" required="false"> @@ -203,11 +204,12 @@ </c:map-property> </c:list-property> </c:group> +-->
<c:group name="children:extension" displayName="Installed extensions">
<c:list-property name="*" displayName="Installed extensions" readOnly="true" required="false"> - <c:map-property name="*" displayName="Name"> + <c:map-property name="*" displayName="Name" readOnly="true"> <c:simple-property name="module" displayName="Module name"/> </c:map-property> </c:list-property> @@ -418,6 +420,7 @@
<resource-configuration>
+<!-- <c:group name="attribute:schema-locations" displayName="Schema locations">
<c:list-property name="schema-locations" displayName="Schema locations" readOnly="true" required="false"> @@ -426,11 +429,12 @@ </c:map-property> </c:list-property> </c:group> +-->
<c:group name="children:extension" displayName="Installed extensions">
<c:list-property name="*" displayName="Installed extensions" readOnly="true" required="false"> - <c:map-property name="*" displayName="Name"> + <c:map-property name="*" displayName="Name" readOnly="true"> <c:simple-property name="module" displayName="Module name"/> </c:map-property> </c:list-property> @@ -733,9 +737,9 @@ <c:simple-property name="protocol" required="true" type="string" readOnly="true" description="The web connector protocol."/> <c:simple-property name="socket-binding" required="true" type="string" readOnly="true" description="The web connector socket-binding reference, this connector should be bound to."> - <c:option-source target="configuration" expression="socket-binding=name:type=SocketBindingGroup"/> + <c:option-source target="configuration" expression="socket-binding=name:type=SocketBindingGroup"/> <!-- TODO different for Domain vs standalone --> </c:simple-property> - <c:simple-property name="scheme" type="string" readOnly="true" default="http" description="The web connector scheme."/> + <c:simple-property name="scheme" type="string" readOnly="true" default="http" description="The web connector scheme." required="true"/> <c:simple-property name="executor" type="string" readOnly="true" required="false" description="The name of the executor that should be used for the processing threads of this connector. Defaults to using an internal pool."/> <c:simple-property name="enabled" type="boolean" readOnly="true" defaultValue="true" @@ -760,19 +764,24 @@ <c:simple-property name="virtual-server" /> </c:list-property> <c:map-property name="ssl" description="The SSL configuration of the connector." readOnly="true" required="false"> - <c:simple-property name="name" type="string" readOnly="true" description="The configuration name."/> - <c:simple-property name="key-alias" type="string" readOnly="true" description="The key alias."/> - <c:simple-property name="password" type="string" readOnly="true" description="Password."/> - <c:simple-property name="certificate-key-file" type="string" readOnly="true" description="Key file for the certificate."/> - <c:simple-property name="cipher-suite" type="string" readOnly="true" description="The allowed cipher suite."/> - <c:simple-property name="protocol" type="string" readOnly="true" description="The SSL protocols that are enabled."/> - <c:simple-property name="verify-client" type="string" readOnly="true" description="Enable client certificate verification."/> - <c:simple-property name="verify-depth" type="integer" readOnly="true" description="Limit certificate nesting."/> - <c:simple-property name="certificate-file" type="string" readOnly="true" description="Server certificate file."/> - <c:simple-property name="ca-certificate-file" type="string" readOnly="true" description="Certificate authority."/> - <c:simple-property name="ca-revocation-url" type="string" readOnly="true" description="Certificate authority revocation list."/> - <c:simple-property name="session-cache-size" type="string" readOnly="true" description="SSL session cache."/> - <c:simple-property name="session-timeout" type="string" readOnly="true" description="SSL session cache timeout."/> + <c:simple-property name="name" type="string" readOnly="true" description="The configuration name." required="false"/> + <c:simple-property name="key-alias" type="string" readOnly="true" description="The key alias." required="false"/> + <c:simple-property name="password" type="password" readOnly="true" description="Password." required="false"/> + <c:simple-property name="certificate-key-file" type="string" readOnly="true" description="Key file for the certificate." required="false"/> + <c:simple-property name="cipher-suite" type="string" readOnly="true" description="The allowed cipher suite." required="false"/> + <c:simple-property name="protocol" type="string" readOnly="true" description="The SSL protocols that are enabled." required="false"/> + <c:simple-property name="verify-client" type="string" readOnly="true" required="false" + description="Enable client certificate verification."/> + <c:simple-property name="verify-depth" type="integer" readOnly="true" required="false" + description="Limit certificate nesting."/> + <c:simple-property name="certificate-file" type="string" readOnly="true" required="false" + description="Server certificate file."/> + <c:simple-property name="ca-certificate-file" type="string" readOnly="true" + required="false" description="Certificate authority."/> + <c:simple-property name="ca-revocation-url" type="string" readOnly="true" + required="false" description="Certificate authority revocation list."/> + <c:simple-property name="session-cache-size" type="string" readOnly="true" description="SSL session cache." required="false"/> + <c:simple-property name="session-timeout" type="string" readOnly="true" description="SSL session cache timeout." required="false"/> </c:map-property> </resource-configuration>
commit 323ee4f464d746768c13320325ec103087f08cc1 Author: John Sanda jsanda@redhat.com Date: Mon Aug 15 10:38:37 2011 -0400
Handle relative paths in filters
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 c8e5061..5ae6447 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 @@ -145,7 +145,7 @@ public class DriftDetector implements Runnable { }
// Now we need to do a directory tree scan to look for newly added files - forEachFile(basedir, new FilterFileVisitor(schedule.getDriftConfiguration().getIncludes(), + forEachFile(basedir, new FilterFileVisitor(basedir, schedule.getDriftConfiguration().getIncludes(), schedule.getDriftConfiguration().getExcludes(), new FileVisitor() { @Override public void visit(File file) { @@ -178,7 +178,8 @@ public class DriftDetector implements Runnable { final DriftConfiguration config = schedule.getDriftConfiguration(); final File basedir = new File(basedir(schedule.getResourceId(), config));
- forEachFile(basedir, new FilterFileVisitor(config.getIncludes(), config.getExcludes(), new FileVisitor() { + forEachFile(basedir, new FilterFileVisitor(basedir, config.getIncludes(), config.getExcludes(), + new FileVisitor() { @Override public void visit(File file) { try { diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java index 0c3b500..a8bc319 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -28,6 +28,7 @@ import org.rhq.core.domain.drift.Filter; import org.rhq.core.util.file.FileVisitor; import org.rhq.core.util.file.PathFilter;
+import static org.apache.commons.io.FilenameUtils.normalize; import static org.rhq.core.util.file.FileUtil.generateRegex;
public class FilterFileVisitor implements FileVisitor { @@ -42,18 +43,24 @@ public class FilterFileVisitor implements FileVisitor {
private Pattern excludesPattern;
- public FilterFileVisitor(List<Filter> includes, List<Filter> excludes, FileVisitor visitor) { - this.includes = convert(includes); - this.excludes = convert(excludes); + public FilterFileVisitor(File basedir, List<Filter> includes, List<Filter> excludes, FileVisitor visitor) { + this.includes = convert(basedir, includes); + this.excludes = convert(basedir, excludes); this.visitor = visitor; includesPattern = generateRegex(this.includes); excludesPattern = generateRegex(this.excludes); }
- private List<PathFilter> convert(List<Filter> filters) { + private List<PathFilter> convert(File basedir, List<Filter> filters) { List<PathFilter> pathFilters = new ArrayList<PathFilter>(filters.size()); for (Filter filter : filters) { - pathFilters.add(new PathFilter(filter.getPath(), filter.getPattern())); + File path = new File(filter.getPath()); + if (path.isAbsolute()) { + pathFilters.add(new PathFilter(normalize(path.getAbsolutePath()), filter.getPattern())); + } else { + pathFilters.add(new PathFilter(normalize(new File(basedir, filter.getPath()).getAbsolutePath()), + filter.getPattern())); + } } return pathFilters; } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java index 2636583..bb8f4dc 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java @@ -65,7 +65,7 @@ public class FilterFileVisitorTest { List<Filter> excludes = emptyList(); TestVisitor visitor = new TestVisitor();
- forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertCollectionEqualsNoOrder(asList(server1Jar, server2Jar, nativeServer1Lib, nativeServer2Lib), visitor.visitedFiles, "Visitor should be called for every file when no filters specified"); @@ -84,7 +84,7 @@ public class FilterFileVisitorTest { List<Filter> excludes = emptyList(); TestVisitor visitor = new TestVisitor();
- forEachFile(libDir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertCollectionEqualsNoOrder(asList(fooJar, fooWar, myapp), visitor.visitedFiles, "Filtering failed with mulitple includes and no excludes"); @@ -98,7 +98,7 @@ public class FilterFileVisitorTest { List<Filter> excludes = emptyList(); TestVisitor visitor = new TestVisitor();
- forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertTrue(visitor.visitedFiles.isEmpty(), "Do not visit files that do not match an includes filter"); } @@ -112,7 +112,7 @@ public class FilterFileVisitorTest { List<Filter> excludes = asList(new Filter(basedir.getAbsolutePath(), "*.txt")); TestVisitor visitor = new TestVisitor();
- forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertCollectionEqualsNoOrder(asList(server1Html), visitor.visitedFiles, "Visit files that do not match " + "excludes filter and no includes are specified"); @@ -128,10 +128,10 @@ public class FilterFileVisitorTest { List<Filter> excludes = asList(new Filter(libDir.getAbsolutePath(), "server-1.jar")); TestVisitor visitor = new TestVisitor();
- forEachFile(libDir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertCollectionEqualsNoOrder(asList(server2Jar), visitor.visitedFiles, - "Filtering failed when no includes an exclude were specified."); + "Filtering failed when no includes and an exclude were specified."); }
@Test @@ -151,12 +151,33 @@ public class FilterFileVisitorTest { List<Filter> excludes = asList(new Filter(confDir.getAbsolutePath(), "server-2.conf")); TestVisitor visitor = new TestVisitor();
- forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor));
assertCollectionEqualsNoOrder(asList(server1Jar, server2Jar, server1Conf), visitor.visitedFiles, "Do not visit files that match an excludes even when the file matches an include"); }
+ @Test + public void expandRelativePaths() throws Exception { + File server1Html = touch(basedir, "server-1.html"); + File server2Html = touch(basedir, "server-2.html"); + File server1Txt = touch(basedir, "server-1.txt"); + File server2Txt = touch(basedir, "server-2.txt"); + + File libDir = mkdir(basedir, "lib"); + File server1Jar = touch(libDir, "server-1.jar"); + File server2Jar = touch(libDir, "server-2.jar"); + + List<Filter> includes = asList(new Filter(".", "server-1.*"), new Filter("./lib", "server-1.*")); + List<Filter> excludes = emptyList(); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(basedir, includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(server1Html, server1Txt, server1Jar), visitor.visitedFiles, + "Relative paths should be expanded out to full paths"); + } + private File mkdir(File parent, String dirName) throws IOException { File dir = new File(parent, dirName); dir.mkdirs();
commit 2f858f7d708fbe710fe08ca578b348f53fc58f92 Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 15 10:36:01 2011 -0400
add better error handling when an exception occurs in updateTabContent() for a resource or group detail view
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 88d754b..8d5d477 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 @@ -226,27 +226,31 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }
protected void updateTabContent(ResourceGroupComposite groupComposite) { - this.groupComposite = groupComposite; - ResourceGroup group = groupComposite.getResourceGroup(); - int groupId = group.getId(); - getTitleBar().setGroup(groupComposite); - - // wipe the canvas views for the current set of subtabs. - this.getTabSet().destroyViews(); - - GroupCategory groupCategory = groupComposite.getResourceGroup().getGroupCategory(); - Set<ResourceTypeFacet> facets = groupComposite.getResourceFacets().getFacets(); - - updateSummaryTab(); - updateMonitoringTab(groupId, groupCategory, facets); - updateInventoryTab(groupId, facets); - updateOperationsTab(groupCategory, facets); - updateAlertsTab(groupComposite, groupCategory); - updateConfigurationTab(groupId, groupCategory, facets); - updateEventsTab(groupComposite, groupCategory, facets); - - this.show(); - markForRedraw(); + try { + this.groupComposite = groupComposite; + ResourceGroup group = groupComposite.getResourceGroup(); + int groupId = group.getId(); + getTitleBar().setGroup(groupComposite); + + // wipe the canvas views for the current set of subtabs. + this.getTabSet().destroyViews(); + + GroupCategory groupCategory = groupComposite.getResourceGroup().getGroupCategory(); + Set<ResourceTypeFacet> facets = groupComposite.getResourceFacets().getFacets(); + + updateSummaryTab(); + updateMonitoringTab(groupId, groupCategory, facets); + updateInventoryTab(groupId, facets); + updateOperationsTab(groupCategory, facets); + updateAlertsTab(groupComposite, groupCategory); + updateConfigurationTab(groupId, groupCategory, facets); + updateEventsTab(groupComposite, groupCategory, facets); + + this.show(); + markForRedraw(); + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Failed to update tab content.", e); + } }
private void updateSummaryTab() { 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 0e63d8e..705ce9b 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 @@ -273,31 +273,35 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo }
protected void updateTabContent(ResourceComposite resourceComposite) { - this.resourceComposite = resourceComposite; - for (ResourceSelectListener selectListener : this.selectListeners) { - selectListener.onResourceSelected(this.resourceComposite); + try { + this.resourceComposite = resourceComposite; + for (ResourceSelectListener selectListener : this.selectListeners) { + selectListener.onResourceSelected(this.resourceComposite); + } + Resource resource = this.resourceComposite.getResource(); + getTitleBar().setResource(this.resourceComposite); + + // wipe the canvas views for the current set of subtabs. + this.getTabSet().destroyViews(); + + ResourcePermission resourcePermissions = this.resourceComposite.getResourcePermission(); + Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); + + updateSummaryTabContent(resource); + updateInventoryTabContent(resourceComposite, resource, facets); + updateAlertsTabContent(resourceComposite); + updateMonitoringTabContent(resource, facets); + updateEventsTabContent(resourceComposite, facets); + updateOperationsTabContent(facets); + updateConfigurationTabContent(resourceComposite, resource, resourcePermissions, facets); + updateDriftTabContent(resourceComposite, resource, resourcePermissions, facets); + updateContentTabContent(resource, facets); + + this.show(); + markForRedraw(); + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Failed to update tab content.", e); } - Resource resource = this.resourceComposite.getResource(); - getTitleBar().setResource(this.resourceComposite); - - // wipe the canvas views for the current set of subtabs. - this.getTabSet().destroyViews(); - - ResourcePermission resourcePermissions = this.resourceComposite.getResourcePermission(); - Set<ResourceTypeFacet> facets = this.resourceComposite.getResourceFacets().getFacets(); - - updateSummaryTabContent(resource); - updateInventoryTabContent(resourceComposite, resource, facets); - updateAlertsTabContent(resourceComposite); - updateMonitoringTabContent(resource, facets); - updateEventsTabContent(resourceComposite, facets); - updateOperationsTabContent(facets); - updateConfigurationTabContent(resourceComposite, resource, resourcePermissions, facets); - updateDriftTabContent(resourceComposite, resource, resourcePermissions, facets); - updateContentTabContent(resource, facets); - - this.show(); - markForRedraw(); }
private void updateSummaryTabContent(final Resource resource) {
commit 3281da4177c13321ed2fe9f7765619e9c596786f Author: Ian Springer ian.springer@redhat.com Date: Mon Aug 15 10:35:00 2011 -0400
[BZ 729337] init values on system details form using form.setValue(), rather than formItem.setValue(), to prevent "JavaScriptException:(TypeError): this.form is null" errors from occurring if formItem.setValue() is called before the form has been added to its parent Canvas (https://bugzilla.redhat.com/show_bug.cgi?id=729337)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java index d404581..5804f9d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/SystemSettingsView.java @@ -570,7 +570,7 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu }
private DynamicForm getServerDetails() { - DynamicForm form = new LocatableDynamicForm(extendLocatorId("serverDetails")); + final DynamicForm form = new LocatableDynamicForm(extendLocatorId("serverDetails")); form.setWidth100(); form.setExtraSpace(15); form.setIsGroup(true); @@ -624,21 +624,21 @@ public class SystemSettingsView extends LocatableVLayout implements PropertyValu @Override public void onSuccess(ServerDetails result) { ProductInfo productInfo = result.getProductInfo(); - productName.setValue(productInfo.getName()); - productVersion.setValue(productInfo.getVersion()); - productBuildNumber.setValue(productInfo.getBuildNumber()); - - HashMap<Detail, String> details = result.getDetails(); - serverTimezone.setValue(details.get(ServerDetails.Detail.SERVER_TIMEZONE)); - serverTime.setValue(details.get(ServerDetails.Detail.SERVER_LOCAL_TIME)); - serverInstallDir.setValue(details.get(ServerDetails.Detail.SERVER_INSTALL_DIR)); - dbUrl.setValue(details.get(ServerDetails.Detail.DATABASE_CONNECTION_URL)); - dbProductName.setValue(details.get(ServerDetails.Detail.DATABASE_PRODUCT_NAME)); - dbProductVersion.setValue(details.get(ServerDetails.Detail.DATABASE_PRODUCT_VERSION)); - dbDriverName.setValue(details.get(ServerDetails.Detail.DATABASE_DRIVER_NAME)); - dbDriverVersion.setValue(details.get(ServerDetails.Detail.DATABASE_DRIVER_VERSION)); - currentMeasRawTable.setValue(details.get(ServerDetails.Detail.CURRENT_MEASUREMENT_TABLE)); - nextMeasTableRotation.setValue(details.get(ServerDetails.Detail.NEXT_MEASUREMENT_TABLE_ROTATION)); + form.setValue(productName.getName(), productInfo.getName()); + form.setValue(productVersion.getName(), productInfo.getVersion()); + form.setValue(productBuildNumber.getName(), productInfo.getBuildNumber()); + + Map<Detail, String> details = result.getDetails(); + form.setValue(serverTimezone.getName(), details.get(ServerDetails.Detail.SERVER_TIMEZONE)); + form.setValue(serverTime.getName(), details.get(ServerDetails.Detail.SERVER_LOCAL_TIME)); + form.setValue(serverInstallDir.getName(), details.get(ServerDetails.Detail.SERVER_INSTALL_DIR)); + form.setValue(dbUrl.getName(), details.get(ServerDetails.Detail.DATABASE_CONNECTION_URL)); + form.setValue(dbProductName.getName(), details.get(ServerDetails.Detail.DATABASE_PRODUCT_NAME)); + form.setValue(dbProductVersion.getName(), details.get(ServerDetails.Detail.DATABASE_PRODUCT_VERSION)); + form.setValue(dbDriverName.getName(), details.get(ServerDetails.Detail.DATABASE_DRIVER_NAME)); + form.setValue(dbDriverVersion.getName(), details.get(ServerDetails.Detail.DATABASE_DRIVER_VERSION)); + form.setValue(currentMeasRawTable.getName(), details.get(ServerDetails.Detail.CURRENT_MEASUREMENT_TABLE)); + form.setValue(nextMeasTableRotation.getName(), details.get(ServerDetails.Detail.NEXT_MEASUREMENT_TABLE_ROTATION)); }
@Override
commit e4f0646981f5a769e4e7fcd514866f4f2a6d6056 Author: John Sanda jsanda@redhat.com Date: Mon Aug 15 08:45:47 2011 -0400
disabling mongodb tests for hudson
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 9f2ed2a..50b4572 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 @@ -52,7 +52,7 @@ public class ChangeSetDAOTest {
// Tests need to be disabled when committed/pushed to the remote repo until we get // mongodb installed on the hudson slave - static final boolean ENABLED = true; + static final boolean ENABLED = false;
Mongo connection;
commit a5778c167d3c23754dcf32771341baa7cd8a4414 Author: Heiko W. Rupp hwr@redhat.com Date: Mon Aug 15 14:07:48 2011 +0200
Add support for the deployment scanner and (a little bit) for Infinispan.
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml index 56f9de3..ecf541d 100644 --- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml @@ -894,7 +894,7 @@ <parameters> <c:simple-property name="name" required="true" description="Name of the datasource"/> <c:simple-property name="driver-name" required="true"> - <c:option-source target="resource" expression="type=^Deployment$"/> + <c:option-source target="resource" expression="type=^Deployment$" filter="sameHierarchy"/> </c:simple-property> <c:simple-property name="jndi-name" description="JNDI-Name of the Datasource" required="true"/> <c:simple-property name="connection-url" description="URL for the connection to the database" required="true"/> @@ -1674,6 +1674,53 @@ working area for individual server instances</li></ul>"/>
</server>
+ <server name="Infinispan" + discovery="SubsystemDiscovery" + class="BaseComponent" + singleton="true" + > + <runs-inside> + <parent-resource-type name="Profile" plugin="jboss-as-7"/> + <parent-resource-type name="JBossAS7-Standalone" plugin="jboss-as-7"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="path" readOnly="true" default="subsystem=infinispan"/> + </plugin-configuration> + + <resource-configuration> + <c:simple-property name="default-cache-container" readOnly="true"/> + </resource-configuration> + + <service name="Cache Container" + discovery="SubsystemDiscovery" + class="BaseComponent" + > + <plugin-configuration> + <c:simple-property name="path" readOnly="true" default="cache-container"/> + </plugin-configuration> + + <resource-configuration> + <c:simple-property name="default-cache" readOnly="true"/> + <c:list-property name="cache" readOnly="true"> + <c:map-property name="*"> + <c:simple-property name="name" /> + <c:simple-property name="mode" /> +<!-- + <c:map-property name="eviction"> + <c:simple-property name="strategy"/> + <c:simple-property name="max-entries" required="false"/> + </c:map-property> +--> + <c:simple-property name="eviction" required="false" readOnly="true"/> + <c:simple-property name="expiration" required="false" readOnly="true"/> + </c:map-property> + </c:list-property> + </resource-configuration> + </service> + + </server> + <server name="Threads" discovery="SubsystemDiscovery" class="BaseComponent" @@ -1967,4 +2014,45 @@ working area for individual server instances</li></ul>"/>
</service>
+ <service name="DeploymentScanner" + class="BaseComponent" + discovery="SubsystemDiscovery" + description="Management of the deployment scanner" + singleton="true" + > + <runs-inside> + <parent-resource-type name="JBossAS7-Standalone" plugin="jboss-as-7"/> + </runs-inside> + <plugin-configuration> + <c:simple-property name="path" default="subsystem=deployment-scanner" readOnly="true"/> + </plugin-configuration> + + <resource-configuration> + <!--<c:simple-property name="default" readOnly="false" required="true" description="Scanner policy to use"/>--> + <c:group name="children:scanner:name" displayName="Available scanners"> + <c:list-property name="*" description="List of scanners" > + <c:map-property name="scanner"> + <c:simple-property name="name" required="true" type="string" readOnly="true" description="The name of the scanner"/> + <c:simple-property name="path" required="true" type="string" readOnly="false" + description="The actual filesystem path to be scanned. Treated as an absolute path, unless the 'relative-to' attribute is specified, in which case the value is treated as relative to that path."/> + <c:simple-property name="relative-to" required="false" type="string" readOnly="false" + description="Reference to a filesystem path defined in the 'paths' section of the server configuration."/> + <c:simple-property name="scan-enabled" required="false" type="boolean" readOnly="false" + defaultValue="true" description="Flag indicating that all scanning (including initial scanning at startup) should be disabled."/> + <c:simple-property name="scan-interval" required="false" type="integer" readOnly="false" + defaultValue="5000" description="Periodic interval, in milliseconds, at which the repository should be scanned for changes. A value of less than 1 indicates the repository should only be scanned at initial startup."/> + <c:simple-property name="auto-deploy-zipped" required="false" type="boolean" readOnly="false" + defaultValue="true" description="Controls whether zipped deployment content should be automatically deployed by the scanner without requiring the user to add a .dodeploy marker file."/> + <c:simple-property name="auto-deploy-exploded" required="false" type="boolean" readOnly="false" + defaultValue="false" description="Controls whether zipped deployment content should be automatically deployed by the scanner without requiring the user to add a .dodeploy marker file. Setting this to 'true' is not recommended for anything but basic development scenarios, as there is no way to ensure that deployment will not occur in the middle of changes to the content."/> + <c:simple-property name="deployment-timeout" required="false" type="long" readOnly="false" + defaultValue="60" description="Timeout, in seconds, a deployment is allows to execute before being canceled. The default is 60 seconds."/> + </c:map-property> + </c:list-property> + </c:group> + + </resource-configuration> + + </service> + </plugin>
commit 4c03ae7c672801d9bf189c286c1b631c4d8ff284 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Aug 12 20:27:01 2011 +0200
BZ 719983 - provide a better version string
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..daa0447 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 @@ -44,6 +44,7 @@ public abstract class AbstractBaseDiscovery<T extends ResourceComponent> impleme static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file="; private static final String DJBOSS_SERVER_HOME_DIR = "-Djboss.home.dir"; static final int DEFAULT_MGMT_PORT = 9990; + private static final String JBOSS_AS_PREFIX = "jboss-as-"; protected Document hostXml; protected final Log log = LogFactory.getLog(this.getClass());
@@ -256,6 +257,17 @@ public abstract class AbstractBaseDiscovery<T extends ResourceComponent> impleme
}
+ protected String determineServerVersionFromHomeDir(String homeDir) { + String version; + String tmp = homeDir.substring(homeDir.lastIndexOf("/")+1); + if (tmp.startsWith("jboss-as-")) { + version = tmp.substring(JBOSS_AS_PREFIX.length()); + } else { + version = homeDir.substring(homeDir.lastIndexOf("-") + 1); + } + return version; + } + /** * Helper class that holds information about the host,port tuple */ 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 9d289f3..8e73205 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 @@ -52,11 +52,7 @@ import org.rhq.core.system.ProcessInfo; public class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent
{ - - static final String DJBOSS_HOME_DIR = "-Djboss.home.dir="; static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file="; - static final String DLOGGING_CONFIGURATION = "-Dlogging.configuration="; - static final String DASH_DASH_SERVER_CONFIG = "--server-config="; private final Log log = LogFactory.getLog(this.getClass());
/** @@ -77,6 +73,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou String serverName; String psName = psr.getProcessScan().getName(); String description = discoveryContext.getResourceType().getDescription(); + String homeDir = getHomeDirFromCommandLine(commandLine); String version = null;
//retrieve specific boot log file. Override for Standalone as server.log is more appropriate @@ -96,9 +93,8 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou serverName = "HostController"; // TODO make more unique serverNameFull = "HostController"; } - String homeDir = getHomeDirFromCommandLine(psr.getProcessInfo().getCommandLine()); + config.put(new PropertySimple("baseDir", homeDir)); - version = homeDir.substring(homeDir.lastIndexOf("-") + 1); config.put(new PropertySimple("startScript", AS7Mode.DOMAIN.getStartScript())); String host = findHost(psr.getProcessInfo(), true); config.put(new PropertySimple("domainHost", host)); @@ -112,9 +108,9 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou config.put(new PropertySimple("hostConfig",hostConfig));
} else { // Standalone server - serverNameFull = getHomeDirFromCommandLine(commandLine); + serverNameFull = homeDir; readStandaloneOrHostXml(psr.getProcessInfo(), false); - if (serverNameFull == null || serverNameFull.isEmpty()) { + if ( serverNameFull.isEmpty()) { // Try to obtain the server name // -Dorg.jboss.boot.log.file=domain/servers/server-one/log/boot.log // This is a hack until I know a better way to do so. @@ -134,7 +130,6 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou if (serverName.isEmpty()) serverName = serverNameFull;
- version = serverName.substring(serverName.lastIndexOf("-") + 1);
String serverConfig = getServerConfigFromCommandLine(commandLine, AS7Mode.STANDALONE); config.put(new PropertySimple("config",serverConfig)); diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java index 7764e63..5a105bd 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java @@ -104,7 +104,7 @@ public class ManagedASDiscovery extends AbstractBaseDiscovery String homeDir = getHomeDirFromCommandLine(processInfo.getCommandLine()); initLogFile(scans, serverInfo.name, config, homeDir);
- String version = homeDir.substring(homeDir.lastIndexOf("-") + 1); + String version = determineServerVersionFromHomeDir(homeDir);
DiscoveredResourceDetails detail = new DiscoveredResourceDetails(discoveryContext.getResourceType(), // ResourceType hostName + "/" + serverInfo.name, // key
commit 40aab040c3b53f616a0b226f9d77a8ed39fd5bde Author: Heiko W. Rupp hwr@redhat.com Date: Fri Aug 12 17:35:17 2011 +0200
BZ 729938 - If reload returns "connection refused", treat as success, as7 sometimes closes the connection before sending a result. Add a result of "Success" if it is a success.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java index 328ec3c..581c4e1 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java @@ -137,18 +137,23 @@ public class BaseServerComponent extends BaseComponent { */ protected OperationResult postProcessResult(String name, Result res) { OperationResult operationResult = new OperationResult(); - if (name.equals("shutdown")) { + if (name.equals("shutdown") || name.equals("reload")) { /* * Shutdown needs a special treatment, because after sending the operation, if shutdown suceeds, * the server connection is closed and we can't read from it. So if we get connection refused for * reading, this is a good sign. */ if (!res.isSuccess()) { - if (res.getThrowable()!=null && (res.getThrowable() instanceof ConnectException || res.getThrowable().getMessage().equals("Connection refused"))) + if (res.getThrowable()!=null && (res.getThrowable() instanceof ConnectException || res.getThrowable().getMessage().equals("Connection refused"))) { operationResult.setSimpleResult("Success"); + log.debug("Got a ConnectionRefused for operation " + name + " this is considered ok, as the remote server sometimes closes the communications channel before sending a reply"); + } else operationResult.setErrorMessage(res.getFailureDescription()); } + else { + operationResult.setSimpleResult("Success"); + } } else { if (res.isSuccess()) {
commit e3b39f8182290ede9b85410f7ca9afd74f5f3339 Author: Heiko W. Rupp hwr@redhat.com Date: Mon Aug 15 14:07:48 2011 +0200
Add support for the deployment scanner and (a little bit) for Infinispan.
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml index 56f9de3..ecf541d 100644 --- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml @@ -894,7 +894,7 @@ <parameters> <c:simple-property name="name" required="true" description="Name of the datasource"/> <c:simple-property name="driver-name" required="true"> - <c:option-source target="resource" expression="type=^Deployment$"/> + <c:option-source target="resource" expression="type=^Deployment$" filter="sameHierarchy"/> </c:simple-property> <c:simple-property name="jndi-name" description="JNDI-Name of the Datasource" required="true"/> <c:simple-property name="connection-url" description="URL for the connection to the database" required="true"/> @@ -1674,6 +1674,53 @@ working area for individual server instances</li></ul>"/>
</server>
+ <server name="Infinispan" + discovery="SubsystemDiscovery" + class="BaseComponent" + singleton="true" + > + <runs-inside> + <parent-resource-type name="Profile" plugin="jboss-as-7"/> + <parent-resource-type name="JBossAS7-Standalone" plugin="jboss-as-7"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="path" readOnly="true" default="subsystem=infinispan"/> + </plugin-configuration> + + <resource-configuration> + <c:simple-property name="default-cache-container" readOnly="true"/> + </resource-configuration> + + <service name="Cache Container" + discovery="SubsystemDiscovery" + class="BaseComponent" + > + <plugin-configuration> + <c:simple-property name="path" readOnly="true" default="cache-container"/> + </plugin-configuration> + + <resource-configuration> + <c:simple-property name="default-cache" readOnly="true"/> + <c:list-property name="cache" readOnly="true"> + <c:map-property name="*"> + <c:simple-property name="name" /> + <c:simple-property name="mode" /> +<!-- + <c:map-property name="eviction"> + <c:simple-property name="strategy"/> + <c:simple-property name="max-entries" required="false"/> + </c:map-property> +--> + <c:simple-property name="eviction" required="false" readOnly="true"/> + <c:simple-property name="expiration" required="false" readOnly="true"/> + </c:map-property> + </c:list-property> + </resource-configuration> + </service> + + </server> + <server name="Threads" discovery="SubsystemDiscovery" class="BaseComponent" @@ -1967,4 +2014,45 @@ working area for individual server instances</li></ul>"/>
</service>
+ <service name="DeploymentScanner" + class="BaseComponent" + discovery="SubsystemDiscovery" + description="Management of the deployment scanner" + singleton="true" + > + <runs-inside> + <parent-resource-type name="JBossAS7-Standalone" plugin="jboss-as-7"/> + </runs-inside> + <plugin-configuration> + <c:simple-property name="path" default="subsystem=deployment-scanner" readOnly="true"/> + </plugin-configuration> + + <resource-configuration> + <!--<c:simple-property name="default" readOnly="false" required="true" description="Scanner policy to use"/>--> + <c:group name="children:scanner:name" displayName="Available scanners"> + <c:list-property name="*" description="List of scanners" > + <c:map-property name="scanner"> + <c:simple-property name="name" required="true" type="string" readOnly="true" description="The name of the scanner"/> + <c:simple-property name="path" required="true" type="string" readOnly="false" + description="The actual filesystem path to be scanned. Treated as an absolute path, unless the 'relative-to' attribute is specified, in which case the value is treated as relative to that path."/> + <c:simple-property name="relative-to" required="false" type="string" readOnly="false" + description="Reference to a filesystem path defined in the 'paths' section of the server configuration."/> + <c:simple-property name="scan-enabled" required="false" type="boolean" readOnly="false" + defaultValue="true" description="Flag indicating that all scanning (including initial scanning at startup) should be disabled."/> + <c:simple-property name="scan-interval" required="false" type="integer" readOnly="false" + defaultValue="5000" description="Periodic interval, in milliseconds, at which the repository should be scanned for changes. A value of less than 1 indicates the repository should only be scanned at initial startup."/> + <c:simple-property name="auto-deploy-zipped" required="false" type="boolean" readOnly="false" + defaultValue="true" description="Controls whether zipped deployment content should be automatically deployed by the scanner without requiring the user to add a .dodeploy marker file."/> + <c:simple-property name="auto-deploy-exploded" required="false" type="boolean" readOnly="false" + defaultValue="false" description="Controls whether zipped deployment content should be automatically deployed by the scanner without requiring the user to add a .dodeploy marker file. Setting this to 'true' is not recommended for anything but basic development scenarios, as there is no way to ensure that deployment will not occur in the middle of changes to the content."/> + <c:simple-property name="deployment-timeout" required="false" type="long" readOnly="false" + defaultValue="60" description="Timeout, in seconds, a deployment is allows to execute before being canceled. The default is 60 seconds."/> + </c:map-property> + </c:list-property> + </c:group> + + </resource-configuration> + + </service> + </plugin>
commit 9f67314cd351a3d94ce7b00b02ed4ebab06e5d6d Author: John Sanda jsanda@redhat.com Date: Sat Aug 13 22:50:40 2011 -0400
Add filtering logic when generating drift change set
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 30519b6..c8e5061 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 @@ -145,7 +145,8 @@ public class DriftDetector implements Runnable { }
// Now we need to do a directory tree scan to look for newly added files - forEachFile(basedir, new FileVisitor() { + forEachFile(basedir, new FilterFileVisitor(schedule.getDriftConfiguration().getIncludes(), + schedule.getDriftConfiguration().getExcludes(), new FileVisitor() { @Override public void visit(File file) { try { @@ -162,7 +163,7 @@ public class DriftDetector implements Runnable { throw new DriftDetectionException("An error occurred while generating a drift change set", e); } } - }); + }));
driftWriter.close(); coverageWriter.close();
commit 9a4e53106f6a7a923b9f64e31275a55d154128d9 Author: John Sanda jsanda@redhat.com Date: Sat Aug 13 21:59:33 2011 -0400
Adding filtering support to DriftDetector
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 708a003..30519b6 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 @@ -174,10 +174,10 @@ public class DriftDetector implements Runnable { private void generateCoverageChangeSet(final DriftDetectionSchedule schedule) throws IOException { final ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, COVERAGE)); + final DriftConfiguration config = schedule.getDriftConfiguration(); + final File basedir = new File(basedir(schedule.getResourceId(), config));
- final File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration())); - - forEachFile(basedir, new FileVisitor() { + forEachFile(basedir, new FilterFileVisitor(config.getIncludes(), config.getExcludes(), new FileVisitor() { @Override public void visit(File file) { try { @@ -189,7 +189,7 @@ public class DriftDetector implements Runnable { schedule, e); } } - }); + })); writer.close(); }
commit b3def0fff5ec07cdd29fd4a9c0807a4f03e0ed26 Author: John Sanda jsanda@redhat.com Date: Sat Aug 13 15:08:14 2011 -0400
Adding logic and tests for filtering
The filtering is done in FilterFileVisitor and for files to be included, it delegates to an another instance of FileVisitor. Need to add some javadocs yet but the tests in FilterFileVisitorTest specify the filtering rules.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java index 88c1868..0c3b500 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -20,20 +20,62 @@ package org.rhq.core.pc.drift;
import java.io.File; +import java.util.ArrayList; import java.util.List; +import java.util.regex.Pattern;
import org.rhq.core.domain.drift.Filter; import org.rhq.core.util.file.FileVisitor; +import org.rhq.core.util.file.PathFilter; + +import static org.rhq.core.util.file.FileUtil.generateRegex;
public class FilterFileVisitor implements FileVisitor {
+ private List<PathFilter> includes; + + private List<PathFilter> excludes; + private FileVisitor visitor;
+ private Pattern includesPattern; + + private Pattern excludesPattern; + public FilterFileVisitor(List<Filter> includes, List<Filter> excludes, FileVisitor visitor) { + this.includes = convert(includes); + this.excludes = convert(excludes); this.visitor = visitor; + includesPattern = generateRegex(this.includes); + excludesPattern = generateRegex(this.excludes); + } + + private List<PathFilter> convert(List<Filter> filters) { + List<PathFilter> pathFilters = new ArrayList<PathFilter>(filters.size()); + for (Filter filter : filters) { + pathFilters.add(new PathFilter(filter.getPath(), filter.getPattern())); + } + return pathFilters; }
@Override public void visit(File file) { + if (includes.isEmpty() && excludes.isEmpty()) { + visitor.visit(file); + } else if (!includes.isEmpty() && excludes.isEmpty()) { + if (includesPattern.matcher(file.getAbsolutePath()).matches()) { + visitor.visit(file); + } + } else if (includes.isEmpty() && !excludes.isEmpty()) { + if (!excludesPattern.matcher(file.getAbsolutePath()).matches()) { + visitor.visit(file); + } + } else { + // else neither includes nor excludes is empty + if (includesPattern.matcher(file.getAbsolutePath()).matches() && + !excludesPattern.matcher(file.getAbsolutePath()).matches()) { + visitor.visit(file); + } + } } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java index e9b7918..2636583 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java @@ -20,16 +20,28 @@ package org.rhq.core.pc.drift;
import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List;
+import org.apache.commons.io.FileUtils; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
+import org.rhq.core.domain.drift.Filter; +import org.rhq.core.util.file.FileVisitor; + +import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; import static org.apache.commons.io.FileUtils.deleteDirectory; import static org.apache.commons.io.FileUtils.toFile; +import static org.rhq.core.util.file.FileUtil.forEachFile; +import static org.rhq.test.AssertUtils.assertCollectionEqualsNoOrder; +import static org.testng.Assert.assertTrue;
public class FilterFileVisitorTest {
- File basedir; + private File basedir;
@BeforeMethod public void setUp() throws Exception { @@ -40,9 +52,131 @@ public class FilterFileVisitorTest { }
@Test - public void callVisitorWhenFileMatchesIncludeFilter() { -// touch(new ); -// List<Filter> includes = asList(new Filter("")); + public void visitAllFilesWhenNoFiltersSpecified() throws Exception { + File libDir = mkdir(basedir, "lib"); + File server1Jar = touch(libDir, "server-1.jar"); + File server2Jar = touch(libDir, "server-2.jar"); + + File nativeLibDir = mkdir(libDir, "native"); + File nativeServer1Lib = touch(nativeLibDir, "server-1.so"); + File nativeServer2Lib = touch(nativeLibDir, "server-2.so"); + + List<Filter> includes = emptyList(); + List<Filter> excludes = emptyList(); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(server1Jar, server2Jar, nativeServer1Lib, nativeServer2Lib), + visitor.visitedFiles, "Visitor should be called for every file when no filters specified"); + } + + @Test + public void visitFilesThatMatchIncludes() throws Exception { + File libDir = mkdir(basedir, "lib"); + File fooJar = touch(libDir, "foo.jar"); + File fooWar = touch(libDir, "foo-1.jar"); + File myapp = touch(libDir, "myapp.war"); + touch(libDir, "bar.jar"); + + List<Filter> includes = asList(new Filter(libDir.getAbsolutePath(), "foo*"), + new Filter(libDir.getAbsolutePath(), "*.war")); + List<Filter> excludes = emptyList(); + TestVisitor visitor = new TestVisitor(); + + forEachFile(libDir, new FilterFileVisitor(includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(fooJar, fooWar, myapp), visitor.visitedFiles, + "Filtering failed with mulitple includes and no excludes"); + } + + @Test + public void doNotVisitFileThatDoesNotMatchInclude() throws Exception { + touch(basedir, "server.txt"); + + List<Filter> includes = asList(new Filter(basedir.getAbsolutePath(), "*.html")); + List<Filter> excludes = emptyList(); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + + assertTrue(visitor.visitedFiles.isEmpty(), "Do not visit files that do not match an includes filter"); + } + + @Test + public void visitFileThatDoesNotMatchExcludes() throws Exception { + File server1Txt = touch(basedir, "server-1.txt"); + File server1Html = touch(basedir, "server-1.html"); + + List<Filter> includes = emptyList(); + List<Filter> excludes = asList(new Filter(basedir.getAbsolutePath(), "*.txt")); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(server1Html), visitor.visitedFiles, "Visit files that do not match " + + "excludes filter and no includes are specified"); + } + + @Test + public void doNotVisitFileThatMatchesExclude() throws Exception { + File libDir = mkdir(basedir, "lib"); + File server1Jar = touch(libDir, "server-1.jar"); + File server2Jar = touch(libDir, "server-2.jar"); + + List<Filter> includes = emptyList(); + List<Filter> excludes = asList(new Filter(libDir.getAbsolutePath(), "server-1.jar")); + TestVisitor visitor = new TestVisitor(); + + forEachFile(libDir, new FilterFileVisitor(includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(server2Jar), visitor.visitedFiles, + "Filtering failed when no includes an exclude were specified."); + } + + @Test + public void visitFileThatMatchesIncludeAndDoesNotMatchesExclude() throws Exception { + // This test also verifies that files that match an include and also match + // an exclude are not visited. + + File libDir = mkdir(basedir, "lib"); + File server1Jar = touch(libDir, "server-1.jar"); + File server2Jar = touch(libDir, "server-2.jar"); + + File confDir = mkdir(basedir, "conf"); + File server1Conf = touch(confDir, "server-1.conf"); + File server2Conf = touch(confDir, "server-2.conf"); + + List<Filter> includes = asList(new Filter(basedir.getAbsolutePath(), "**/*.*")); + List<Filter> excludes = asList(new Filter(confDir.getAbsolutePath(), "server-2.conf")); + TestVisitor visitor = new TestVisitor(); + + forEachFile(basedir, new FilterFileVisitor(includes, excludes, visitor)); + + assertCollectionEqualsNoOrder(asList(server1Jar, server2Jar, server1Conf), visitor.visitedFiles, + "Do not visit files that match an excludes even when the file matches an include"); + } + + private File mkdir(File parent, String dirName) throws IOException { + File dir = new File(parent, dirName); + dir.mkdirs(); + return dir; + } + + private File touch(File dir, String fileName) throws IOException { + File file = new File(dir, fileName); + FileUtils.touch(file); + return file; + } + + static class TestVisitor implements FileVisitor { + + public List<File> visitedFiles = new ArrayList<File>(); + + @Override + public void visit(File file) { + visitedFiles.add(file); + } }
} 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 5776424..761b941 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 @@ -347,10 +347,10 @@ public class FileUtil { } }
- public static Pattern generateRegex(List<Filter> filters) { + public static Pattern generateRegex(List<PathFilter> filters) { boolean first = true; StringBuilder regex = new StringBuilder(); - for (Filter filter : filters) { + for (PathFilter filter : filters) { if (!first) { regex.append("|"); } else { diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java deleted file mode 100644 index f0fc34b..0000000 --- a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java +++ /dev/null @@ -1,40 +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.util.file; - -public class Filter { - - private String path; - - private String pattern; - - public Filter(String path, String pattern) { - this.path = path; - this.pattern = pattern; - } - - public String getPath() { - return path; - } - - public String getPattern() { - return pattern; - } -} diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/PathFilter.java b/modules/core/util/src/main/java/org/rhq/core/util/file/PathFilter.java new file mode 100644 index 0000000..7d33e94 --- /dev/null +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/PathFilter.java @@ -0,0 +1,40 @@ +/* + * 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.util.file; + +public class PathFilter { + + private String path; + + private String pattern; + + public PathFilter(String path, String pattern) { + this.path = path; + this.pattern = pattern; + } + + public String getPath() { + return path; + } + + public String getPattern() { + return pattern; + } +} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java index 125ead8..59265eb 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java @@ -217,8 +217,15 @@ public class FileUtilTest { public void testGetPattern() { Pattern regex;
+ regex = assertPatternsRegex("(/basedir/(test1\.txt))", new PathFilter("/basedir", "test1.txt")); + //regex = Pattern.compile("/basedir/test1\.txt"); + //regex = Pattern.compile("(/basedir/(test1\.txt))"); + + assert regex.matcher("/basedir/test1.txt").matches(); + assert !regex.matcher("/basedir/test2.txt").matches(); + regex = assertPatternsRegex("(/basedir/easy\.txt)|(/basedir/test\.txt)", - new Filter("/basedir/easy.txt", null), new Filter("/basedir/test.txt", null)); + new PathFilter("/basedir/easy.txt", null), new PathFilter("/basedir/test.txt", null));
assert regex.matcher("/basedir/easy.txt").matches(); assert regex.matcher("/basedir/test.txt").matches(); @@ -231,7 +238,7 @@ public class FileUtilTest { assert !regex.matcher("easy.txt").matches() : "missing basedir"; assert !regex.matcher("test.txt").matches() : "missing basedir";
- regex = assertPatternsRegex("(/basedir/([^/]*\.txt))", new Filter("/basedir", "*.txt")); + regex = assertPatternsRegex("(/basedir/([^/]*\.txt))", new PathFilter("/basedir", "*.txt"));
assert regex.matcher("/basedir/foo.txt").matches(); assert regex.matcher("/basedir/file with spaces.txt").matches(); @@ -240,7 +247,7 @@ public class FileUtilTest { assert !regex.matcher("/basedir/foo.txt.swp").matches();
regex = assertPatternsRegex("(/var/lib/([^/]*\.war))|(/var/lib/([^/]*\.ear))", - new Filter("/var/lib", "*.war"), new Filter("/var/lib", "*.ear")); + new PathFilter("/var/lib", "*.war"), new PathFilter("/var/lib", "*.ear"));
assert regex.matcher("/var/lib/myapp.war").matches(); assert regex.matcher("/var/lib/myapp.ear").matches(); @@ -250,21 +257,21 @@ public class FileUtilTest { assert !regex.matcher("myapp.ear").matches(); assert !regex.matcher("/var/lib/myapp.ear.rej").matches();
- regex = assertPatternsRegex("(/conf/(server-.\.conf))", new Filter("/conf", "server-?.conf")); + regex = assertPatternsRegex("(/conf/(server-.\.conf))", new PathFilter("/conf", "server-?.conf"));
assert regex.matcher("/conf/server-1.conf").matches(); assert regex.matcher("/conf/server-X.conf").matches(); assert !regex.matcher("/conf/subconf/server-1.conf").matches(); assert !regex.matcher("/conf/server.conf").matches();
- regex = assertPatternsRegex("(/etc/(.*[^/]*\.conf))", new Filter("/etc", "**/*.conf")); + regex = assertPatternsRegex("(/etc/(.*[^/]*\.conf))", new PathFilter("/etc", "**/*.conf"));
assert regex.matcher("/etc/yum.conf").matches(); assert regex.matcher("/etc/httpd/httpd.conf").matches(); assert !regex.matcher("/etc/foo.conf/foo").matches(); }
- private Pattern assertPatternsRegex(String expectedPattern, Filter... filters) { + private Pattern assertPatternsRegex(String expectedPattern, PathFilter... filters) { Pattern regex = FileUtil.generateRegex(asList(filters));
assert regex != null : "The regex was not able to be produced - it was null";
commit e474d2746b5ac22692857b58c73457ec5877a206 Author: John Mazzitelli mazz@redhat.com Date: Sat Aug 13 02:28:51 2011 -0400
deleting drift configuration now works. need to test that the agent is being told properly and is stopping the drift detection this also adds to data purge job - orphaned drift files are now purged - i.e. if no drift entities are pointing to a drift file, that drift file is purged
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java index 3a9c6b9..e426a78 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java @@ -43,6 +43,30 @@ import javax.persistence.Table; public class JPADriftFile extends AbstractJPADriftFile implements Serializable, DriftFile { private static final long serialVersionUID = 1L;
+ /* + * This should be proper JPSQL to delete drift file entities if there are no drift entities referencing them: + * + * DELETE FROM JPADriftFile f + * WHERE f.hashId NOT IN (SELECT d1.oldDriftFile FROM JPADrift d1) + * AND f.hashId NOT IN (SELECT d2.newDriftFile FROM JPADrift d2) + * + * However, Hibernate erroneously translates this to: + * + * delete from RHQ_DRIFT_FILE + * where (HASH_ID not in (select jpadrift1_.OLD_DRIFT_FILE from RHQ_DRIFT jpadrift1_)) + * and (jpadriftfi0_.HASH_ID not in (select jpadrift2_.NEW_DRIFT_FILE from RHQ_DRIFT jpadrift2_)) + * + * Notice "jpadriftfi0_" SHOULD be the alias of RHQ_DRIFT_FILE, but it is not being defined by Hibernate. + * Thus, that alias is unknown and a parse error occurs in the database engine. + * + * Therefore, we need to define a native query that we know works. This should be periodically executed + * in order to purge unused drift files. + */ + public static final String NATIVE_DELETE_ORPHANED_DRIFT_FILES = "" // + + "DELETE FROM RHQ_DRIFT_FILE " // + + " WHERE (HASH_ID NOT IN (SELECT OLD_DRIFT_FILE FROM RHQ_DRIFT)) " // + + " AND (HASH_ID NOT IN (SELECT NEW_DRIFT_FILE FROM RHQ_DRIFT)) "; + // this is a hash/digest that should uniquely identify the content @Id @Column(name = "HASH_ID", nullable = false) 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 738bc66..c486401 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 @@ -23,7 +23,6 @@ import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
import java.io.File; import java.io.InputStream; -import java.util.Iterator;
import javax.ejb.EJB; import javax.ejb.Stateless; @@ -240,23 +239,8 @@ public class DriftManagerBean implements DriftManagerLocal {
@Override public void deleteResourceDriftConfiguration(Subject subject, int resourceId, int driftConfigId) { - Resource resource = entityManager.getReference(Resource.class, resourceId); - boolean removed = false; - Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); - while (i.hasNext()) { - DriftConfiguration next = i.next(); - if (next.getId() == driftConfigId) { - i.remove(); - removed = true; - break; - } - } - - // just removing the drift config from the list of drift configs associated with the resource will purge it. - // this is because the DELETE_ORPHAN annotation is on the resource drift config field - if (removed) { - entityManager.merge(resource); - } + DriftConfiguration doomed = entityManager.getReference(DriftConfiguration.class, driftConfigId); + entityManager.remove(doomed); return; }
@@ -347,6 +331,13 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + @TransactionAttribute(NOT_SUPPORTED) + public int purgeOrphanedDriftFiles(Subject subject) { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.purgeOrphanedDriftFiles(subject); + } + + @Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) {
// before we do anything, make sure the drift config name is valid 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 51ba572..cc515d3 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 @@ -98,4 +98,13 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR * @param driftConfig */ void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig); + + /** + * This will remove all drift files that are no longer referenced by drift entries. This is a maintenance method + * to help reclaim space on the backend. + * + * @param subject + * @return number of orphaned drife files that were removed + */ + int purgeOrphanedDriftFiles(Subject subject); } 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 6d89ad3..c55032e 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 @@ -100,6 +100,15 @@ public class JPADriftServerBean implements JPADriftServerLocal {
@Override @TransactionAttribute(REQUIRES_NEW) + public int purgeOrphanedDriftFiles(Subject subject) { + Query q = entityManager.createNativeQuery(JPADriftFile.NATIVE_DELETE_ORPHANED_DRIFT_FILES); + int count = q.executeUpdate(); + log.debug("purged [" + count + "] drift files that were orphaned (that is, no longer referenced by drift)"); + return count; + } + + @Override + @TransactionAttribute(REQUIRES_NEW) public void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception {
int driftsDeleted; 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 eb46f18..3f4f0f0 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 @@ -114,4 +114,14 @@ public interface JPADriftServerLocal { * This purges all drift entities and changeset entities associated with the drift config. */ void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception; + + /** + * SUPPORTS JPA DRIFT SERVER PLUGIN + * This will remove all drift files that are no longer referenced by drift entries. This is a maintenance method + * to help reclaim space on the backend. + * + * @param subject + * @return number of orphaned drife files that were removed + */ + int purgeOrphanedDriftFiles(Subject subject); } 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 9868f0e..29e65e5 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 @@ -85,4 +85,13 @@ public interface DriftServerPluginFacet { * @param driftConfigName identifies the data that is to be purged */ void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception; + + /** + * This will remove all drift files that are no longer referenced by drift entries. This is a maintenance method + * to help reclaim space on the backend. + * + * @param subject + * @return number of orphaned drife files that were removed + */ + int purgeOrphanedDriftFiles(Subject subject); } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java index ffc5dfc..3423540 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJob.java @@ -35,6 +35,7 @@ import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.alert.AlertDefinitionManagerLocal; import org.rhq.enterprise.server.alert.AlertManagerLocal; import org.rhq.enterprise.server.alert.AlertNotificationManagerLocal; +import org.rhq.enterprise.server.drift.DriftManagerLocal; import org.rhq.enterprise.server.event.EventManagerLocal; import org.rhq.enterprise.server.measurement.AvailabilityManagerLocal; import org.rhq.enterprise.server.measurement.CallTimeDataManagerLocal; @@ -120,6 +121,7 @@ public class DataPurgeJob extends AbstractStatefulJob { purgeOrphanedAlertNotifications(LookupUtil.getAlertNotificationManager()); purgeMeasurementTraitData(LookupUtil.getMeasurementDataManager(), systemConfig); purgeAvailabilityData(LookupUtil.getAvailabilityManager(), systemConfig); + purgeOrphanedDriftFiles(LookupUtil.getDriftManager()); }
private void purgeMeasurementTraitData(MeasurementDataManagerLocal measurementDataManager, Properties systemConfig) { @@ -252,6 +254,21 @@ public class DataPurgeJob extends AbstractStatefulJob { } }
+ private void purgeOrphanedDriftFiles(DriftManagerLocal driftManager) { + long timeStart = System.currentTimeMillis(); + LOG.info("Drift file orphan purge starting at " + new Date(timeStart)); + int orphansPurged = 0; + + try { + orphansPurged = driftManager.purgeOrphanedDriftFiles(LookupUtil.getSubjectManager().getOverlord()); + } catch (Exception e) { + LOG.error("Failed to purge orphaned drift files. Cause: " + e, e); + } finally { + long duration = System.currentTimeMillis() - timeStart; + LOG.info("Purged [" + orphansPurged + "] orphaned drift files - completed in [" + duration + "]ms"); + } + } + private void performDatabaseMaintenance(SystemManagerLocal systemManager, Properties systemConfig) { long timeStart = System.currentTimeMillis(); LOG.info("Database maintenance starting at " + new Date(timeStart)); 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 6dc1545..d0db7d0 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 @@ -221,6 +221,12 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC // TODO implement me! }
+ @Override + public int purgeOrphanedDriftFiles(Subject subject) { + // TODO implement me! + return 0; + } + Map<Integer, Resource> loadResourceMap(Subject subject, Integer[] resourceIds) { ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterIds(resourceIds); 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 d964133..4d228bb 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 @@ -118,4 +118,8 @@ public class JPADriftServerPluginComponent implements DriftServerPluginFacet, Se getJPADriftServer().purgeByDriftConfigurationName(subject, resourceId, driftConfigName); }
+ @Override + public int purgeOrphanedDriftFiles(Subject subject) { + return getJPADriftServer().purgeOrphanedDriftFiles(subject); + } }
commit 4fad1a23df540d2233914f7bb8410fe9b944ba3c Author: John Mazzitelli mazz@redhat.com Date: Sat Aug 13 00:56:52 2011 -0400
more work on deleting drift configuration - still not finished. need to fix deleting the drift config entity itself
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 02d41da..b56597e 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 @@ -49,13 +49,20 @@ import javax.persistence.Table; @Entity @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 ) ) )") }) + + " WHERE d.changeSet IN ( SELECT dcs FROM JPADriftChangeSet dcs WHERE dcs.resource.id IN ( :resourceIds ) ) )"), // + @NamedQuery(name = JPADrift.QUERY_DELETE_BY_DRIFTCONFIG_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)") }) @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";
@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 f739389..f9509bb 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 @@ -55,13 +55,22 @@ import org.rhq.core.domain.resource.Resource; @Entity @NamedQueries( { @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_RESOURCES, query = "" // + "DELETE FROM JPADriftChangeSet dcs " // - + " WHERE dcs.resource.id IN ( :resourceIds )") }) + + " WHERE dcs.resource.id IN ( :resourceIds )"), // + @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE, query = "" // + + "DELETE FROM JPADriftChangeSet dcs " // + + " WHERE dcs.resource.id = :resourceId " // + + " AND dcs.driftConfiguration.id IN " // + + " (SELECT dc.id " // + + " FROM DriftConfiguration dc " // + + " WHERE dc.resource.id = :resourceId AND dc.name = :driftConfigurationName)" // + ) }) @Table(name = "RHQ_DRIFT_CHANGE_SET") @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DRIFT_CHANGE_SET_ID_SEQ") 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";
@Column(name = "ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") diff --git a/modules/enterprise/server/container/src/main/resources/jbossas/server/default/conf/jboss-log4j.xml b/modules/enterprise/server/container/src/main/resources/jbossas/server/default/conf/jboss-log4j.xml index 8ec0af5..16b0384 100644 --- a/modules/enterprise/server/container/src/main/resources/jbossas/server/default/conf/jboss-log4j.xml +++ b/modules/enterprise/server/container/src/main/resources/jbossas/server/default/conf/jboss-log4j.xml @@ -325,7 +325,21 @@ <!-- log JDBC bind parameters --> <!-- <category name="org.hibernate.type"> - <priority value="INFO"/> + <priority value="DEBUG"/> + </category> + --> + + <!-- log JDBC bind parameters --> + <!-- + <category name="org.hibernate.engine.query"> + <priority value="DEBUG"/> + </category> + --> + + <!-- Log all JDBC resource acquisition --> + <!-- + <category name="org.hibernate.jdbc"> + <priority value="DEBUG"/> </category> -->
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 abbe352..738bc66 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 @@ -191,6 +191,7 @@ public class DriftManagerBean implements DriftManagerLocal { DriftConfigurationCriteria criteria = new DriftConfigurationCriteria(); criteria.addFilterName(driftConfigName); criteria.addFilterResourceIds(resourceId); + criteria.setStrict(true); PageList<DriftConfiguration> results = driftManager.findDriftConfigurationsByCriteria(subject, criteria); DriftConfiguration doomedDriftConfig = null; if (results != null && results.size() == 1) { @@ -226,6 +227,9 @@ public class DriftManagerBean implements DriftManagerLocal {
// now purge the drift config itself driftManager.deleteResourceDriftConfiguration(subject, resourceId, doomedDriftConfig.getId()); + } else { + throw new IllegalArgumentException("Resource does not have drift config named [" + driftConfigName + + "]"); } break;
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 277daff..6d89ad3 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 @@ -37,6 +37,7 @@ import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import javax.persistence.Query;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -65,6 +66,7 @@ import org.rhq.core.domain.drift.JPADriftFile; import org.rhq.core.domain.drift.JPADriftFileBits; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.StopWatch; import org.rhq.core.util.ZipUtil; import org.rhq.core.util.file.FileUtil; import org.rhq.enterprise.server.RHQConstants; @@ -97,9 +99,29 @@ public class JPADriftServerBean implements JPADriftServerLocal { private EntityManager entityManager;
@Override + @TransactionAttribute(REQUIRES_NEW) public void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception { - // TODO security checks - System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + resourceId + " !!!" + driftConfigName); + + int driftsDeleted; + int changeSetsDeleted; + StopWatch timer = new StopWatch(); + + // purge all drift entities first + Query q = entityManager.createNamedQuery(JPADrift.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE); + q.setParameter("resourceId", resourceId); + q.setParameter("driftConfigurationName", driftConfigName); + driftsDeleted = q.executeUpdate(); + + // now purge all changesets + q = entityManager.createNamedQuery(JPADriftChangeSet.QUERY_DELETE_BY_DRIFTCONFIG_RESOURCE); + q.setParameter("resourceId", resourceId); + q.setParameter("driftConfigurationName", driftConfigName); + changeSetsDeleted = q.executeUpdate(); + + log.info("Purged [" + driftsDeleted + "] drift items and [" + changeSetsDeleted + + "] changesets associated with drift config [" + driftConfigName + "] from resource [" + resourceId + + "]. Elapsed time=[" + timer.getElapsed() + "]ms"); + return; }
@Override
commit 7e8d4fd6fa6a08cd5bb564fa0c91538c754143f5 Author: John Sanda jsanda@redhat.com Date: Fri Aug 12 17:18:52 2011 -0400
Make sure new properties are added to the configuration
There are situations where a property def exists but no corresponding property in the configuration. In those cases the config editor creates new properties, but they were not added to the configuration; consequently, those properties will not be persisted as part of the configuration. This commit fixes that.
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..cda038d 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 @@ -599,6 +599,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (propertySimple == null) { propertySimple = new PropertySimple(propertyDefinitionSimple.getName(), null); + configuration.put(propertySimple); }
fieldsForThisProperty = buildFieldsForPropertySimple(propertyDefinition, propertyDefinitionSimple, @@ -609,6 +610,7 @@ public class ConfigurationEditor extends LocatableVLayout { PropertyList propertyList = (PropertyList) property; if (propertyList == null) { propertyList = new PropertyList(propertyDefinitionList.getName()); + configuration.put(propertyList); } fieldsForThisProperty = buildFieldsForPropertyList(locatorId, propertyDefinition, oddRow, propertyDefinitionList, memberDefinition, propertyList); @@ -617,6 +619,7 @@ public class ConfigurationEditor extends LocatableVLayout { PropertyMap propertyMap = (PropertyMap) property; if (propertyMap == null) { propertyMap = new PropertyMap(propertyDefinitionMap.getName()); + configuration.put(propertyMap); }
fieldsForThisProperty = buildFieldsForPropertyMap(locatorId, propertyDefinitionMap, propertyMap);
commit d619c5150a661a872c502cbda48570b0f8b25b74 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 17:04:57 2011 -0400
more on getting the ability to delete drift configuration only thing left is to implement the server plugins to delete changesets and drifts
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 69cd6d5..abbe352 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 @@ -23,6 +23,7 @@ import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
import java.io.File; import java.io.InputStream; +import java.util.Iterator;
import javax.ejb.EJB; import javax.ejb.Stateless; @@ -111,6 +112,9 @@ public class DriftManagerBean implements DriftManagerLocal { private AgentManagerLocal agentManager;
@EJB + private DriftManagerLocal driftManager; // ourself + + @EJB private SubjectManagerLocal subjectManager;
// use a new transaction when putting things on the JMS queue. see @@ -178,42 +182,50 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + @TransactionAttribute(NOT_SUPPORTED) public void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName) {
- // TODO security check! - switch (entityContext.getType()) { case Resource: int resourceId = entityContext.getResourceId(); - Resource resource = entityManager.find(Resource.class, resourceId); - if (null == resource) { - throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); - } - + DriftConfigurationCriteria criteria = new DriftConfigurationCriteria(); + criteria.addFilterName(driftConfigName); + criteria.addFilterResourceIds(resourceId); + PageList<DriftConfiguration> results = driftManager.findDriftConfigurationsByCriteria(subject, criteria); DriftConfiguration doomedDriftConfig = null; - for (DriftConfiguration dc : resource.getDriftConfigurations()) { - if (dc.getName().equals(driftConfigName)) { - doomedDriftConfig = dc; - break; - } + if (results != null && results.size() == 1) { + doomedDriftConfig = results.get(0); }
if (doomedDriftConfig != null) { + + // TODO security check! + // tell the agent first - we don't want the agent reporting on the drift config after we delete it + boolean unscheduledOnAgent = false; try { AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService(); - // make a copy of the config, so we don't mess with the attached original - // note that we don't copy over the resource reference, that's also attached but we don't need it in the copy anyway - DriftConfiguration copy = new DriftConfiguration(doomedDriftConfig.getConfiguration().clone()); - service.unscheduleDriftDetection(resourceId, copy); + service.unscheduleDriftDetection(resourceId, doomedDriftConfig); + unscheduledOnAgent = true; } catch (Exception e) { log.warn(" Unable to inform agent of unscheduled drift detection [" + doomedDriftConfig + "]", e); }
- resource.getDriftConfigurations().remove(doomedDriftConfig); - doomedDriftConfig.setResource(null); - resource = entityManager.merge(resource); + // purge all data related to this drift configuration + try { + driftManager.purgeByDriftConfigurationName(subject, resourceId, doomedDriftConfig.getName()); + } catch (Exception e) { + String warnMessage = "Failed to purge data for drift configuration [" + driftConfigName + + "] for resource [" + resourceId + "]."; + if (unscheduledOnAgent) { + warnMessage += " The agent was told to stop detecting drift for that configuration."; + } + log.warn(warnMessage, e); + } + + // now purge the drift config itself + driftManager.deleteResourceDriftConfiguration(subject, resourceId, doomedDriftConfig.getId()); } break;
@@ -223,6 +235,28 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + public void deleteResourceDriftConfiguration(Subject subject, int resourceId, int driftConfigId) { + Resource resource = entityManager.getReference(Resource.class, resourceId); + boolean removed = false; + Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); + while (i.hasNext()) { + DriftConfiguration next = i.next(); + if (next.getId() == driftConfigId) { + i.remove(); + removed = true; + break; + } + } + + // just removing the drift config from the list of drift configs associated with the resource will purge it. + // this is because the DELETE_ORPHAN annotation is on the resource drift config field + if (removed) { + entityManager.merge(resource); + } + return; + } + + @Override @TransactionAttribute(NOT_SUPPORTED) public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { @@ -292,6 +326,22 @@ public class DriftManagerBean implements DriftManagerLocal { driftServerPlugin.saveChangeSetFiles(subject, changeSetFilesZip); }
+ /** + * 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. + * + * If you want to delete a drift configuration and all that that entails, you must use + * {@link #deleteDriftConfiguration(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 { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + driftServerPlugin.purgeByDriftConfigurationName(subject, resourceId, driftConfigName); + } + @Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) {
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 eddd4c3..51ba572 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 @@ -66,6 +66,11 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName);
/** + * 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); + + /** * One time on-demand request to detect drift on the specified entities, using the supplied config. * * @param entityContext 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 163ad16..277daff 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,8 @@ */ package org.rhq.enterprise.server.drift;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -72,8 +74,6 @@ import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; - /** * The SLSB method implementation needed to support the JPA (RHQ Default) Drift Server Plugin. * @@ -97,6 +97,12 @@ public class JPADriftServerBean implements JPADriftServerLocal { private EntityManager entityManager;
@Override + public void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception { + // TODO security checks + System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + resourceId + " !!!" + driftConfigName); + } + + @Override public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { // TODO security checks DriftSnapshot snapshot = new DriftSnapshot(); 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 7f1516c..eb46f18 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 @@ -108,4 +108,10 @@ public interface JPADriftServerLocal { */ void storeFiles(Subject subject, File filesZip) throws Exception;
+ /** + * SUPPORTS JPA DRIFT SERVER PLUGIN + * 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; } 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 1da1738..9868f0e 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 @@ -75,4 +75,14 @@ public interface DriftServerPluginFacet { void saveChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception;
void saveChangeSetFiles(Subject subject, File changeSetFilesZip) throws Exception; + + /** + * When a user wants to completely remove all data related to a drift configuration, + * 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. + * @param Subject + * @param resourceId the resource whose drift configuration is being purged + * @param driftConfigName identifies the data that is to be purged + */ + void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception; } 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 cb22062..6dc1545 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 @@ -19,6 +19,8 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; + import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; @@ -64,8 +66,6 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; import org.rhq.enterprise.server.resource.ResourceManagerLocal;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; - public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
//private final Log log = LogFactory.getLog(MongoDBDriftServer.class); @@ -216,6 +216,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC return null; }
+ @Override + public void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception { + // TODO implement me! + } + Map<Integer, Resource> loadResourceMap(Subject subject, Integer[] resourceIds) { ResourceCriteria criteria = new ResourceCriteria(); criteria.addFilterIds(resourceIds); 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 e213e2f..d964133 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 @@ -113,4 +113,9 @@ public class JPADriftServerPluginComponent implements DriftServerPluginFacet, Se getJPADriftServer().storeFiles(subject, changeSetFilesZip); }
+ @Override + public void purgeByDriftConfigurationName(Subject subject, int resourceId, String driftConfigName) throws Exception { + getJPADriftServer().purgeByDriftConfigurationName(subject, resourceId, driftConfigName); + } + }
commit 27db80948605754a2e02d01ad4631e270234cf0d Author: Heiko W. Rupp hwr@redhat.com Date: Fri Aug 12 20:27:01 2011 +0200
BZ 719983 - provide a better version string
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..daa0447 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 @@ -44,6 +44,7 @@ public abstract class AbstractBaseDiscovery<T extends ResourceComponent> impleme static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file="; private static final String DJBOSS_SERVER_HOME_DIR = "-Djboss.home.dir"; static final int DEFAULT_MGMT_PORT = 9990; + private static final String JBOSS_AS_PREFIX = "jboss-as-"; protected Document hostXml; protected final Log log = LogFactory.getLog(this.getClass());
@@ -256,6 +257,17 @@ public abstract class AbstractBaseDiscovery<T extends ResourceComponent> impleme
}
+ protected String determineServerVersionFromHomeDir(String homeDir) { + String version; + String tmp = homeDir.substring(homeDir.lastIndexOf("/")+1); + if (tmp.startsWith("jboss-as-")) { + version = tmp.substring(JBOSS_AS_PREFIX.length()); + } else { + version = homeDir.substring(homeDir.lastIndexOf("-") + 1); + } + return version; + } + /** * Helper class that holds information about the host,port tuple */ 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 9d289f3..8e73205 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 @@ -52,11 +52,7 @@ import org.rhq.core.system.ProcessInfo; public class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent
{ - - static final String DJBOSS_HOME_DIR = "-Djboss.home.dir="; static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file="; - static final String DLOGGING_CONFIGURATION = "-Dlogging.configuration="; - static final String DASH_DASH_SERVER_CONFIG = "--server-config="; private final Log log = LogFactory.getLog(this.getClass());
/** @@ -77,6 +73,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou String serverName; String psName = psr.getProcessScan().getName(); String description = discoveryContext.getResourceType().getDescription(); + String homeDir = getHomeDirFromCommandLine(commandLine); String version = null;
//retrieve specific boot log file. Override for Standalone as server.log is more appropriate @@ -96,9 +93,8 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou serverName = "HostController"; // TODO make more unique serverNameFull = "HostController"; } - String homeDir = getHomeDirFromCommandLine(psr.getProcessInfo().getCommandLine()); + config.put(new PropertySimple("baseDir", homeDir)); - version = homeDir.substring(homeDir.lastIndexOf("-") + 1); config.put(new PropertySimple("startScript", AS7Mode.DOMAIN.getStartScript())); String host = findHost(psr.getProcessInfo(), true); config.put(new PropertySimple("domainHost", host)); @@ -112,9 +108,9 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou config.put(new PropertySimple("hostConfig",hostConfig));
} else { // Standalone server - serverNameFull = getHomeDirFromCommandLine(commandLine); + serverNameFull = homeDir; readStandaloneOrHostXml(psr.getProcessInfo(), false); - if (serverNameFull == null || serverNameFull.isEmpty()) { + if ( serverNameFull.isEmpty()) { // Try to obtain the server name // -Dorg.jboss.boot.log.file=domain/servers/server-one/log/boot.log // This is a hack until I know a better way to do so. @@ -134,7 +130,6 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou if (serverName.isEmpty()) serverName = serverNameFull;
- version = serverName.substring(serverName.lastIndexOf("-") + 1);
String serverConfig = getServerConfigFromCommandLine(commandLine, AS7Mode.STANDALONE); config.put(new PropertySimple("config",serverConfig)); diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java index 7764e63..5a105bd 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASDiscovery.java @@ -104,7 +104,7 @@ public class ManagedASDiscovery extends AbstractBaseDiscovery String homeDir = getHomeDirFromCommandLine(processInfo.getCommandLine()); initLogFile(scans, serverInfo.name, config, homeDir);
- String version = homeDir.substring(homeDir.lastIndexOf("-") + 1); + String version = determineServerVersionFromHomeDir(homeDir);
DiscoveredResourceDetails detail = new DiscoveredResourceDetails(discoveryContext.getResourceType(), // ResourceType hostName + "/" + serverInfo.name, // key
commit 631c1c8dcd43682198bf8bd337ade36b78f1d56b Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 14:00:54 2011 -0400
remove delete drift capabilities fix drift config comparator so basedir is part of the directory specification that is compared
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 index 406bdd0..75098c8 100644 --- 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 @@ -24,8 +24,8 @@ import java.util.List;
/** * Compares two {@link DriftConfiguration} objects. The comparison can either - * compare includes/excludes filters or ignore them. Will also compare - * name, interval, enabled flag and base directory. + * compare basedir/includes-excludes filters or ignore them. Will also compare + * name, interval, enabled flag. * * @author John Mazzitelli */ @@ -33,22 +33,22 @@ public class DriftConfigurationComparator implements Comparator<DriftConfigurati
public enum CompareMode { /** - * The comparator will only check the base information: name, enabled, interval, basedirectory. - * The includes/excludes filters will be ignored. + * The comparator will only check the base information: name, enabled, interval. + * The basedir/includes-excludes filters will be ignored. */ ONLY_BASE_INFO,
/** - * The comparator will only check the includes/excludes filters. + * 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_INCLUDES_EXCLUDES, + ONLY_DIRECTORY_SPECIFICATIONS,
/** - * The comparator will check both the includes/excludes filters and + * 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_INCLUDES_EXCLUDES; + BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS; };
private final CompareMode compareMode; @@ -59,7 +59,7 @@ public class DriftConfigurationComparator implements Comparator<DriftConfigurati
@Override public int compare(DriftConfiguration dc1, DriftConfiguration dc2) { - if (compareMode != CompareMode.ONLY_INCLUDES_EXCLUDES) { + if (compareMode != CompareMode.ONLY_DIRECTORY_SPECIFICATIONS) { if (dc1.getName() != null) { if (dc2.getName() != null) { int results = dc1.getName().compareTo(dc2.getName()); @@ -73,16 +73,6 @@ public class DriftConfigurationComparator implements Comparator<DriftConfigurati return -1; // dc1's name is null, but dc2's name is not null, not equal! }
- 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! - } - if (dc1.getInterval() != dc2.getInterval()) { return dc1.getInterval() < dc2.getInterval() ? -1 : 1; } @@ -93,6 +83,16 @@ public class DriftConfigurationComparator implements Comparator<DriftConfigurati }
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); 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 89a61b4..1cf29d6 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 @@ -1,5 +1,12 @@ package org.rhq.core.domain.drift;
+import static java.util.Arrays.asList; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; +import static org.testng.Assert.assertEquals; + import java.util.List;
import org.testng.annotations.Test; @@ -11,13 +18,6 @@ import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext;
-import static java.util.Arrays.asList; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; -import static org.testng.Assert.assertEquals; - public class DriftConfigurationTest { @Test public void getCompareIgnoreIncludesExcludes() { @@ -28,9 +28,6 @@ public class DriftConfigurationTest {
// 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; - dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.fileSystem, "/foo")); - assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; - assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; dc1.setEnabled(true); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; @@ -41,17 +38,12 @@ public class DriftConfigurationTest { 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.fileSystem, "/foo")); dc2.setEnabled(true); dc2.setInterval(1000L); dc2.setName("the-name");
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2;
- dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "/foo")); - assert comparator.compare(dc1, dc2) != 0 : dc1 + " should have different basedir than " + dc2; - - dc1.setBasedir(dc2.getBasedir()); // put them back to the same value dc1.setEnabled(!dc2.isEnabled()); assert comparator.compare(dc1, dc2) < 0 : dc1 + " should have different enabled than " + dc2;
@@ -67,32 +59,33 @@ 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.addInclude(new Filter("ipath1", "ipattern1")); dc2.addInclude(new Filter("ipath2", "ipattern2")); dc1.addExclude(new Filter("epath1", "epattern1")); dc2.addExclude(new Filter("epath2", "epattern2"));
- assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal (ignoring includes/excludes) " + dc2; + 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_INCLUDES_EXCLUDES); - assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal (not ignoring includes/excludes) " + dc2; + comparator = new DriftConfigurationComparator(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( - CompareMode.BOTH_BASE_INFO_AND_INCLUDES_EXCLUDES); + CompareMode.BOTH_BASE_INFO_AND_DIRECTORY_SPECIFICATIONS);
DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); DriftConfiguration dc2 = new DriftConfiguration(new Configuration());
- dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); dc1.setEnabled(true); dc1.setInterval(1000L); dc1.setName("the-name");
- dc2.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); dc2.setEnabled(true); dc2.setInterval(1000L); dc2.setName("the-name"); @@ -102,17 +95,16 @@ public class DriftConfigurationTest {
@Test public void getCompareOnlyIncludesExcludes() { - DriftConfigurationComparator comparator = new DriftConfigurationComparator(CompareMode.ONLY_INCLUDES_EXCLUDES); + DriftConfigurationComparator comparator = new DriftConfigurationComparator( + CompareMode.ONLY_DIRECTORY_SPECIFICATIONS);
DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); DriftConfiguration dc2 = new DriftConfiguration(new Configuration());
- dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.resourceConfiguration, "foo")); dc1.setEnabled(false); dc1.setInterval(1111L); dc1.setName("some-name");
- dc2.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); dc2.setEnabled(true); dc2.setInterval(2222L); dc2.setName("another-name"); @@ -137,6 +129,14 @@ public class DriftConfigurationTest {
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check
+ dc1.setBasedir(new DriftConfiguration.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")); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + dc1.addInclude(new Filter("ipath1", "ipattern1")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; @@ -257,8 +257,7 @@ public class DriftConfigurationTest { DriftConfiguration driftConfig = new DriftConfiguration(config); List<Filter> actual = driftConfig.getIncludes();
- List<Filter> expected = asList(new Filter(path1, pattern1), - new Filter(path2, pattern2)); + List<Filter> expected = asList(new Filter(path1, pattern1), new Filter(path2, pattern2));
assertEquals(actual.size(), 2, "Expected to find two includes filters"); assertEquals(actual, expected, "Failed to get drift configuration includes filters"); @@ -283,8 +282,7 @@ public class DriftConfigurationTest { DriftConfiguration driftConfig = new DriftConfiguration(config); List<Filter> actual = driftConfig.getExcludes();
- List<Filter> expected = asList(new Filter(path1, pattern1), - new Filter(path2, pattern2)); + List<Filter> expected = asList(new Filter(path1, pattern1), new Filter(path2, pattern2));
assertEquals(actual.size(), 2, "Expected to find two excludes filters"); assertEquals(actual, expected, "Failed to get drift configuration excludes filters"); 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 index a8ca1f4..abdc35e 100644 --- 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 @@ -180,19 +180,7 @@ public class DriftConfigurationView extends TableSection<DriftConfigurationDataS driftConfigNames[i] = driftConfigName; }
- 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_deleteConfigs(), caught); - } - }); + deleteDriftConfigurationsByName(driftConfigNames); }
private void deleteAll() { @@ -205,6 +193,10 @@ public class DriftConfigurationView extends TableSection<DriftConfigurationDataS driftConfigNames[i] = driftConfigName; }
+ deleteDriftConfigurationsByName(driftConfigNames); + } + + private void deleteDriftConfigurationsByName(final String[] driftConfigNames) { GWTServiceLookup.getDriftService().deleteDriftConfigurationsByContext(context, driftConfigNames, new AsyncCallback<Integer>() { public void onSuccess(Integer resultCount) { 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 998c142..d603dbb 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 @@ -20,37 +20,27 @@ package org.rhq.enterprise.gui.coregui.client.drift;
import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedHashMap;
-import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; -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.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.grid.CellFormatter; -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.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.components.form.EnumSelectItem; -import org.rhq.enterprise.gui.coregui.client.components.table.AbstractTableAction; import org.rhq.enterprise.gui.coregui.client.components.table.StringIDTableSection; -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.TimestampCellFormatter; import org.rhq.enterprise.gui.coregui.client.components.view.ViewName; -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.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** @@ -170,41 +160,21 @@ public class DriftHistoryView extends StringIDTableSection<DriftDataSource> { }
protected void setupTableInteractions(final boolean hasWriteAccess) { + + /* + * TODO add ack + * TableActionEnablement singleTargetEnablement = hasWriteAccess ? TableActionEnablement.ANY : TableActionEnablement.NEVER;
- addTableAction("DeleteDrift", MSG.common_button_delete(), MSG.view_drift_delete_confirm(), - new AbstractTableAction(singleTargetEnablement) { - public void executeAction(ListGridRecord[] selection, Object actionValue) { - delete(selection); - } - }); - - // TODO add ack - /* addTableAction("AcknowledgeDrift", MSG.common_button_ack(), MSG.view_drift_ack_confirm(), new AbstractTableAction(singleTargetEnablement) { public void executeAction(ListGridRecord[] selection, Object actionValue) { acknowledge(selection); } }); - */ - - addTableAction("DeleteAll", MSG.common_button_delete_all(), MSG.view_drift_delete_confirmAll(), - 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("AcknowledgeAll", MSG.common_button_ack_all(), MSG.iew_alerts_ack_confirm_all(), + addTableAction("AcknowledgeAll", MSG.common_button_ack_all(), MSG.view_drift_ack_confirm_all(), new TableAction() { public boolean isEnabled(ListGridRecord[] selection) { ListGrid grid = getListGrid(); @@ -216,78 +186,51 @@ public class DriftHistoryView extends StringIDTableSection<DriftDataSource> { acknowledgeAll(); } }); + * + * */ }
- private void delete(ListGridRecord[] records) { - final String[] driftIds = new String[records.length]; + /* + * TODO add ack + * + private void acknowledge(ListGridRecord[] records) { + final int[] alertIds = new int[records.length]; for (int i = 0, selectionLength = records.length; i < selectionLength; i++) { ListGridRecord record = records[i]; - String driftId = record.getAttributeAsString(DriftDataSource.ATTR_ID); - driftIds[i] = driftId; + Integer alertId = record.getAttributeAsInt(DriftDataSource.ATTR_ID); + alertIds[i] = alertId; }
- GWTServiceLookup.getDriftService().deleteDrifts(driftIds, new AsyncCallback<Integer>() { + GWTServiceLookup.getDriftService().acknowledgeDrifts(alertIds, new AsyncCallback<Integer>() { public void onSuccess(Integer resultCount) { CoreGUI.getMessageCenter().notify( - new Message(MSG.view_drift_success_delete(String.valueOf(resultCount)), Message.Severity.Info)); + new Message(MSG.view_drift_ack_success(String.valueOf(resultCount)), Message.Severity.Info)); refresh(); }
public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_delete(Arrays.toString(driftIds)), caught); + CoreGUI.getErrorHandler().handleError(MSG.view_drift_ack_failure(Arrays.toString(alertIds)), caught); } }); }
- private void deleteAll() { - GWTServiceLookup.getDriftService().deleteDriftsByContext(context, new AsyncCallback<Integer>() { + private void acknowledgeAll() { + GWTServiceLookup.getDriftService().acknowledgeDriftsByContext(context, new AsyncCallback<Integer>() { public void onSuccess(Integer resultCount) { CoreGUI.getMessageCenter().notify( - new Message(MSG.view_drift_success_delete(String.valueOf(resultCount)), Message.Severity.Info)); + new Message(MSG.view_drift_ack_success(String.valueOf(resultCount)), Message.Severity.Info)); refresh(); }
public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteAll(), caught); + CoreGUI.getErrorHandler().handleError(MSG.view_drift_ack_failure_all(), caught); } }); } - - // private void acknowledge(ListGridRecord[] records) { - // final int[] alertIds = new int[records.length]; - // for (int i = 0, selectionLength = records.length; i < selectionLength; i++) { - // ListGridRecord record = records[i]; - // Integer alertId = record.getAttributeAsInt(DriftDataSource.ATTR_ID); - // alertIds[i] = alertId; - // } - // - // GWTServiceLookup.getAlertService().acknowledgeAlerts(alertIds, new AsyncCallback<Integer>() { - // public void onSuccess(Integer resultCount) { - // CoreGUI.getMessageCenter().notify( - // new Message(MSG.iew_alerts_ack_success(String.valueOf(resultCount)), Message.Severity.Info)); - // refresh(); - // } - // - // public void onFailure(Throwable caught) { - // CoreGUI.getErrorHandler().handleError(MSG.iew_alerts_ack_failure(Arrays.toString(alertIds)), caught); - // } - // }); - // } - - // private void acknowledgeAll() { - // GWTServiceLookup.getAlertService().acknowledgeAlertsByContext(context, new AsyncCallback<Integer>() { - // public void onSuccess(Integer resultCount) { - // CoreGUI.getMessageCenter().notify( - // new Message(MSG.iew_alerts_ack_success(String.valueOf(resultCount)), Message.Severity.Info)); - // refresh(); - // } - // - // public void onFailure(Throwable caught) { - // CoreGUI.getErrorHandler().handleError(MSG.iew_alerts_ack_failure_all(), caught); - // } - // }); - // } + * + * + */
@Override public Canvas getDetailsView(String driftId) { 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 f47a5b9..7b1c880 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 @@ -40,33 +40,6 @@ public interface DriftGWTService extends RemoteService { DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) throws RuntimeException;
/** - * Delete the drifts with the specified ids 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). - * If the user does not have permission for all of the specified drifts, then none of the drifts will be deleted - * and a PermissionException will be thrown. - * - * If any of the ids do not correspond to drift entities that exist, those ids will be gracefully ignored. - * - * @param driftIds the ids of the drifts to be deleted - * @return the number of drifts deleted - * @deprecated - */ - int deleteDrifts(String[] driftIds) throws RuntimeException; - - /** - * Delete all drifts 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). - * If the user does not have permission for all of the specified drifts, then none of the drifts will be deleted - * and a PermissionException will be thrown. - * - * If the entity does not correspond to an existing entity, it will be gracefully ignored. - * - * @param entityContext the context for deletion - * @return the number of drifts deleted - */ - int deleteDriftsByContext(EntityContext entityContext) throws RuntimeException; - - /** * Delete all named drift configurations 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). * 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 c99a475..ca3f30b 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 @@ -43,25 +43,6 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift private DriftManagerLocal driftManager = LookupUtil.getDriftManager();
@Override - @Deprecated - public int deleteDrifts(String[] driftIds) throws RuntimeException { - try { - return this.driftManager.deleteDrifts(getSessionSubject(), driftIds); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public int deleteDriftsByContext(EntityContext entityContext) throws RuntimeException { - try { - return this.driftManager.deleteDriftsByContext(getSessionSubject(), entityContext); - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override public int deleteDriftConfigurationsByContext(EntityContext entityContext, String[] driftConfigNames) throws RuntimeException { try { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages.properties index 01447f3..fa309a2 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 @@ -1129,10 +1129,6 @@ view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. view_drift_changeset_tree_showConfiguration = Show Configuration view_drift_delete_configConfirm = Delete the selected drift configuration(s)? view_drift_delete_configConfirmAll = Delete all drift configurations? -view_drift_delete_confirm = Delete the selected drift(s)? -view_drift_delete_confirmAll = Delete all drifts from this source? -view_drift_failure_delete = Failed to delete drift targets with id''s: {0} -view_drift_failure_deleteAll = Failed to delete all drift targets from this source view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. view_drift_failure_detectNow = Failed to submit drift detection request view_drift_failure_load = Failed to fetch drift data 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 c121055..259e807 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 @@ -947,10 +947,6 @@ view_dashboards_title = Dashboard ##view_drift_changeset_tree_showConfiguration = Show Configuration ##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? ##view_drift_delete_configConfirmAll = Delete all drift configurations? -##view_drift_delete_confirm = Delete the selected drift(s)? -##view_drift_delete_confirmAll = Delete all drifts from this source? -##view_drift_failure_delete = Failed to delete drift targets with id''s: {0} -##view_drift_failure_deleteAll = Failed to delete all drift targets from this source ##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. ##view_drift_failure_detectNow = Failed to submit drift detection request ##view_drift_failure_load = Failed to fetch drift data 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 eb07683..4068998 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 @@ -1145,10 +1145,6 @@ view_dashboards_title = Dashboard ##view_drift_category_fileRemoved = Arquivo removido ##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? ##view_drift_delete_configConfirmAll = Delete all drift configurations? -##view_drift_delete_confirm = Excluir drift(s) selecionado(s)? -##view_drift_delete_confirmAll = Excluir todos os drifts desta origem? -##view_drift_failure_delete = Falha ao excluir os alvos dos drifts com ids: {0} -##view_drift_failure_deleteAll = Falha ao excluir todos os alvos dos drifts desta origem ##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. ##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 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 5daa885..69cd6d5 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 @@ -23,12 +23,10 @@ import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
import java.io.File; import java.io.InputStream; -import java.util.List;
import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; -import javax.ejb.TransactionAttributeType; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.MessageProducer; @@ -49,7 +47,6 @@ 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.JPADriftCriteria; import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.drift.DriftChangeSet; import org.rhq.core.domain.drift.DriftComposite; @@ -58,7 +55,6 @@ import org.rhq.core.domain.drift.DriftConfigurationComparator; import org.rhq.core.domain.drift.DriftConfigurationDefinition; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; -import org.rhq.core.domain.drift.JPADrift; import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; @@ -115,9 +111,6 @@ public class DriftManagerBean implements DriftManagerLocal { private AgentManagerLocal agentManager;
@EJB - private DriftManagerLocal driftManager; - - @EJB private SubjectManagerLocal subjectManager;
// use a new transaction when putting things on the JMS queue. see @@ -185,67 +178,6 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override - @Deprecated - public int deleteDrifts(Subject subject, String[] driftIds) { - // avoid big transactions by doing this one at a time. if this is too slow we can chunk in bigger increments. - int result = 0; - - for (String driftId : driftIds) { - result += driftManager.deleteDriftsInNewTransaction(subject, driftId); - } - - return result; - } - - @Override - @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) - public int deleteDriftsInNewTransaction(Subject subject, String... driftIds) { - int result = 0; - - for (String driftId : driftIds) { - Drift<?, ?> doomed = entityManager.find(JPADrift.class, driftId); - if (null != doomed) { - entityManager.remove(doomed); - ++result; - } - } - - return result; - } - - @Override - public int deleteDriftsByContext(Subject subject, EntityContext entityContext) throws RuntimeException { - int result = 0; - JPADriftCriteria criteria = new JPADriftCriteria(); - - switch (entityContext.getType()) { - case Resource: - criteria.addFilterResourceIds(entityContext.getResourceId()); - break; - - case SubsystemView: - // delete them all - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); - } - - List<? extends Drift<?, ?>> drifts = driftManager.findDriftsByCriteria(subject, criteria); - if (!drifts.isEmpty()) { - String[] driftIds = new String[drifts.size()]; - int i = 0; - for (Drift<?, ?> drift : drifts) { - driftIds[i++] = drift.getId(); - } - - result = driftManager.deleteDrifts(subject, driftIds); - } - - return result; - } - - @Override public void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName) {
// TODO security check! @@ -267,19 +199,21 @@ public class DriftManagerBean implements DriftManagerLocal { }
if (doomedDriftConfig != null) { - resource.getDriftConfigurations().remove(doomedDriftConfig); - doomedDriftConfig.setResource(null); - resource = entityManager.merge(resource); - entityManager.flush(); - entityManager.clear(); // clear the hibernate cache - we're about to call some agent API and we don't want it messing with attached objects - + // tell the agent first - we don't want the agent reporting on the drift config after we delete it try { AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService(); - service.unscheduleDriftDetection(resourceId, doomedDriftConfig); + // make a copy of the config, so we don't mess with the attached original + // note that we don't copy over the resource reference, that's also attached but we don't need it in the copy anyway + DriftConfiguration copy = new DriftConfiguration(doomedDriftConfig.getConfiguration().clone()); + service.unscheduleDriftDetection(resourceId, copy); } catch (Exception e) { log.warn(" Unable to inform agent of unscheduled drift detection [" + doomedDriftConfig + "]", e); } + + resource.getDriftConfigurations().remove(doomedDriftConfig); + doomedDriftConfig.setResource(null); + resource = entityManager.merge(resource); } break;
@@ -377,7 +311,7 @@ public class DriftManagerBean implements DriftManagerLocal {
// Update or add the driftConfig as necessary DriftConfigurationComparator comparator = new DriftConfigurationComparator( - CompareMode.ONLY_INCLUDES_EXCLUDES); + CompareMode.ONLY_DIRECTORY_SPECIFICATIONS); boolean isUpdated = false; for (DriftConfiguration dc : resource.getDriftConfigurations()) { if (dc.getName().equals(driftConfig.getName())) { 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 725c964..eddd4c3 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 @@ -56,43 +56,6 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR */ void addFiles(int resourceId, long zipSize, InputStream zipStream) throws Exception;
- //TODO Should probably move to DriftServerPluginFacet - /** - * Remove the specified drifts. Ids not identifying an actual drift record will be ignored. - * - * @param subject - * @param - * @param driftConfig - * - * @return the number of Drift records deleted - * @deprecated this will be removed, we will only support deleting changesets in the future - */ - int deleteDrifts(Subject subject, String[] driftIds); - - //TODO Should probably move to JPADriftServerLocal when deleteDrifts graduates to server plugin facet - /** - * Remove the specified drift in its own transaction. This is used for chunking transactions and - * should not be exposed in a Remote interface. - * - * @param subject - * @param - * @param driftConfig - * - * @return the number of Drift records deleted - */ - int deleteDriftsInNewTransaction(Subject subject, String... driftIds); - - //TODO Should probably move to DriftServerPluginFacet - /** - * Remove all drifts on the specified entity context. - * - * @param subject - * @param entityContext the context - * - * @return the number of Drift records deleted - */ - int deleteDriftsByContext(Subject subject, EntityContext entityContext); - /** * Remove the provided driftConfig (identified by name) on the specified entityContext. * Agents, if available, will be notified of the change.
commit 714aee9feeffc2908c925a129dd32a10bbcf7fd5 Author: John Sanda jsanda@redhat.com Date: Fri Aug 12 13:05:25 2011 -0400
Moving Filter back to core/domain
The Filter class has to be accessible to coregui and classes in core/util are not accessible to coregui.
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 f15a03b..572bb10 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 @@ -42,7 +42,7 @@ import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.domain.drift.DriftConfigurationDefinition; import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory; -import org.rhq.core.util.file.Filter; +import org.rhq.core.domain.drift.Filter; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.resource.ResourceType;
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 701a4bd..d928c6c 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 @@ -18,8 +18,6 @@ */ package org.rhq.core.domain.drift;
-import static java.util.Collections.emptyList; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -44,7 +42,8 @@ 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.resource.Resource; -import org.rhq.core.util.file.Filter; + +import static java.util.Collections.emptyList;
/** * This is a convienence wrapper around a Configuration object whose schema is that @@ -55,8 +54,6 @@ import org.rhq.core.util.file.Filter; * * This object also has an optional relationship with a Resource. * - * TODO: this is missing setters for includes/excludes filters. We should add those. - * * @author John Sanda * @author John Mazzitelli * @author Jay Shaughnessy 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 index a081157..406bdd0 100644 --- 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 @@ -1,24 +1,20 @@ /* * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. + * 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, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. + * 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 and the GNU Lesser General Public License - * for more details. + * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * 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; @@ -26,8 +22,6 @@ package org.rhq.core.domain.drift; import java.util.Comparator; import java.util.List;
-import org.rhq.core.domain.drift.DriftConfiguration.Filter; - /** * Compares two {@link DriftConfiguration} objects. The comparison can either * compare includes/excludes filters or ignore them. Will also compare diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Filter.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Filter.java new file mode 100644 index 0000000..9ecea57 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Filter.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.drift; + +import java.io.Serializable; + +public class Filter implements Serializable { + private static final long serialVersionUID = 1L; + + private String path; + private String pattern; + + public Filter(String path, String pattern) { + setPath(path); + setPattern(pattern); + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + if (path == null) { + this.path = ""; + } else { + this.path = path; + } + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + if (pattern == null) { + this.pattern = ""; + } else { + this.pattern = pattern; + } + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (obj instanceof Filter) { + Filter that = (Filter) obj; + return this.path.equals(that.path) && this.pattern.equals(that.pattern); + } + + return false; + } + + @Override + public int hashCode() { + int result = 1; + result = 31 * result + path.hashCode(); + result = 31 * result + pattern.hashCode(); + return result; + } + + @Override + public String toString() { + return "Filter[path: " + path + ", pattern: " + pattern + "]"; + } +} 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 19a477a..89a61b4 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 @@ -1,12 +1,5 @@ package org.rhq.core.domain.drift;
-import static java.util.Arrays.asList; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; -import static org.testng.Assert.assertEquals; - import java.util.List;
import org.testng.annotations.Test; @@ -17,7 +10,13 @@ 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.DriftConfigurationDefinition.BaseDirValueContext; -import org.rhq.core.util.file.Filter; + +import static java.util.Arrays.asList; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; +import static org.testng.Assert.assertEquals;
public class DriftConfigurationTest { @Test @@ -68,10 +67,10 @@ 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.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); - dc2.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); - dc1.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); - dc2.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + dc1.addInclude(new Filter("ipath1", "ipattern1")); + dc2.addInclude(new Filter("ipath2", "ipattern2")); + dc1.addExclude(new Filter("epath1", "epattern1")); + dc2.addExclude(new Filter("epath2", "epattern2"));
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal (ignoring includes/excludes) " + dc2;
@@ -138,55 +137,55 @@ public class DriftConfigurationTest {
assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check
- dc1.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); + dc1.addInclude(new Filter("ipath1", "ipattern1")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
- dc2.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); + dc2.addInclude(new Filter("ipath1", "ipattern1")); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1;
// add a second include to see that we test multiple filters - dc1.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); + dc1.addInclude(new Filter("ipath2", "ipattern2")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
- dc2.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); + dc2.addInclude(new Filter("ipath2", "ipattern2")); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1;
// side test just to see null patterns work - dc1.addInclude(new DriftConfiguration.Filter("ipath3", null)); + dc1.addInclude(new Filter("ipath3", null)); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
- dc2.addInclude(new DriftConfiguration.Filter("ipath3", null)); + dc2.addInclude(new Filter("ipath3", null)); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1;
// now test excludes
- dc1.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); + dc1.addExclude(new Filter("epath1", "epattern1")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
- dc2.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); + dc2.addExclude(new Filter("epath1", "epattern1")); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1;
// add a second exclude to see that we test multiple filters - dc1.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + dc1.addExclude(new Filter("epath2", "epattern2")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
- dc2.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + dc2.addExclude(new Filter("epath2", "epattern2")); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1;
// now test that we have the same number of filters but they differ
- dc1.addInclude(new DriftConfiguration.Filter("ipathA", "ipatternA")); - dc2.addInclude(new DriftConfiguration.Filter("ipathZ", "ipatternZ")); + dc1.addInclude(new Filter("ipathA", "ipatternA")); + dc2.addInclude(new Filter("ipathZ", "ipatternZ")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1;
@@ -194,8 +193,8 @@ public class DriftConfigurationTest { dc1 = new DriftConfiguration(new Configuration()); dc2 = new DriftConfiguration(new Configuration()); assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check - dc1.addExclude(new DriftConfiguration.Filter("epathA", "epatternA")); - dc2.addExclude(new DriftConfiguration.Filter("epathZ", "epatternZ")); + dc1.addExclude(new Filter("epathA", "epatternA")); + dc2.addExclude(new Filter("epathZ", "epatternZ")); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java index 8fc8e6b..88c1868 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -22,8 +22,8 @@ package org.rhq.core.pc.drift; import java.io.File; import java.util.List;
+import org.rhq.core.domain.drift.Filter; import org.rhq.core.util.file.FileVisitor; -import org.rhq.core.util.file.Filter;
public class FilterFileVisitor implements FileVisitor {
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java index 42d53be..f0fc34b 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java @@ -19,67 +19,22 @@
package org.rhq.core.util.file;
-import java.io.Serializable; - -public class Filter implements Serializable { - private static final long serialVersionUID = 1L; +public class Filter {
private String path; + private String pattern;
public Filter(String path, String pattern) { - setPath(path); - setPattern(pattern); + this.path = path; + this.pattern = pattern; }
public String getPath() { return path; }
- public void setPath(String path) { - if (path == null) { - this.path = ""; - } else { - this.path = path; - } - } - public String getPattern() { return pattern; } - - public void setPattern(String pattern) { - if (pattern == null) { - this.pattern = ""; - } else { - this.pattern = pattern; - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (obj instanceof Filter) { - Filter that = (Filter) obj; - return this.path.equals(that.path) && this.pattern.equals(that.pattern); - } - - return false; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + path.hashCode(); - result = 31 * result + pattern.hashCode(); - return result; - } - - @Override - public String toString() { - return "Filter[path: " + path + ", pattern: " + pattern + "]"; - } } 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 1e959f4..511df03 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 @@ -32,7 +32,7 @@ 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.DriftConfigurationDefinition; -import org.rhq.core.util.file.Filter; +import org.rhq.core.domain.drift.Filter; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.InventoryStatus;
commit 3cd5c6db90e1d011dbc80de62372f19811287ed2 Author: John Sanda jsanda@redhat.com Date: Fri Aug 12 12:14:01 2011 -0400
Adding back methods that were lost during merge conflict
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java index 17368bd..42d53be 100644 --- a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java @@ -72,7 +72,10 @@ public class Filter implements Serializable {
@Override public int hashCode() { - return 13 * (path.hashCode() + pattern.hashCode()); + int result = 1; + result = 31 * result + path.hashCode(); + result = 31 * result + pattern.hashCode(); + return result; }
@Override
commit 1da2f21b4ec8bed20e003fd3ca3dc13d2b929bdb Author: John Sanda jsanda@redhat.com Date: Fri Aug 12 11:57:46 2011 -0400
Another class was updated as a result of making DriftConfiguration.Filter top level
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 4df42fb..f15a03b 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 @@ -42,7 +42,7 @@ import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.domain.drift.DriftConfigurationDefinition; import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory; -import org.rhq.core.domain.drift.DriftConfiguration.Filter; +import org.rhq.core.util.file.Filter; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.resource.ResourceType;
@@ -651,7 +651,7 @@ public class PluginMetadataParserTest { assertNotNull(includes, "Expected to find default property set for <includes>"); assertEquals(includes.size(), 2, "Expected <includes> property list to have two property elements.");
- DriftConfiguration.Filter include1 = includes.get(0); + Filter include1 = includes.get(0); String path1 = include1.getPath(); String pattern1 = include1.getPattern();
@@ -661,7 +661,7 @@ public class PluginMetadataParserTest { assertNotNull(pattern1, "Expected to find a simple property for the pattern of the first <include>"); assertEquals(pattern1, "*.ijar", "The value is wrong for the pattern of the first <include>");
- DriftConfiguration.Filter include2 = includes.get(1); + Filter include2 = includes.get(1); String path2 = include2.getPath(); String pattern2 = include2.getPattern();
@@ -691,7 +691,7 @@ public class PluginMetadataParserTest { assertNotNull(excludes, "Expected to find default property set for <excludes>"); assertEquals(excludes.size(), 2, "Expected <excludes> property list to have two property elements.");
- DriftConfiguration.Filter exclude1 = excludes.get(0); + Filter exclude1 = excludes.get(0); String path1 = exclude1.getPath(); String pattern1 = exclude1.getPattern();
@@ -701,7 +701,7 @@ public class PluginMetadataParserTest { assertNotNull(pattern1, "Expected to find a simple property for the pattern of the first <exclude>"); assertEquals(pattern1, "*.ejar", "The value is wrong for the pattern of the first <exclude>");
- DriftConfiguration.Filter exclude2 = excludes.get(1); + Filter exclude2 = excludes.get(1); String path2 = exclude2.getPath(); String pattern2 = exclude2.getPattern();
@@ -728,7 +728,7 @@ public class PluginMetadataParserTest { assertNotNull(includes, "Expected to find default property set for <includes>"); assertEquals(includes.size(), 2, "Expected <includes> property list to have two property elements.");
- DriftConfiguration.Filter include1 = includes.get(0); + Filter include1 = includes.get(0); String path1 = include1.getPath(); String pattern1 = include1.getPattern();
@@ -738,7 +738,7 @@ public class PluginMetadataParserTest { assertNotNull(pattern1, "Expected to find a simple property for the pattern of the first <include>"); assertEquals(pattern1, "*.ijar", "The value is wrong for the pattern of the first <include>");
- DriftConfiguration.Filter include2 = includes.get(1); + Filter include2 = includes.get(1); String path2 = include2.getPath(); String pattern2 = include2.getPattern();
@@ -753,7 +753,7 @@ public class PluginMetadataParserTest { assertNotNull(excludes, "Expected to find default property set for <excludes>"); assertEquals(excludes.size(), 2, "Expected <excludes> property list to have two property elements.");
- DriftConfiguration.Filter exclude1 = excludes.get(0); + Filter exclude1 = excludes.get(0); path1 = exclude1.getPath(); pattern1 = exclude1.getPattern();
@@ -763,7 +763,7 @@ public class PluginMetadataParserTest { assertNotNull(pattern1, "Expected to find a simple property for the pattern of the first <exclude>"); assertEquals(pattern1, "*.ejar", "The value is wrong for the pattern of the first <exclude>");
- DriftConfiguration.Filter exclude2 = excludes.get(1); + Filter exclude2 = excludes.get(1); path2 = exclude2.getPath(); pattern2 = exclude2.getPattern();
commit 70f23b2f04d446a56f212f34f6bfacfb101faca9 Author: John Sanda jsanda@redhat.com Date: Fri Aug 12 11:55:17 2011 -0400
starting to add support for filtering during drift detection
This commit adds the filtering login in FileUtil. I put it there because it is general purpose code that could be used in placed other than drift code. As part of that I pulled the Filter class out of DriftConfiguration and moved it into core/util for use with the filtering.
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 4f92e3b..701a4bd 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 @@ -44,6 +44,7 @@ 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.resource.Resource; +import org.rhq.core.util.file.Filter;
/** * This is a convienence wrapper around a Configuration object whose schema is that @@ -54,6 +55,8 @@ import org.rhq.core.domain.resource.Resource; * * This object also has an optional relationship with a Resource. * + * TODO: this is missing setters for includes/excludes filters. We should add those. + * * @author John Sanda * @author John Mazzitelli * @author Jay Shaughnessy @@ -258,69 +261,6 @@ public class DriftConfiguration implements Serializable { } }
- public static class Filter implements Serializable { - private static final long serialVersionUID = 1L; - - private String path; - private String pattern; - - public Filter(String path, String pattern) { - setPath(path); - setPattern(pattern); - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - if (path == null) { - this.path = ""; - } else { - this.path = path; - } - } - - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - if (pattern == null) { - this.pattern = ""; - } else { - this.pattern = pattern; - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (obj instanceof Filter) { - Filter that = (Filter) obj; - return this.path.equals(that.path) && this.pattern.equals(that.pattern); - } - - return false; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + path.hashCode(); - result = 31 * result + pattern.hashCode(); - return result; - } - - @Override - public String toString() { - return "Filter[path: " + path + ", pattern: " + pattern + "]"; - } - } - private String getNameProperty() { return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME, null); } 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 c4f2857..19a477a 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 @@ -17,6 +17,7 @@ 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.DriftConfigurationDefinition.BaseDirValueContext; +import org.rhq.core.util.file.Filter;
public class DriftConfigurationTest { @Test @@ -255,10 +256,10 @@ public class DriftConfigurationTest { config.put(includes);
DriftConfiguration driftConfig = new DriftConfiguration(config); - List<DriftConfiguration.Filter> actual = driftConfig.getIncludes(); + List<Filter> actual = driftConfig.getIncludes();
- List<DriftConfiguration.Filter> expected = asList(new DriftConfiguration.Filter(path1, pattern1), - new DriftConfiguration.Filter(path2, pattern2)); + List<Filter> expected = asList(new Filter(path1, pattern1), + new Filter(path2, pattern2));
assertEquals(actual.size(), 2, "Expected to find two includes filters"); assertEquals(actual, expected, "Failed to get drift configuration includes filters"); @@ -281,10 +282,10 @@ public class DriftConfigurationTest { config.put(excludes);
DriftConfiguration driftConfig = new DriftConfiguration(config); - List<DriftConfiguration.Filter> actual = driftConfig.getExcludes(); + List<Filter> actual = driftConfig.getExcludes();
- List<DriftConfiguration.Filter> expected = asList(new DriftConfiguration.Filter(path1, pattern1), - new DriftConfiguration.Filter(path2, pattern2)); + List<Filter> expected = asList(new Filter(path1, pattern1), + new Filter(path2, pattern2));
assertEquals(actual.size(), 2, "Expected to find two excludes filters"); assertEquals(actual, expected, "Failed to get drift configuration excludes filters"); diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java new file mode 100644 index 0000000..8fc8e6b --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/FilterFileVisitor.java @@ -0,0 +1,39 @@ +/* + * 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.pc.drift; + +import java.io.File; +import java.util.List; + +import org.rhq.core.util.file.FileVisitor; +import org.rhq.core.util.file.Filter; + +public class FilterFileVisitor implements FileVisitor { + + private FileVisitor visitor; + + public FilterFileVisitor(List<Filter> includes, List<Filter> excludes, FileVisitor visitor) { + this.visitor = visitor; + } + + @Override + public void visit(File file) { + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java new file mode 100644 index 0000000..e9b7918 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/FilterFileVisitorTest.java @@ -0,0 +1,48 @@ +/* + * 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.pc.drift; + +import java.io.File; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.apache.commons.io.FileUtils.deleteDirectory; +import static org.apache.commons.io.FileUtils.toFile; + +public class FilterFileVisitorTest { + + File basedir; + + @BeforeMethod + public void setUp() throws Exception { + File root = toFile(getClass().getResource(".")); + basedir = new File(root, "basedir"); + deleteDirectory(basedir); + basedir.mkdirs(); + } + + @Test + public void callVisitorWhenFileMatchesIncludeFilter() { +// touch(new ); +// List<Filter> includes = asList(new Filter("")); + } + +} 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 be7310f..5776424 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 @@ -315,8 +315,7 @@ public class FileUtil { /** * Ensure that the path uses only forward slash * Like java.io.File(String,String) but just - * @param dir - * @param fileName + * @param path * @return */ public static String useForwardSlash(String path) { @@ -348,4 +347,61 @@ public class FileUtil { } }
+ public static Pattern generateRegex(List<Filter> filters) { + boolean first = true; + StringBuilder regex = new StringBuilder(); + for (Filter filter : filters) { + if (!first) { + regex.append("|"); + } else { + first = false; + } + regex.append("("); + File path = new File(filter.getPath()); + + if (isEmpty(filter.getPattern()) && path.isDirectory()) { + regex.append(".*"); + } else if (isEmpty(filter.getPattern()) && !path.isDirectory()) { + buildPatternRegex(path.getAbsolutePath(), regex); + } else if (!isEmpty(filter.getPattern())) { + // note that this case assumes path is a directory. We probably + // need another if else block for when there is a pattern and + // path is not a directory. + regex.append(path).append("/").append("("); + buildPatternRegex(filter.getPattern(), regex); + regex.append(")"); + } + regex.append(")"); + } + return Pattern.compile(regex.toString()); + } + + private static void buildPatternRegex(String pattern, StringBuilder regex) { + for (int i = 0; i < pattern.length(); i++) { + char c = pattern.charAt(i); + if (c == '?') { + regex.append('.'); + } else if (c == '*') { + if (i + 1 < pattern.length()) { + char c2 = pattern.charAt(i + 1); + if (c2 == '*') { + regex.append(".*"); + i += 2; + continue; + } + } + regex.append("[^/]*"); + } else if (c == '.') { + regex.append("\."); + } else { + regex.append(c); + } + // TODO: Escape backslashes. + } + } + + private static boolean isEmpty(String s) { + return s == null || s.length() == 0; + } + } \ No newline at end of file diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java new file mode 100644 index 0000000..17368bd --- /dev/null +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/Filter.java @@ -0,0 +1,82 @@ +/* + * 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.util.file; + +import java.io.Serializable; + +public class Filter implements Serializable { + private static final long serialVersionUID = 1L; + + private String path; + private String pattern; + + public Filter(String path, String pattern) { + setPath(path); + setPattern(pattern); + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + if (path == null) { + this.path = ""; + } else { + this.path = path; + } + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + if (pattern == null) { + this.pattern = ""; + } else { + this.pattern = pattern; + } + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + + if (obj instanceof Filter) { + Filter that = (Filter) obj; + return this.path.equals(that.path) && this.pattern.equals(that.pattern); + } + + return false; + } + + @Override + public int hashCode() { + return 13 * (path.hashCode() + pattern.hashCode()); + } + + @Override + public String toString() { + return "Filter[path: " + path + ", pattern: " + pattern + "]"; + } +} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java index cd53a06..125ead8 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java @@ -25,6 +25,7 @@ package org.rhq.core.util.file; import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.regex.Pattern;
import org.testng.annotations.Test;
@@ -213,4 +214,64 @@ public class FileUtilTest { "Expected to visit files in nested sub directories"); }
+ public void testGetPattern() { + Pattern regex; + + regex = assertPatternsRegex("(/basedir/easy\.txt)|(/basedir/test\.txt)", + new Filter("/basedir/easy.txt", null), new Filter("/basedir/test.txt", null)); + + assert regex.matcher("/basedir/easy.txt").matches(); + assert regex.matcher("/basedir/test.txt").matches(); + assert !regex.matcher("/basedir/easyXtxt").matches(); + assert !regex.matcher("/basedir/testXtxt").matches(); + assert !regex.matcher("/basedir/easy.txtX").matches(); + assert !regex.matcher("/basedir/test.txtX").matches(); + assert !regex.matcher("/basedirX/easy.txt").matches(); + assert !regex.matcher("/basedirX/test.txt").matches(); + assert !regex.matcher("easy.txt").matches() : "missing basedir"; + assert !regex.matcher("test.txt").matches() : "missing basedir"; + + regex = assertPatternsRegex("(/basedir/([^/]*\.txt))", new Filter("/basedir", "*.txt")); + + assert regex.matcher("/basedir/foo.txt").matches(); + assert regex.matcher("/basedir/file with spaces.txt").matches(); + assert regex.matcher("/basedir/123.txt").matches(); + assert !regex.matcher("/basedir/subdir/foo.txt").matches(); + assert !regex.matcher("/basedir/foo.txt.swp").matches(); + + regex = assertPatternsRegex("(/var/lib/([^/]*\.war))|(/var/lib/([^/]*\.ear))", + new Filter("/var/lib", "*.war"), new Filter("/var/lib", "*.ear")); + + assert regex.matcher("/var/lib/myapp.war").matches(); + assert regex.matcher("/var/lib/myapp.ear").matches(); + assert regex.matcher("/var/lib/my-app.war").matches(); + assert !regex.matcher("/var/lib/myapp.War").matches(); + assert !regex.matcher("/var/libs/myapp.war").matches(); + assert !regex.matcher("myapp.ear").matches(); + assert !regex.matcher("/var/lib/myapp.ear.rej").matches(); + + regex = assertPatternsRegex("(/conf/(server-.\.conf))", new Filter("/conf", "server-?.conf")); + + assert regex.matcher("/conf/server-1.conf").matches(); + assert regex.matcher("/conf/server-X.conf").matches(); + assert !regex.matcher("/conf/subconf/server-1.conf").matches(); + assert !regex.matcher("/conf/server.conf").matches(); + + regex = assertPatternsRegex("(/etc/(.*[^/]*\.conf))", new Filter("/etc", "**/*.conf")); + + assert regex.matcher("/etc/yum.conf").matches(); + assert regex.matcher("/etc/httpd/httpd.conf").matches(); + assert !regex.matcher("/etc/foo.conf/foo").matches(); + } + + private Pattern assertPatternsRegex(String expectedPattern, Filter... filters) { + Pattern regex = FileUtil.generateRegex(asList(filters)); + + assert regex != null : "The regex was not able to be produced - it was null"; + assert expectedPattern.equals(regex.pattern()) : "The expected pattern [" + expectedPattern + + "] did not match the actual pattern [" + regex.pattern() + "]"; + + return regex; + } + } 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 066bd8c..1e959f4 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 @@ -32,7 +32,7 @@ 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.DriftConfigurationDefinition; -import org.rhq.core.domain.drift.DriftConfiguration.Filter; +import org.rhq.core.util.file.Filter; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.operation.OperationDefinition; import org.rhq.core.domain.resource.InventoryStatus;
commit bf35e3cc8a175f82c642c95e3ef40bef1432dd45 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 12 18:03:50 2011 +0200
The metric template importer now correctly enables/disables and sets the configured intervals on the templates and underlying schedules.
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 03cd4bb..6a1ff73 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 @@ -342,6 +342,14 @@ public class MeasurementScheduleManagerBean implements MeasurementScheduleManage updateExistingSchedules); }
+ @RequiredPermission(Permission.MANAGE_SETTINGS) + public void updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(Subject subject, + int[] measurementDefinitionIds, long collectionInterval, boolean enable, boolean updateExistingSchedules) { + + modifyDefaultCollectionIntervalForMeasurementDefinitions(subject, measurementDefinitionIds, enable, + collectionInterval, updateExistingSchedules); + } + /** * Updates the default enablement and/or collection intervals (i.e. metric templates) for the given measurement * definitions. If updateExistingSchedules is true, the schedules for the corresponding metrics or all inventoried 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 0a545ab..9edf221 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 @@ -155,6 +155,20 @@ public interface MeasurementScheduleManagerLocal { long collectionInterval, boolean updateExistingSchedules);
/** + * Using this method one can both update the default collection interval AND enable or disable the + * measurement definitions. This method is therefore preferable if you need to do both these things + * in 1 go. + * + * @param subject the current user + * @param measurementDefinitionIds the ids of measurement definitions to update + * @param collectionInterval the default collection interval to set + * @param enable whether to enable or disable the measurement definition + * @param updateExistingSchedules whether to accordingly update the existing schedules + */ + void updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(Subject subject, int[] measurementDefinitionIds, + long collectionInterval, boolean enable, boolean updateExistingSchedules); + + /** * Enables all collection schedules attached to the given auto group whose schedules are based off the given * definitions. This does not enable the "templates" (aka definitions). If the passed group does not exist an * Exception is thrown. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index eddd052..1445ba9 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -71,18 +71,20 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M public static final String METRIC_UPDATE_OVERRIDES_PROPERTY = "metricUpdateOverrides"; public static final String METRIC_UPDATE_OVERRIDE_PROPERTY = "metricUpdateOverride";
- private static class CollectionIntervalAndUpdateSchedules { + private static class UpdateKey { public final long collectionInterval; public final boolean updateSchedules; + public final boolean enable;
- public CollectionIntervalAndUpdateSchedules(long collectionInterval, boolean updateSchedules) { + public UpdateKey(long collectionInterval, boolean updateSchedules, boolean enable) { this.collectionInterval = collectionInterval; this.updateSchedules = updateSchedules; + this.enable = enable; }
@Override public int hashCode() { - return (int) collectionInterval * (updateSchedules ? 31 : 1); + return (int) collectionInterval * (updateSchedules ? 31 : 1) * (enable ? 31 : 1); }
@Override @@ -91,22 +93,21 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M return true; }
- if (!(other instanceof CollectionIntervalAndUpdateSchedules)) { + if (!(other instanceof UpdateKey)) { return false; }
- CollectionIntervalAndUpdateSchedules o = (CollectionIntervalAndUpdateSchedules) other; + UpdateKey o = (UpdateKey) other;
- return o.collectionInterval == collectionInterval && o.updateSchedules == updateSchedules; + return o.collectionInterval == collectionInterval && o.updateSchedules == updateSchedules + && enable == o.enable; } }
private Subject subject; private EntityManager entityManager; - private List<MeasurementDefinition> definitionsToEnable = new ArrayList<MeasurementDefinition>(); - private List<MeasurementDefinition> definitionsToDisable = new ArrayList<MeasurementDefinition>(); - private Map<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> definitionsByCollectionIntervalAndUpdateSchedules = - new HashMap<MetricTemplateImporter.CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>>(); + private Map<UpdateKey, List<MeasurementDefinition>> definitionsByUpdateKey = + new HashMap<UpdateKey, List<MeasurementDefinition>>(); private Configuration importConfiguration; private Unmarshaller unmarshaller; private MeasurementScheduleManagerLocal measurementScheduleManager; @@ -215,13 +216,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M return; }
- if (exportedEntity.isEnabled()) { - definitionsToEnable.add(entity); - } else { - definitionsToDisable.add(entity); - } - - addToCollectionIntervalMap(exportedEntity, entity); + addToUpdateMap(exportedEntity, entity); }
@Override @@ -235,13 +230,14 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
@Override public void finishImport() { - measurementScheduleManager.enableMeasurementTemplates(subject, getIdsFromDefs(definitionsToEnable)); - measurementScheduleManager.disableMeasurementTemplates(subject, getIdsFromDefs(definitionsToDisable)); - - for (Map.Entry<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> e : definitionsByCollectionIntervalAndUpdateSchedules - .entrySet()) { - measurementScheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(subject, - getIdsFromDefs(e.getValue()), e.getKey().collectionInterval, e.getKey().updateSchedules); + for (Map.Entry<UpdateKey, List<MeasurementDefinition>> e : definitionsByUpdateKey.entrySet()) { + int[] ids = getIdsFromDefs(e.getValue()); + boolean enable = e.getKey().enable; + boolean updateSchedules = e.getKey().updateSchedules; + long collectionInterval = e.getKey().collectionInterval; + + measurementScheduleManager.updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(subject, + ids, collectionInterval, enable, updateSchedules); } }
@@ -256,16 +252,13 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M return ids; }
- private void addToCollectionIntervalMap(MetricTemplate metricTemplate, MeasurementDefinition def) { - CollectionIntervalAndUpdateSchedules key = - new CollectionIntervalAndUpdateSchedules(metricTemplate.getDefaultInterval(), - shouldUpdateSchedules(metricTemplate)); - - List<MeasurementDefinition> defs = definitionsByCollectionIntervalAndUpdateSchedules.get(key); + private void addToUpdateMap(MetricTemplate metricTemplate, MeasurementDefinition def) { + UpdateKey key = new UpdateKey(metricTemplate.getDefaultInterval(), shouldUpdateSchedules(metricTemplate), metricTemplate.isEnabled());
+ List<MeasurementDefinition> defs = definitionsByUpdateKey.get(key); if (defs == null) { defs = new ArrayList<MeasurementDefinition>(); - definitionsByCollectionIntervalAndUpdateSchedules.put(key, defs); + definitionsByUpdateKey.put(key, defs); }
defs.add(def); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java index e792c0e..819a5d9 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java @@ -149,10 +149,8 @@ public class MetricTemplateImporterTest extends JMockTest {
//this is what we expect the measurement schedule manager msm to be //called with when the importer finishes its work. - one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); - one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 1 }), with(1000L), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true), with(false)); } });
@@ -209,12 +207,10 @@ public class MetricTemplateImporterTest extends JMockTest {
//this is what we expect the measurement schedule manager msm to be //called with when the importer finishes its work. - one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); - one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 2 })); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 1 }), with(1000L), with(false)); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 2 }), with(2000L), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(false), with(false)); } });
@@ -260,10 +256,8 @@ public class MetricTemplateImporterTest extends JMockTest {
MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager();
- one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); - one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 1 }), with(1000L), with(true)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true), with(true)); } });
@@ -310,12 +304,10 @@ public class MetricTemplateImporterTest extends JMockTest {
MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager();
- one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1, 2 })); - one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 1 }), with(1000L), with(true)); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 2 }), with(2000L), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true), with(true)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(true), with(false)); } });
@@ -397,12 +389,10 @@ public class MetricTemplateImporterTest extends JMockTest {
MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager();
- one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); - one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 2 })); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 1 }), with(1000L), with(false)); - one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), - with(new int[] { 2 }), with(2000L), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true), with(false)); + one(msm).updateDefaultCollectionIntervalAndEnablementForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(false), with(false)); } });
commit dac66dc7534367e02d86467369e9e5216570ced0 Author: Heiko W. Rupp hwr@redhat.com Date: Fri Aug 12 17:35:17 2011 +0200
BZ 729938 - If reload returns "connection refused", treat as success, as7 sometimes closes the connection before sending a result. Add a result of "Success" if it is a success.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java index 328ec3c..581c4e1 100644 --- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java +++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java @@ -137,18 +137,23 @@ public class BaseServerComponent extends BaseComponent { */ protected OperationResult postProcessResult(String name, Result res) { OperationResult operationResult = new OperationResult(); - if (name.equals("shutdown")) { + if (name.equals("shutdown") || name.equals("reload")) { /* * Shutdown needs a special treatment, because after sending the operation, if shutdown suceeds, * the server connection is closed and we can't read from it. So if we get connection refused for * reading, this is a good sign. */ if (!res.isSuccess()) { - if (res.getThrowable()!=null && (res.getThrowable() instanceof ConnectException || res.getThrowable().getMessage().equals("Connection refused"))) + if (res.getThrowable()!=null && (res.getThrowable() instanceof ConnectException || res.getThrowable().getMessage().equals("Connection refused"))) { operationResult.setSimpleResult("Success"); + log.debug("Got a ConnectionRefused for operation " + name + " this is considered ok, as the remote server sometimes closes the communications channel before sending a reply"); + } else operationResult.setErrorMessage(res.getFailureDescription()); } + else { + operationResult.setSimpleResult("Success"); + } } else { if (res.isSuccess()) {
commit 19b995d365079f589f8431c1fbc43f8bbb6cf98d Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 12 11:51:54 2011 +0200
commented out the debug output in the test.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java index b44ed08..3798e55 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java @@ -81,11 +81,11 @@ public class SystemSettingsExporterTest extends JMockTest {
InputStream eis = new ExportingInputStream(exporters, new HashMap<String, ExporterMessages>(), 65536, false);
- String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); - - LOG.warn("Export contents:\n" + exportContents); - - eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8")); +// String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); +// +// LOG.warn("Export contents:\n" + exportContents); +// +// eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8"));
// <?xml version="1.0" ?> // <configuration-export>
commit d3d7cf22034c1bd9f2eca0488cdeebeb9e7e17d7 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 12 11:41:00 2011 +0200
Implemented tests for config-sync validators and importers. + some changes in the code to better support testability.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/Importer.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/Importer.java index 8ec5ebd..b61777d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/Importer.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/Importer.java @@ -37,6 +37,8 @@ public interface Importer<Entity, ExportedType> { /** * A configuration definition describing the configuration of the importer and * the default values for individual properties. + * <p> + * The returned configuration definition <b>MUST</b> define a default template. */ ConfigurationDefinition getImportConfigurationDefinition();
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index eefb452..eddd052 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -72,8 +72,13 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M public static final String METRIC_UPDATE_OVERRIDE_PROPERTY = "metricUpdateOverride";
private static class CollectionIntervalAndUpdateSchedules { - public long collectionInterval; - public boolean updateSchedules; + public final long collectionInterval; + public final boolean updateSchedules; + + public CollectionIntervalAndUpdateSchedules(long collectionInterval, boolean updateSchedules) { + this.collectionInterval = collectionInterval; + this.updateSchedules = updateSchedules; + }
@Override public int hashCode() { @@ -100,17 +105,18 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M private EntityManager entityManager; private List<MeasurementDefinition> definitionsToEnable = new ArrayList<MeasurementDefinition>(); private List<MeasurementDefinition> definitionsToDisable = new ArrayList<MeasurementDefinition>(); - private Map<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> definitionsByCollectionIntervalAndUpdateSchedules = + private Map<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> definitionsByCollectionIntervalAndUpdateSchedules = new HashMap<MetricTemplateImporter.CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>>(); private Configuration importConfiguration; private Unmarshaller unmarshaller; private MeasurementScheduleManagerLocal measurementScheduleManager; - + public MetricTemplateImporter(Subject subject, EntityManager entityManager) { this(subject, entityManager, LookupUtil.getMeasurementScheduleManager()); }
- public MetricTemplateImporter(Subject subject, EntityManager entityManager, MeasurementScheduleManagerLocal measurementScheduleManager) { + public MetricTemplateImporter(Subject subject, EntityManager entityManager, + MeasurementScheduleManagerLocal measurementScheduleManager) { try { this.subject = subject; this.entityManager = entityManager; @@ -121,26 +127,44 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M } this.measurementScheduleManager = measurementScheduleManager; } - + @Override public ConfigurationDefinition getImportConfigurationDefinition() { ConfigurationDefinition def = new ConfigurationDefinition("MetricTemplateImportConfiguration", null); - PropertyDefinitionSimple updateAllSchedules = new PropertyDefinitionSimple(UPDATE_ALL_SCHEDULES_PROPERTY, "If set to true, all the metric templates will update all the existing schedules on corresponding resources.", true, PropertySimpleType.BOOLEAN); + PropertyDefinitionSimple updateAllSchedules = + new PropertyDefinitionSimple( + UPDATE_ALL_SCHEDULES_PROPERTY, + "If set to true, all the metric templates will update all the existing schedules on corresponding resources.", + true, PropertySimpleType.BOOLEAN); updateAllSchedules.setDefaultValue(Boolean.toString(UPDATE_SCHEDULES_DEFAULT)); def.put(updateAllSchedules);
- PropertyDefinitionSimple metricName = new PropertyDefinitionSimple(METRIC_NAME_PROPERTY, "The name of the metric", true, PropertySimpleType.STRING); - PropertyDefinitionSimple resourceTypeName = new PropertyDefinitionSimple(RESOURCE_TYPE_NAME_PROPERTY, "The name of the resource type defining the metric", true, PropertySimpleType.STRING); - PropertyDefinitionSimple resourceTypePlugin = new PropertyDefinitionSimple(RESOURCE_TYPE_PLUGIN_PROPERTY, "The name of the plugin defining the resource type that defines the metric", true, PropertySimpleType.STRING); - PropertyDefinitionSimple updateSchedules = new PropertyDefinitionSimple(UPDATE_SCHEDULES_PROPERTY, "Whether to update the schedules of this metric on existing resources", true, PropertySimpleType.BOOLEAN); - - PropertyDefinitionMap metricUpdateOverride = new PropertyDefinitionMap(METRIC_UPDATE_OVERRIDE_PROPERTY, null, true, metricName, resourceTypeName, resourceTypePlugin, updateSchedules); - PropertyDefinitionList metricUpdateOverrides = new PropertyDefinitionList(METRIC_UPDATE_OVERRIDES_PROPERTY, "Per metric settings", false, metricUpdateOverride); - + PropertyDefinitionSimple metricName = + new PropertyDefinitionSimple(METRIC_NAME_PROPERTY, "The name of the metric", true, + PropertySimpleType.STRING); + PropertyDefinitionSimple resourceTypeName = + new PropertyDefinitionSimple(RESOURCE_TYPE_NAME_PROPERTY, + "The name of the resource type defining the metric", true, PropertySimpleType.STRING); + PropertyDefinitionSimple resourceTypePlugin = + new PropertyDefinitionSimple(RESOURCE_TYPE_PLUGIN_PROPERTY, + "The name of the plugin defining the resource type that defines the metric", true, + PropertySimpleType.STRING); + PropertyDefinitionSimple updateSchedules = + new PropertyDefinitionSimple(UPDATE_SCHEDULES_PROPERTY, + "Whether to update the schedules of this metric on existing resources", true, + PropertySimpleType.BOOLEAN); + + PropertyDefinitionMap metricUpdateOverride = + new PropertyDefinitionMap(METRIC_UPDATE_OVERRIDE_PROPERTY, null, true, metricName, resourceTypeName, + resourceTypePlugin, updateSchedules); + PropertyDefinitionList metricUpdateOverrides = + new PropertyDefinitionList(METRIC_UPDATE_OVERRIDES_PROPERTY, "Per metric settings", false, + metricUpdateOverride); + def.put(metricUpdateOverrides);
ConfigurationUtility.initializeDefaultTemplate(def); - + return def; }
@@ -155,8 +179,9 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
@Override public MeasurementDefinition findMatch(MetricTemplate object) { - Query q = entityManager - .createNamedQuery(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME); + Query q = + entityManager + .createNamedQuery(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME); q.setParameter("name", object.getMetricName()); q.setParameter("resourceTypeName", object.getResourceTypeName()); q.setParameter("resourceTypePlugin", object.getResourceTypePlugin()); @@ -215,12 +240,11 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
for (Map.Entry<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> e : definitionsByCollectionIntervalAndUpdateSchedules .entrySet()) { - measurementScheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(subject, getIdsFromDefs(e.getValue()), - e.getKey().collectionInterval, e.getKey().updateSchedules); + measurementScheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(subject, + getIdsFromDefs(e.getValue()), e.getKey().collectionInterval, e.getKey().updateSchedules); } }
- private static int[] getIdsFromDefs(Collection<MeasurementDefinition> defs) { int[] ids = new int[defs.size()];
@@ -233,9 +257,9 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M }
private void addToCollectionIntervalMap(MetricTemplate metricTemplate, MeasurementDefinition def) { - CollectionIntervalAndUpdateSchedules key = new CollectionIntervalAndUpdateSchedules(); - key.collectionInterval = metricTemplate.getDefaultInterval(); - key.updateSchedules = shouldUpdateSchedules(metricTemplate); + CollectionIntervalAndUpdateSchedules key = + new CollectionIntervalAndUpdateSchedules(metricTemplate.getDefaultInterval(), + shouldUpdateSchedules(metricTemplate));
List<MeasurementDefinition> defs = definitionsByCollectionIntervalAndUpdateSchedules.get(key);
@@ -254,7 +278,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
String updateAll = importConfiguration.getSimpleValue(UPDATE_ALL_SCHEDULES_PROPERTY, null); if (updateAll != null) { - if(Boolean.parseBoolean(updateAll)) { + if (Boolean.parseBoolean(updateAll)) { return true; } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java index 82b4180..604196a 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java @@ -48,6 +48,11 @@ import org.rhq.enterprise.server.system.SystemManagerLocal; */ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSettings> {
+ public static final String PROPERTIES_TO_IMPORT_PROPERTY = "propertiesToImport"; + public static final String DEFAULT_IMPORTED_PROPERTIES_LIST = + "AGENT_MAX_QUIET_TIME_ALLOWED, ENABLE_AGENT_AUTO_UPDATE, ENABLE_DEBUG_MODE, ENABLE_EXPERIMENTAL_FEATURES, CAM_DATA_PURGE_1H, CAM_DATA_PURGE_6H, " + + "CAM_DATA_PURGE_1D, CAM_DATA_MAINTENANCE, DATA_REINDEX_NIGHTLY, RT_DATA_PURGE, ALERT_PURGE, EVENT_PURGE, TRAIT_PURGE, AVAILABILITY_PURGE, CAM_BASELINE_FREQUENCY, CAM_BASELINE_DATASET"; + private Subject subject; private SystemManagerLocal systemManager; private Configuration importConfiguration; @@ -61,20 +66,23 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe unmarshaller = context.createUnmarshaller(); } catch (JAXBException e) { throw new IllegalStateException("Failed to initialize JAXB marshaller for MetricTemplate.", e); - } + } } - + @Override public ConfigurationDefinition getImportConfigurationDefinition() { ConfigurationDefinition def = new ConfigurationDefinition("SystemSettingsConfiguration", null); - - PropertyDefinitionSimple props = new PropertyDefinitionSimple("propertiesToImport", "The names of the properties that should be imported. Note that these are the INTERNAL names as used in the RHQ database", true, PropertySimpleType.STRING); - props.setDefaultValue("AGENT_MAX_QUIET_TIME_ALLOWED, ENABLE_AGENT_AUTO_UPDATE, ENABLE_DEBUG_MODE, ENABLE_EXPERIMENTAL_FEATURES, CAM_DATA_PURGE_1H, CAM_DATA_PURGE_6H, " + - "CAM_DATA_PURGE_1D, CAM_DATA_MAINTENANCE, DATA_REINDEX_NIGHTLY, RT_DATA_PURGE, ALERT_PURGE, EVENT_PURGE, TRAIT_PURGE, AVAILABILITY_PURGE, CAM_BASELINE_FREQUENCY, CAM_BASELINE_DATASET"); + + PropertyDefinitionSimple props = + new PropertyDefinitionSimple( + PROPERTIES_TO_IMPORT_PROPERTY, + "The names of the properties that should be imported. Note that these are the INTERNAL names as used in the RHQ database", + true, PropertySimpleType.STRING); + props.setDefaultValue(DEFAULT_IMPORTED_PROPERTIES_LIST); def.put(props); - + ConfigurationUtility.initializeDefaultTemplate(def); - + return def; }
@@ -94,22 +102,22 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe @Override public void update(NoSingleEntity entity, SystemSettings exportedEntity) throws Exception { Properties props = exportedEntity.toProperties(); - + Set<String> propsToImport = getSettingNamesConfiguredForImport(importConfiguration); - + Set<String> propsToRemove = new HashSet<String>(); - - for(Object k : props.keySet()) { + + for (Object k : props.keySet()) { String key = (String) k; if (!propsToImport.contains(key)) { propsToRemove.add(key); } } - - for(String p : propsToRemove) { + + for (String p : propsToRemove) { props.remove(p); } - + systemManager.setSystemConfiguration(subject, props, true); }
@@ -125,15 +133,15 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe @Override public void finishImport() { } - + private Set<String> getSettingNamesConfiguredForImport(Configuration importConfiguration) { - String settingsToImport = importConfiguration.getSimpleValue("propertiesToImport", null); - + String settingsToImport = importConfiguration.getSimpleValue(PROPERTIES_TO_IMPORT_PROPERTY, null); + if (settingsToImport == null) { return Collections.emptySet(); } else { String[] vals = settingsToImport.split("\s*,\s*"); - + return new HashSet<String>(Arrays.asList(vals)); } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java index f8f9ec7..17eae8a 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/validators/DeployedAgentPluginsValidator.java @@ -46,7 +46,7 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class DeployedAgentPluginsValidator implements ConsistencyValidator {
- private static class ConsistentPlugin extends Plugin { + public static class ConsistentPlugin extends Plugin {
private static final long serialVersionUID = 1L;
@@ -94,6 +94,22 @@ public class DeployedAgentPluginsValidator implements ConsistencyValidator { this.pluginManager = pluginManager; }
+ /** + * Provided for testability + * @return the pluginsToValidate + */ + public Set<ConsistentPlugin> getPluginsToValidate() { + return pluginsToValidate; + } + + /** + * Provided for testability + * @param pluginsToValidate the pluginsToValidate to set + */ + public void setPluginsToValidate(Set<ConsistentPlugin> pluginsToValidate) { + this.pluginsToValidate = pluginsToValidate; + } + @Override public void initialize(Subject subject, EntityManager entityManager) { } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java new file mode 100644 index 0000000..14cf4ce --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DeployedAgentPluginsValidatorTest.java @@ -0,0 +1,219 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.test; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.fail; + +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jmock.Expectations; +import org.testng.annotations.Test; + +import org.rhq.core.domain.plugin.Plugin; +import org.rhq.core.domain.plugin.PluginStatusType; +import org.rhq.enterprise.server.resource.metadata.PluginManagerLocal; +import org.rhq.enterprise.server.sync.ExportReader; +import org.rhq.enterprise.server.sync.ExportWriter; +import org.rhq.enterprise.server.sync.validators.DeployedAgentPluginsValidator; +import org.rhq.enterprise.server.sync.validators.InconsistentStateException; +import org.rhq.test.JMockTest; + +/** + * + * + * @author Lukas Krejci + */ +@Test +public class DeployedAgentPluginsValidatorTest extends JMockTest { + + private static final Log LOG = LogFactory.getLog(DeployedAgentPluginsValidator.class); + + public void testCanExportAndImportState() throws Exception { + final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); + + final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager); + + context.checking(new Expectations() { + { + oneOf(pluginManager).getInstalledPlugins(); + will(returnValue(new ArrayList<Plugin>(getDeployedPlugins()))); + } + }); + + validator.initialize(null, null); + + StringWriter output = new StringWriter(); + try { + XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); + + XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output); + //wrap the exported plugins in "something" so that we produce + //a valid xml + wrt.writeStartDocument(); + wrt.writeStartElement("root"); + + validator.exportState(new ExportWriter(wrt)); + + wrt.writeEndDocument(); + + wrt.close(); + + StringReader input = new StringReader(output.toString()); + + try { + XMLInputFactory ifactory = XMLInputFactory.newInstance(); + XMLStreamReader rdr = ifactory.createXMLStreamReader(input); + + //push the reader to the start of the plugin elements + //this is what is expected by the validators + rdr.nextTag(); + + validator.initializeValidation(new ExportReader(rdr)); + + rdr.close(); + + assertEquals(validator.getPluginsToValidate(), getDeployedPlugins()); + } finally { + input.close(); + } + } catch (Exception e) { + LOG.error("Test failed. Output generated so far:\n" + output, e); + throw e; + } finally { + output.close(); + } + } + + public void testDetectsPluginDifferencies() { + final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); + + //this is what we are going to return from the mocked plugin manager + final List<Plugin> installedPlugins = new ArrayList<Plugin>(getDeployedPlugins()); + + context.checking(new Expectations() { + { + allowing(pluginManager).getInstalledPlugins(); + will(returnValue(installedPlugins)); + } + }); + + DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager); + + Set<DeployedAgentPluginsValidator.ConsistentPlugin> pluginsToValidate = getDeployedPlugins(); + + validator.initialize(null, null); + + validator.setPluginsToValidate(pluginsToValidate); + + //this should validate cleanly + validator.validateCurrentState(); + + //now add 1 plugin to the validated state + DeployedAgentPluginsValidator.ConsistentPlugin newPlugin = createPlugin("superfluous", "1", "md5_4"); + pluginsToValidate.add(newPlugin); + + try { + validator.validateCurrentState(); + fail("validation should have detected that the current installation has one plugin less."); + } catch (InconsistentStateException e) { + //this is expected + } + + //ok, remove the new plugin from the "exported state" and put it in the current state + pluginsToValidate.remove(newPlugin); + installedPlugins.add(newPlugin); + + try { + validator.validateCurrentState(); + fail("validation should have detected that the current installation has one plugin more."); + } catch (InconsistentStateException e) { + //ok + } + + //make the current state and exported state be in sync again + DeployedAgentPluginsValidator.ConsistentPlugin newPluginCopy = new DeployedAgentPluginsValidator.ConsistentPlugin(newPlugin); + pluginsToValidate.add(newPluginCopy); + + //change the newPlugin to not be equal + newPlugin.setMd5("md5_different"); + + try { + validator.validateCurrentState(); + fail("validation should have failed because one of the plugins differs between current and exported states."); + } catch (InconsistentStateException e) { + //ok + } + + newPlugin.setMd5(newPluginCopy.getMd5()); + newPluginCopy.setMd5("md5_different"); + + try { + validator.validateCurrentState(); + fail("validation should have failed because one of the plugins differs between current and exported states."); + } catch (InconsistentStateException e) { + //ok + } + } + + public void testAllValidatorsEqual() { + PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); + + DeployedAgentPluginsValidator v1 = new DeployedAgentPluginsValidator(pluginManager); + DeployedAgentPluginsValidator v2 = new DeployedAgentPluginsValidator(pluginManager); + DeployedAgentPluginsValidator v3 = new DeployedAgentPluginsValidator(pluginManager); + Object o = new Object(); + + assertEquals(v1, v2); + assertEquals(v1, v3); + assertEquals(v2, v3); + + assertFalse(v1.equals(o)); + assertFalse(v2.equals(o)); + assertFalse(v3.equals(o)); + } + + private static Set<DeployedAgentPluginsValidator.ConsistentPlugin> getDeployedPlugins() { + HashSet<DeployedAgentPluginsValidator.ConsistentPlugin> ret = new HashSet<DeployedAgentPluginsValidator.ConsistentPlugin>(); + + ret.add(createPlugin("p1", "1", "md5_1")); + ret.add(createPlugin("p2", "1", "md5_2")); + ret.add(createPlugin("p3", "1", "md5_3")); + + return ret; + } + + private static DeployedAgentPluginsValidator.ConsistentPlugin createPlugin(String name, String version, String md5) { + return new DeployedAgentPluginsValidator.ConsistentPlugin(new Plugin(0, name, null, null, true, PluginStatusType.INSTALLED, null, null, md5, version, null, 0, 0)); + } +} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyExporter.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyExporter.java deleted file mode 100644 index 09037ba..0000000 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyExporter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.enterprise.server.sync.test; - -import org.rhq.enterprise.server.sync.NoSingleEntity; -import org.rhq.enterprise.server.sync.exporters.Exporter; -import org.rhq.enterprise.server.sync.exporters.ExportingIterator; - -public class DummyExporter<T> implements Exporter<NoSingleEntity, T> { - - @Override - public String getNotes() { - return null; - } - - @Override - public ExportingIterator<T> getExportingIterator() { - return null; - } - -} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyImporter.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyImporter.java deleted file mode 100644 index 17e2959..0000000 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummyImporter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.enterprise.server.sync.test; - -import javax.xml.stream.XMLStreamException; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; -import org.rhq.enterprise.server.sync.ExportReader; -import org.rhq.enterprise.server.sync.NoSingleEntity; -import org.rhq.enterprise.server.sync.importers.ExportedEntityMatcher; -import org.rhq.enterprise.server.sync.importers.Importer; -import org.rhq.enterprise.server.sync.importers.NoSingleEntityMatcher; - -public class DummyImporter<T> implements Importer<NoSingleEntity, T> { - - @Override - public ConfigurationDefinition getImportConfigurationDefinition() { - return new ConfigurationDefinition("dummy", "dummy"); - } - - @Override - public void configure(Configuration configuration) { - } - - @Override - public ExportedEntityMatcher<NoSingleEntity, T> getExportedEntityMatcher() { - return new NoSingleEntityMatcher<T>(); - } - - @Override - public void update(NoSingleEntity entity, T exportedEntity) { - } - - @Override - public void finishImport() { - } - - @Override - public T unmarshallExportedEntity(ExportReader reader) throws XMLStreamException { - return null; - } -} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummySynchronizer.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummySynchronizer.java deleted file mode 100644 index 78cfbd1..0000000 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/DummySynchronizer.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.enterprise.server.sync.test; - -import java.util.Collections; -import java.util.Set; - -import javax.persistence.EntityManager; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.enterprise.server.sync.NoSingleEntity; -import org.rhq.enterprise.server.sync.Synchronizer; -import org.rhq.enterprise.server.sync.exporters.Exporter; -import org.rhq.enterprise.server.sync.importers.Importer; -import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; - -/** - * - * - * @author Lukas Krejci - */ -public class DummySynchronizer<T> implements Synchronizer<NoSingleEntity, T> { - - @Override - public void initialize(Subject subject, EntityManager entityManager) { - } - - @Override - public Exporter<NoSingleEntity, T> getExporter() { - return new DummyExporter<T>(); - } - - @Override - public Importer<NoSingleEntity, T> getImporter() { - return new DummyImporter<T>(); - } - - @Override - public Set<ConsistencyValidator> getRequiredValidators() { - return Collections.emptySet(); - } - -} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsImporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsImporterTest.java new file mode 100644 index 0000000..5b94450 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsImporterTest.java @@ -0,0 +1,120 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import org.jmock.Expectations; +import org.testng.annotations.Test; + +import org.rhq.core.clientapi.util.StringUtil; +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.sync.entity.SystemSettings; +import org.rhq.enterprise.server.sync.importers.SystemSettingsImporter; +import org.rhq.enterprise.server.system.SystemManagerLocal; +import org.rhq.test.JMockTest; + +/** + * @author Lukas Krejci + */ +@Test +public class SystemSettingsImporterTest extends JMockTest { + + public void testNullConfigurationUnderstoodAsDefault() throws Exception { + final SystemManagerLocal systemManager = context.mock(SystemManagerLocal.class); + + SystemSettingsImporter importer = new SystemSettingsImporter(null, systemManager); + + final HashMap<String, String> settings = new HashMap<String, String>(); + settings.put("CAM_BASE_URL", "url"); + settings.put("SOME_UNKNOWN_PROPERTY", "asdf"); + String[] importableProps = SystemSettingsImporter.DEFAULT_IMPORTED_PROPERTIES_LIST.split("\s*,\s*"); + for (String p : importableProps) { + settings.put(p, "value"); + } + final SystemSettings importedSettings = new SystemSettings(settings); + + context.checking(new Expectations() { + { + Properties expectedImport = new Properties(); + expectedImport.putAll(settings); + //base url is not imported by default + expectedImport.remove("CAM_BASE_URL"); + expectedImport.remove("SOME_UNKNOWN_PROPERTY"); + + oneOf(systemManager).setSystemConfiguration(with(any(Subject.class)), with(expectedImport), with(true)); + } + }); + + importer.configure(null); + + importer.update(null, importedSettings); + + importer.finishImport(); + } + + public void testImportConfigurationHonored() throws Exception { + final SystemManagerLocal systemManager = context.mock(SystemManagerLocal.class); + + SystemSettingsImporter importer = new SystemSettingsImporter(null, systemManager); + + String[] importableProps = SystemSettingsImporter.DEFAULT_IMPORTED_PROPERTIES_LIST.split("\s*,\s*"); + + final HashMap<String, String> settings = new HashMap<String, String>(); + for (String p : importableProps) { + settings.put(p, "value"); + } + final SystemSettings importedSettings = new SystemSettings(settings); + + final List<String> allowedSettings = new ArrayList<String>(); + for (int i = 0; i < importableProps.length; ++i) { + if (i % 2 == 0) { + allowedSettings.add(importableProps[i]); + } + } + + context.checking(new Expectations() { + { + Properties expectedImport = new Properties(); + for (String s : allowedSettings) { + expectedImport.put(s, settings.get(s)); + } + + oneOf(systemManager).setSystemConfiguration(with(any(Subject.class)), with(expectedImport), with(true)); + } + }); + + Configuration importConfig = new Configuration(); + importConfig.put(new PropertySimple(SystemSettingsImporter.PROPERTIES_TO_IMPORT_PROPERTY, StringUtil + .collectionToString(allowedSettings, ", "))); + + importer.configure(importConfig); + + importer.update(null, importedSettings); + + importer.finishImport(); + } +} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java index a69e0c6..c00cb07 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java @@ -19,11 +19,61 @@
package org.rhq.enterprise.server.sync.test;
+import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; + +import java.util.Properties; + +import org.jmock.Expectations; +import org.testng.annotations.Test; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.sync.entity.SystemSettings; +import org.rhq.enterprise.server.sync.validators.SystemSettingsValidator; +import org.rhq.enterprise.server.system.SystemManagerLocal; +import org.rhq.test.JMockTest; + /** * * * @author Lukas Krejci */ -public class SystemSettingsValidatorTest { +@Test +public class SystemSettingsValidatorTest extends JMockTest {
+ public void testValidatorCallsSystemManager() { + final SystemManagerLocal systemManager = context.mock(SystemManagerLocal.class); + + SystemSettingsValidator validator = new SystemSettingsValidator(systemManager); + + final Properties settings = new Properties(); + settings.put("A", "a"); + settings.put("B", "b"); + SystemSettings importedSettings = new SystemSettings(settings); + + context.checking(new Expectations() { + { + oneOf(systemManager).validateSystemConfiguration(with(any(Subject.class)), with(settings)); + } + }); + + validator.validateExportedEntity(importedSettings); + } + + public void testAllValidatorsAreEqual() { + SystemManagerLocal systemManager = context.mock(SystemManagerLocal.class); + + SystemSettingsValidator v1 = new SystemSettingsValidator(systemManager); + SystemSettingsValidator v2 = new SystemSettingsValidator(systemManager); + SystemSettingsValidator v3 = new SystemSettingsValidator(systemManager); + Object o = new Object(); + + assertEquals(v1, v2); + assertEquals(v1, v3); + assertEquals(v2, v3); + + assertFalse(v1.equals(o)); + assertFalse(v2.equals(o)); + assertFalse(v3.equals(o)); + } }
commit 60f74509f953fb82f920c69e75a83dfd47ce9417 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 02:49:49 2011 -0400
flush hibernate cache before interacting with agent client
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 183d531..5daa885 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 @@ -271,6 +271,7 @@ public class DriftManagerBean implements DriftManagerLocal { doomedDriftConfig.setResource(null); resource = entityManager.merge(resource); entityManager.flush(); + entityManager.clear(); // clear the hibernate cache - we're about to call some agent API and we don't want it messing with attached objects
try { AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
commit 2b27eda2a29d8f49cac2e2b6c1135210bb8374ef Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 02:48:12 2011 -0400
make sure the drift config entity is orphaned so hibernate knows to delete it
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 0e57f45..183d531 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 @@ -268,8 +268,9 @@ public class DriftManagerBean implements DriftManagerLocal {
if (doomedDriftConfig != null) { resource.getDriftConfigurations().remove(doomedDriftConfig); - entityManager.remove(doomedDriftConfig); - entityManager.merge(resource); + doomedDriftConfig.setResource(null); + resource = entityManager.merge(resource); + entityManager.flush();
try { AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId);
commit 215204da2bb9773faaa5b35f1c2903db5e274e8c Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 02:34:00 2011 -0400
trying to get delete drift config to work - this still isn't working but getting there
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 index f090bd8..a8ca1f4 100644 --- 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 @@ -20,10 +20,11 @@ package org.rhq.enterprise.gui.coregui.client.drift;
import java.util.ArrayList; -import java.util.Arrays;
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; @@ -139,14 +140,14 @@ public class DriftConfigurationView extends TableSection<DriftConfigurationDataS } });
- addTableAction("Delete", MSG.common_button_delete(), MSG.view_drift_delete_confirm(), new AbstractTableAction( - deleteEnablement) { - public void executeAction(ListGridRecord[] selection, Object actionValue) { - delete(selection); - } - }); + 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_confirmAll(), + addTableAction("DeleteAll", MSG.common_button_delete_all(), MSG.view_drift_delete_configConfirmAll(), new TableAction() { public boolean isEnabled(ListGridRecord[] selection) { ListGrid grid = getListGrid(); @@ -162,7 +163,7 @@ public class DriftConfigurationView extends TableSection<DriftConfigurationDataS addTableAction("DetectNow", MSG.view_drift_button_detectNow(), null, new AbstractTableAction( detectNowEnablement) { public void executeAction(ListGridRecord[] selection, Object actionValue) { - detectDrift(selection); + detectDrift(selection); // will only ever be a single selection - see detectNowEnablement variable } }); } @@ -172,44 +173,55 @@ public class DriftConfigurationView extends TableSection<DriftConfigurationDataS }
private void delete(ListGridRecord[] records) { - final int[] driftConfigIds = new int[records.length]; + final String[] driftConfigNames = new String[records.length]; for (int i = 0, selectionLength = records.length; i < selectionLength; i++) { ListGridRecord record = records[i]; - Integer driftConfigId = record.getAttributeAsInt("id"); - driftConfigIds[i] = driftConfigId; + String driftConfigName = record.getAttribute(DriftConfigurationDataSource.ATTR_NAME); + driftConfigNames[i] = driftConfigName; }
- GWTServiceLookup.getDriftService().deleteDriftConfigurations(driftConfigIds, 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(); - } + 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_delete(Arrays.toString(driftConfigIds)), - caught); - } - }); + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteConfigs(), caught); + } + }); }
private void deleteAll() { - GWTServiceLookup.getDriftService().deleteDriftConfigurationsByContext(context, new AsyncCallback<Integer>() { - public void onSuccess(Integer resultCount) { - CoreGUI.getMessageCenter().notify( - new Message(MSG.view_drift_success_delete(String.valueOf(resultCount)), Message.Severity.Info)); - refresh(); - } + 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; + }
- public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_deleteAll(), caught); - } - }); + 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_deleteConfigs(), caught); + } + }); }
private void detectDrift(ListGridRecord[] records) { - // why only the [0] item? + // 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>() { 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 60065d9..f47a5b9 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 @@ -49,6 +49,7 @@ public interface DriftGWTService extends RemoteService { * * @param driftIds the ids of the drifts to be deleted * @return the number of drifts deleted + * @deprecated */ int deleteDrifts(String[] driftIds) throws RuntimeException;
@@ -66,30 +67,15 @@ public interface DriftGWTService extends RemoteService { int deleteDriftsByContext(EntityContext entityContext) throws RuntimeException;
/** - * Delete the drift configs with the specified ids if the current user has permission to do so (i.e. either + * Delete all named drift configurations 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). - * If the user does not have permission for all of the specified drift configs, then none of them will be deleted - * and a PermissionException will be thrown. - * - * If any of the ids do not correspond to drift entities that exist, those ids will be gracefully ignored. - * - * @param driftConfigIds the ids of the drift configs to be deleted - * @return the number of drift configs deleted - */ - int deleteDriftConfigurations(int[] driftConfigIds) throws RuntimeException; - - /** - * Delete all drift configurations 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). - * If the user does not have permission for all of the specified drifts, then none of the drifts will be deleted - * and a PermissionException will be thrown. - * - * If the entity does not correspond to an existing entity, it will be gracefully ignored. * * @param entityContext the context for deletion + * @param driftConfigNames the names of the configs to delete * @return the number of drift configs deleted */ - int deleteDriftConfigurationsByContext(EntityContext entityContext) throws RuntimeException; + int deleteDriftConfigurationsByContext(EntityContext entityContext, String[] driftConfigNames) + throws RuntimeException;
/** * One time on-demand request to detect drift on the specified entities, using the supplied config. 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 95e6d19..c99a475 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 @@ -43,6 +43,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift private DriftManagerLocal driftManager = LookupUtil.getDriftManager();
@Override + @Deprecated public int deleteDrifts(String[] driftIds) throws RuntimeException { try { return this.driftManager.deleteDrifts(getSessionSubject(), driftIds); @@ -61,22 +62,13 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public int deleteDriftConfigurations(int[] driftConfigIds) throws RuntimeException { - try { - // TODO - //return this.driftManager.deleteDriftConfigurations(getSessionSubject(), driftConfigIds); - return 0; - } catch (Throwable t) { - throw getExceptionToThrowToClient(t); - } - } - - @Override - public int deleteDriftConfigurationsByContext(EntityContext entityContext) throws RuntimeException { + public int deleteDriftConfigurationsByContext(EntityContext entityContext, String[] driftConfigNames) + throws RuntimeException { try { - // TODO - //return this.driftManager.deleteDriftConfigurationsByContext(getSessionSubject(), entityContext); - return 0; + for (String driftConfigName : driftConfigNames) { + this.driftManager.deleteDriftConfiguration(getSessionSubject(), entityContext, driftConfigName); + } + return driftConfigNames.length; } catch (Throwable t) { throw getExceptionToThrowToClient(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 0ba3347..01447f3 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 @@ -1127,10 +1127,13 @@ view_drift_changeSets_resourceViewTitle = Resource Drift Change Sets view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. view_drift_changeset_tree_showConfiguration = Show Configuration +view_drift_delete_configConfirm = Delete the selected drift configuration(s)? +view_drift_delete_configConfirmAll = Delete all drift configurations? view_drift_delete_confirm = Delete the selected drift(s)? view_drift_delete_confirmAll = Delete all drifts from this source? view_drift_failure_delete = Failed to delete drift targets with id''s: {0} view_drift_failure_deleteAll = Failed to delete all drift targets from this source +view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. view_drift_failure_detectNow = Failed to submit drift detection request view_drift_failure_load = Failed to fetch drift data view_drift_success_configurationUpdated = Drift configuration updated. File coverage will be updated on next detection scan. 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 977f4a4..c121055 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 @@ -945,10 +945,13 @@ view_dashboards_title = Dashboard ##view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] ##view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. ##view_drift_changeset_tree_showConfiguration = Show Configuration +##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? +##view_drift_delete_configConfirmAll = Delete all drift configurations? ##view_drift_delete_confirm = Delete the selected drift(s)? ##view_drift_delete_confirmAll = Delete all drifts from this source? ##view_drift_failure_delete = Failed to delete drift targets with id''s: {0} ##view_drift_failure_deleteAll = Failed to delete all drift targets from this source +##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. ##view_drift_failure_detectNow = Failed to submit drift detection request ##view_drift_failure_load = Failed to fetch drift data ##view_drift_success_configurationUpdated = Drift configuration updated. File coverage will be updated on next detection scan. 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 6af4be0..44e5478 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 @@ -1110,6 +1110,9 @@ view_dashboards_title = ããã·ã¥ããŒã ##view_drift_changeset_tree_loadConfigFailure = Failed to load drift configuration for change set id [{0}] ##view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. ##view_drift_changeset_tree_showConfiguration = Show Configuration +##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? +##view_drift_delete_configConfirmAll = Delete all drift configurations? +##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. ##view_drift_table_baseDir = Base Directory ##view_drift_table_changeSet = Change Set ##view_drift_table_newFile = New File 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 db58050..eb07683 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 @@ -1085,37 +1085,37 @@ view_configEdit_tooltip_1 = Remove os itens selecionados da lista. view_configEdit_tooltip_2 = Adiciona um item \u00E0 lista. view_configEdit_viewRow = Visualizar linha view_configurationDetails_allPropertiesValid = Todas as propriedades de configura\u00E7\u00E3o s\u00E3o v\u00E1lidas, portanto a configura\u00E7\u00E3o pode ser salva. -view_configurationDetails_configNotUpdatedDueToNoChange = A configuração não foi atualizada, pois a nova configuração é equivalente à atual. -view_configurationDetails_error_updateFailure = Falha ao atualizar a configuração. -view_configurationDetails_messageConcise = Configuração atualizada - versão corrrente: {0}. -view_configurationDetails_messageDetailed = Configuração do Recurso [{1}] atualizada para a versão {0}. -view_configurationDetails_noPermission = Você não possui permisssão para editar a configuraçào do Recurso. -view_configurationDetails_somePropertiesInvalid = As seguintes propriedades possuem valores inválidos: {0}. Os valores devem ser corrigidos antes da configuração ser salva. -view_configurationHistoryDetails_dialogTitle = Detalhes da Configuração -view_configurationHistoryDetails_error_loadFailure = Não foi possível carregar o histórico de configuração. -view_configurationHistoryList_cannotDeleteCurrent = Um dos itens de histórico selecionado representa a configuração corrente. - você não pode excluí-lo. -view_configurationHistoryList_cannotDeleteGroupItems = Um ou mais itens do histórico de configuração selecionado pertencem à uma atualização de configuração em grupo. view_configurationHistoryList_delete_failure = Falha ao excluir o histórico dos itens de configuração. -view_configurationHistoryList_delete_failure = Falha ao excluir o histórico dos itens de configuração. -view_configurationHistoryList_delete_success = Itens do histórico de configuração selecionados excluídos com sucesso. +view_configurationDetails_configNotUpdatedDueToNoChange = A configuraᅵᅵo nï¿œo foi atualizada, pois a nova configuraᅵᅵo ï¿œ equivalente ï¿œ atual. +view_configurationDetails_error_updateFailure = Falha ao atualizar a configuraᅵᅵo. +view_configurationDetails_messageConcise = Configuraᅵᅵo atualizada - versï¿œo corrrente: {0}. +view_configurationDetails_messageDetailed = Configuraᅵᅵo do Recurso [{1}] atualizada para a versï¿œo {0}. +view_configurationDetails_noPermission = Vocï¿œ nï¿œo possui permisssï¿œo para editar a configuraᅵᅵo do Recurso. +view_configurationDetails_somePropertiesInvalid = As seguintes propriedades possuem valores invï¿œlidos: {0}. Os valores devem ser corrigidos antes da configuraᅵᅵo ser salva. +view_configurationHistoryDetails_dialogTitle = Detalhes da Configuraᅵᅵo +view_configurationHistoryDetails_error_loadFailure = Nï¿œo foi possï¿œvel carregar o histï¿œrico de configuraᅵᅵo. +view_configurationHistoryList_cannotDeleteCurrent = Um dos itens de histï¿œrico selecionado representa a configuraᅵᅵo corrente. - vocï¿œ nï¿œo pode excluï¿œ-lo. +view_configurationHistoryList_cannotDeleteGroupItems = Um ou mais itens do histï¿œrico de configuraᅵᅵo selecionado pertencem ï¿œ uma atualizaᅵᅵo de configuraᅵᅵo em grupo. view_configurationHistoryList_delete_failure = Falha ao excluir o histï¿œrico dos itens de configuraᅵᅵo. +view_configurationHistoryList_delete_failure = Falha ao excluir o histï¿œrico dos itens de configuraᅵᅵo. +view_configurationHistoryList_delete_success = Itens do histï¿œrico de configuraᅵᅵo selecionados excluï¿œdos com sucesso. view_configurationHistoryList_rollback = Desfazer -view_configurationHistoryList_rollback_failure = Falha ao desfazer a configuração. A configuração original ainda permanece. -view_configurationHistoryList_rollback_success = Configuração revertida para a configuração selecionada com sucesso. -view_configurationHistoryList_table_clickStatusIcon = Clique no ícone status para visualizar os detlahes. -view_configurationHistoryList_table_statusFailure = Falha ao atualizar a configuração -view_configurationHistoryList_table_statusInprogress = A atualização desta configuração ainda está em andamento. -view_configurationHistoryList_table_statusNochange = Nenhuma mundaça foi feita nesta configuração -view_configurationHistoryList_table_statusSuccess = Configuração atualizada com sucesso -view_configurationHistoryList_title = Histórico de Configuração -view_connectionSettingsDetails_allPropertiesValid = Todas a propriedades estão corretas, portanto a configuração pode ser salva agora. -view_connectionSettingsDetails_error_updateFailure = Falha ao atualizar as propriedades de conexão. -##view_connectionSettingsDetails_messageConcise_updateSuccess = Atualização das propriedades de conexão iniciada. -##view_connectionSettingsDetails_messageDetailed_updateSuccess = Propriedades de conexão do Recurso [{0}] atualizadas -view_connectionSettingsDetails_noPermission = Você não possui permissão para editar as propriedades de conexão do Recurso. -view_connectionSettingsDetails_somePropertiesInvalid = As seguintes propriedades de conexão estão incorretas: {0}. Os valores devem ser corrigidos antes de serem salvos. +view_configurationHistoryList_rollback_failure = Falha ao desfazer a configuraᅵᅵo. A configuraᅵᅵo original ainda permanece. +view_configurationHistoryList_rollback_success = Configuraᅵᅵo revertida para a configuraᅵᅵo selecionada com sucesso. +view_configurationHistoryList_table_clickStatusIcon = Clique no ï¿œcone status para visualizar os detlahes. +view_configurationHistoryList_table_statusFailure = Falha ao atualizar a configuraᅵᅵo +view_configurationHistoryList_table_statusInprogress = A atualizaᅵᅵo desta configuraᅵᅵo ainda estï¿œ em andamento. +view_configurationHistoryList_table_statusNochange = Nenhuma mundaï¿œa foi feita nesta configuraᅵᅵo +view_configurationHistoryList_table_statusSuccess = Configuraᅵᅵo atualizada com sucesso +view_configurationHistoryList_title = Histï¿œrico de Configuraᅵᅵo +view_connectionSettingsDetails_allPropertiesValid = Todas a propriedades estï¿œo corretas, portanto a configuraᅵᅵo pode ser salva agora. +view_connectionSettingsDetails_error_updateFailure = Falha ao atualizar as propriedades de conexï¿œo. +##view_connectionSettingsDetails_messageConcise_updateSuccess = Atualizaᅵᅵo das propriedades de conexï¿œo iniciada. +##view_connectionSettingsDetails_messageDetailed_updateSuccess = Propriedades de conexï¿œo do Recurso [{0}] atualizadas +view_connectionSettingsDetails_noPermission = Vocï¿œ nï¿œo possui permissï¿œo para editar as propriedades de conexï¿œo do Recurso. +view_connectionSettingsDetails_somePropertiesInvalid = As seguintes propriedades de conexï¿œo estï¿œo incorretas: {0}. Os valores devem ser corrigidos antes de serem salvos. view_core_error_1 = Falha ao perquisar novos alertas view_core_loggedInAs = Logado como {0} view_core_loggedOut = Desconectado -view_core_noRecentAlerts = Não existem alertas recentes +view_core_noRecentAlerts = Nï¿œo existem alertas recentes view_core_recentAlerts = [{0}] alertas recentes view_core_uncaught = Exce\u00E7\u00E3o n\u00E3o capturada view_dashboardManager_deleteFail = Falha ao excluir o dashboard. @@ -1131,8 +1131,8 @@ view_dashboardsManager_message_title = Bem vindo ao RHQ view_dashboardsManager_message_title_details = <h1>Bem vindo ao RHQ</h1>\n<p> O projeto RHQ \u00E9 uma abstra\u00E7\u00E3o e uma suite de gerenciamento de sistemas baseada em plug-ins que fornece uma solu\u00E7\u00E3o extens\u00EDvel e integrada para o gerenciamento de m\u00FAltiplas plataformas atrav\u00E9s de um conjunto de funcionalidades que faz parte de seu n\u00FAcleo. O projeto foi concebido com m\u00F3dulos em camadas que fornecem uma arquitetura flexivel para sua implanta\u00E7\u00E3o. Ele possui uma interface de usu\u00E1rio que propcia o hist\u00F3rico e a auditoria do gerenciamento de recursos por toda a empresa. Sua arquitetura baseada em Agente-Servidor permite o gerenciamento remoto atrav\u00E9s de plugins que implementam todo o suporte espec\u00EDfico aos recursos gerenciados.<p> <p>Este dashboard padr\u00E3o pode ser modificado clicando o bot\u00E3o (modo edi\u00E7\u00E3o) acima.</p> view_dashboardsManager_tagcloud_title = Nuvem de Tags view_dashboards_confirm1 = Tem certeza de que deseja excluir? -view_dashboards_portlets_refresh_fail1 = Falha ao alterar o intervalo de atualização de portlets dinâmicos. -view_dashboards_portlets_refresh_fail2 = Falha ao desabilitar a atualização de portlets dinâmicos. +view_dashboards_portlets_refresh_fail1 = Falha ao alterar o intervalo de atualizaᅵᅵo de portlets dinï¿œmicos. +view_dashboards_portlets_refresh_fail2 = Falha ao desabilitar a atualizaᅵᅵo de portlets dinï¿œmicos. view_dashboards_portlets_refresh_multiple_min = {0} minutos view_dashboards_portlets_refresh_none = N\u00E3o atualizar view_dashboards_portlets_refresh_one_min = 1 minuto @@ -1143,94 +1143,97 @@ view_dashboards_title = Dashboard ##view_drift_category_fileAdded = Arquivo adicionado ##view_drift_category_fileChanged = Arquivo alterado ##view_drift_category_fileRemoved = Arquivo removido +##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? +##view_drift_delete_configConfirmAll = Delete all drift configurations? ##view_drift_delete_confirm = Excluir drift(s) selecionado(s)? ##view_drift_delete_confirmAll = Excluir todos os drifts desta origem? ##view_drift_failure_delete = Falha ao excluir os alvos dos drifts com ids: {0} ##view_drift_failure_deleteAll = Falha ao excluir todos os alvos dos drifts desta origem -##view_drift_failure_detectNow = Falha ao submeter a requisição de detecção do drift +##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. +##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 -##view_drift_success_configurationUpdated = Configuração do drift atualizada. O arquivo de cobertura será atualizado na próxima varredura de detecção. -##view_drift_success_delete = Drifts {0} excluídos com sucesso! -##view_drift_success_deleteConfigs = Configurações do drift {0} excluídas com sucesso! -##view_drift_success_detectNow = Requisição de detecção de drift submetida com sucesso. -##view_drift_table_baseDir = Diretório Base +##view_drift_success_configurationUpdated = Configuraᅵᅵo do drift atualizada. O arquivo de cobertura serï¿œ atualizado na prï¿œxima varredura de detecᅵᅵo. +##view_drift_success_delete = Drifts {0} excluï¿œdos com sucesso! +##view_drift_success_deleteConfigs = Configuraᅵᅵes do drift {0} excluï¿œdas com sucesso! +##view_drift_success_detectNow = Requisiᅵᅵo de detecᅵᅵo de drift submetida com sucesso. +##view_drift_table_baseDir = Diretï¿œrio Base ##view_drift_table_newFile = Novo Arquivo ##view_drift_table_oldFile = Arquivo Antigo -##view_drift_table_resourceConfig = Configuração de Drift do Recurso -##view_drift_table_resourceHistory = Histórico de Drift do Recurso -##view_drift_wizard_addConfig_failure = Falha ao adicionar nova configuração de drift [{0}] -##view_drift_wizard_addConfig_infoStepName = Provide Drift Detection Information\nForneça a informação para detecção do drift -##view_drift_wizard_addConfig_nameHelp = Um nome que descreve de forma objetiva o propósito desta configuração de drift de detecção. Nomes de configuração de drift devem ser únicos para um determinado recurso. -##view_drift_wizard_addConfig_namePrompt = Novo nome para configuração do drift -##view_drift_wizard_addConfig_success = Nova configuração de drift incluída com sucesso [{0}]. O(s) agente(s) será(ão) atualizado(s). -##view_drift_wizard_addConfig_templateHelp = Cada configuração de drift define um conjunto de arquivos no qual a detecção será aplicada. A configuração pode ser habilitada ou desabilitada, define um intervalo de detecção, e especifica um diretório raiz e filtros opcionais. Para cada tipo de recurso com suporte a detecção de drift existe um ou mais templates pré-definidos para usar como ponto de partida e que podem ser editados posteriormente. -##view_drift_wizard_addConfig_templatePrompt = Templates de configuração de Drift -##view_drift_wizard_addConfig_title = Incluir Configuração de Drift para o Tipo de Recurso [{0}] -##view_drift_wizard_addConfig_windowTitle = Assistente de Configuração de Drift -view_dynagroup_children = Grupo Dinâmico Filho -view_dynagroup_compatible = Compátivel -view_dynagroup_definitionAlreadyExists = Já existe uma definição de grupo com este nome -view_dynagroup_definitionCreated = Definição de grupo [{0}] criada com sucesso! -view_dynagroup_definitionLoadFailure = Falha ao carregar as definições de grupo -view_dynagroup_definitions = Definições de Grupos Dinâmicos -view_dynagroup_deleteFailureSelection = Falha ao excluir as definições selecionadas -view_dynagroup_deleteSuccessfulSelection = Definições de grupo [{0}] excluídas com sucesso! +##view_drift_table_resourceConfig = Configuraᅵᅵo de Drift do Recurso +##view_drift_table_resourceHistory = Histï¿œrico de Drift do Recurso +##view_drift_wizard_addConfig_failure = Falha ao adicionar nova configuraᅵᅵo de drift [{0}] +##view_drift_wizard_addConfig_infoStepName = Provide Drift Detection Information\nForneï¿œa a informaᅵᅵo para detecᅵᅵo do drift +##view_drift_wizard_addConfig_nameHelp = Um nome que descreve de forma objetiva o propï¿œsito desta configuraᅵᅵo de drift de detecᅵᅵo. Nomes de configuraᅵᅵo de drift devem ser ï¿œnicos para um determinado recurso. +##view_drift_wizard_addConfig_namePrompt = Novo nome para configuraᅵᅵo do drift +##view_drift_wizard_addConfig_success = Nova configuraᅵᅵo de drift incluï¿œda com sucesso [{0}]. O(s) agente(s) serï¿œ(ï¿œo) atualizado(s). +##view_drift_wizard_addConfig_templateHelp = Cada configuraᅵᅵo de drift define um conjunto de arquivos no qual a detecᅵᅵo serï¿œ aplicada. A configuraᅵᅵo pode ser habilitada ou desabilitada, define um intervalo de detecᅵᅵo, e especifica um diretï¿œrio raiz e filtros opcionais. Para cada tipo de recurso com suporte a detecᅵᅵo de drift existe um ou mais templates prï¿œ-definidos para usar como ponto de partida e que podem ser editados posteriormente. +##view_drift_wizard_addConfig_templatePrompt = Templates de configuraᅵᅵo de Drift +##view_drift_wizard_addConfig_title = Incluir Configuraᅵᅵo de Drift para o Tipo de Recurso [{0}] +##view_drift_wizard_addConfig_windowTitle = Assistente de Configuraᅵᅵo de Drift +view_dynagroup_children = Grupo Dinï¿œmico Filho +view_dynagroup_compatible = Compï¿œtivel +view_dynagroup_definitionAlreadyExists = Jï¿œ existe uma definiᅵᅵo de grupo com este nome +view_dynagroup_definitionCreated = Definiᅵᅵo de grupo [{0}] criada com sucesso! +view_dynagroup_definitionLoadFailure = Falha ao carregar as definiᅵᅵes de grupo +view_dynagroup_definitions = Definiᅵᅵes de Grupos Dinï¿œmicos +view_dynagroup_deleteFailureSelection = Falha ao excluir as definiᅵᅵes selecionadas +view_dynagroup_deleteSuccessfulSelection = Definiᅵᅵes de grupo [{0}] excluï¿œdas com sucesso! view_dynagroup_editing = Editando [{0}] -view_dynagroup_exprBuilder_addExpression = Adicionar Expressão -view_dynagroup_exprBuilder_comparisonType = Tipo de comparação -view_dynagroup_exprBuilder_comparisonType_contains = contém +view_dynagroup_exprBuilder_addExpression = Adicionar Expressï¿œo +view_dynagroup_exprBuilder_comparisonType = Tipo de comparaᅵᅵo +view_dynagroup_exprBuilder_comparisonType_contains = contï¿œm view_dynagroup_exprBuilder_comparisonType_endsWith = Termina com view_dynagroup_exprBuilder_comparisonType_equals = igual view_dynagroup_exprBuilder_comparisonType_startsWith = inicia com -view_dynagroup_exprBuilder_comparisonType_tooltip = Tipo de Comparação +view_dynagroup_exprBuilder_comparisonType_tooltip = Tipo de Comparaᅵᅵo view_dynagroup_exprBuilder_definingPlugin = Plugin view_dynagroup_exprBuilder_definingPlugin_tooltip = O plugin a ser procurado -view_dynagroup_exprBuilder_expression = Expressão -view_dynagroup_exprBuilder_expressionType = Tipo de Expressão -view_dynagroup_exprBuilder_expressionType_pluginConfig = Configuração do Plugin +view_dynagroup_exprBuilder_expression = Expressï¿œo +view_dynagroup_exprBuilder_expressionType = Tipo de Expressï¿œo +view_dynagroup_exprBuilder_expressionType_pluginConfig = Configuraᅵᅵo do Plugin view_dynagroup_exprBuilder_expressionType_resource = Recurso view_dynagroup_exprBuilder_expressionType_resourceCategory = Categoria do Recurso -view_dynagroup_exprBuilder_expressionType_resourceConfig = Configuração do Recurso +view_dynagroup_exprBuilder_expressionType_resourceConfig = Configuraᅵᅵo do Recurso view_dynagroup_exprBuilder_expressionType_resourceType = Tipo do Recurso -view_dynagroup_exprBuilder_expressionType_tooltip = Tipo de propriedade usada por esta expressão:<br/> <b>Recurso</b>: Uma propriedade do recurso (ex: nome ou versão)<br/> <b>Tipo de Recurso</b>: Procura por recursos de um tipo específico<br/> <b>Categoria do Recurso</b>: Procura por recursos de uma categoria específica: platforma, servidor, serviço<br/> <b>Característica</b>: Recursos que possuem valores selecionados para uma característica monitorada<br/> <b>Configuração do Plugin</b>: Procurar pela configuração do componente do plugin <br/> <b>Configuração do Recurso</b>: Procurar pela configuração do recurso gerenciado -view_dynagroup_exprBuilder_expressionType_trait = Característica -view_dynagroup_exprBuilder_expression_tooltip = Esta é a expressão completa com base nas definições do formulário abaixo. Este texto será adicionado ao campo de expressão da definição do grupo quando você clicar o botão "Adicionar Expressão" +view_dynagroup_exprBuilder_expressionType_tooltip = Tipo de propriedade usada por esta expressï¿œo:<br/> <b>Recurso</b>: Uma propriedade do recurso (ex: nome ou versï¿œo)<br/> <b>Tipo de Recurso</b>: Procura por recursos de um tipo especï¿œfico<br/> <b>Categoria do Recurso</b>: Procura por recursos de uma categoria especï¿œfica: platforma, servidor, serviï¿œo<br/> <b>Caracterï¿œstica</b>: Recursos que possuem valores selecionados para uma caracterï¿œstica monitorada<br/> <b>Configuraᅵᅵo do Plugin</b>: Procurar pela configuraᅵᅵo do componente do plugin <br/> <b>Configuraᅵᅵo do Recurso</b>: Procurar pela configuraᅵᅵo do recurso gerenciado +view_dynagroup_exprBuilder_expressionType_trait = Caracterï¿œstica +view_dynagroup_exprBuilder_expression_tooltip = Esta ï¿œ a expressï¿œo completa com base nas definiᅵᅵes do formulï¿œrio abaixo. Este texto serï¿œ adicionado ao campo de expressï¿œo da definiᅵᅵo do grupo quando vocï¿œ clicar o botï¿œo "Adicionar Expressï¿œo" view_dynagroup_exprBuilder_groupBy = Agrupado por -view_dynagroup_exprBuilder_groupBy_tooltip = GroupBy fará com que o resultado da busca seja agrupado de acordo com os valores informados na expressão. Por exemplo, usando GroupBy para o nome de um cluster JBossAS, o resultado criará um grupo para cada cluster e seus membros. +view_dynagroup_exprBuilder_groupBy_tooltip = GroupBy farï¿œ com que o resultado da busca seja agrupado de acordo com os valores informados na expressï¿œo. Por exemplo, usando GroupBy para o nome de um cluster JBossAS, o resultado criarï¿œ um grupo para cada cluster e seus membros. view_dynagroup_exprBuilder_noPlugins = --Sem plugins-- view_dynagroup_exprBuilder_noProperties = --Sem propriedades-- view_dynagroup_exprBuilder_noResourceTypes = --Nehum tipo de recurso-- view_dynagroup_exprBuilder_pluginLoadFailure = N\u00E3o foi poss\u00EDvel obter a lista de plugins view_dynagroup_exprBuilder_propLoadFailure = N\u00E3o foi poss\u00EDvel obter a lista de propriedades view_dynagroup_exprBuilder_propertyName = Nome da propriedade -view_dynagroup_exprBuilder_propertyName_tooltip = O nome da propriedade a ser pesquisada. Isso é definido pelo tipo da expressão bem como o tipo do recurso. -view_dynagroup_exprBuilder_resTypeLoadFailure = Não foi possível recuperar a lista de recursos para o plugin [{0}] +view_dynagroup_exprBuilder_propertyName_tooltip = O nome da propriedade a ser pesquisada. Isso ï¿œ definido pelo tipo da expressï¿œo bem como o tipo do recurso. +view_dynagroup_exprBuilder_resTypeLoadFailure = Nï¿œo foi possï¿œvel recuperar a lista de recursos para o plugin [{0}] view_dynagroup_exprBuilder_resource = Recurso view_dynagroup_exprBuilder_resourceType = Tipo de Recurso view_dynagroup_exprBuilder_resourceType_tooltip = O tipo do recurso view_dynagroup_exprBuilder_resource_child = Filho -view_dynagroup_exprBuilder_resource_grandparent = Avô -view_dynagroup_exprBuilder_resource_greatGrandparent = Bizavô -view_dynagroup_exprBuilder_resource_greatGreatGrandparent = Tataravô +view_dynagroup_exprBuilder_resource_grandparent = Avï¿œ +view_dynagroup_exprBuilder_resource_greatGrandparent = Bizavï¿œ +view_dynagroup_exprBuilder_resource_greatGreatGrandparent = Tataravï¿œ view_dynagroup_exprBuilder_resource_parent = Pai view_dynagroup_exprBuilder_resource_resource = Recurso -view_dynagroup_exprBuilder_resource_tooltip = Escolha o nível do recurso que deseja selecionar. Por exemplo, selecione "pai" para procurar por recursos filhos cujo recurso pai case com o resto da expressão. -view_dynagroup_exprBuilder_savedExpression = Expressão salva -view_dynagroup_exprBuilder_title = Construtor de expressão -view_dynagroup_exprBuilder_unset = Não definido -view_dynagroup_exprBuilder_unset_tooltip = Indefinido irá procurar todos os valores que possuem um valor nulo no banco de dados. Não é possível utilizar o operador "=" para valores indefinidos. -view_dynagroup_exprBuilder_value_tooltip = A string de pesquisa da expressão -view_dynagroup_expression = Expressão -view_dynagroup_expressionBuilderIconTooltip = Construtor de Expressão -view_dynagroup_expressionSet = Conjunto de Expressões -view_dynagroup_lastCalculationTime = Último cálculo -view_dynagroup_loadDefinitionFailure = Falha ao carregar as definições [{0}] -view_dynagroup_loadDefinitionMissing = Não existe definição para o grupo com ID [{0}] +view_dynagroup_exprBuilder_resource_tooltip = Escolha o nï¿œvel do recurso que deseja selecionar. Por exemplo, selecione "pai" para procurar por recursos filhos cujo recurso pai case com o resto da expressï¿œo. +view_dynagroup_exprBuilder_savedExpression = Expressï¿œo salva +view_dynagroup_exprBuilder_title = Construtor de expressï¿œo +view_dynagroup_exprBuilder_unset = Nï¿œo definido +view_dynagroup_exprBuilder_unset_tooltip = Indefinido irï¿œ procurar todos os valores que possuem um valor nulo no banco de dados. Nï¿œo ï¿œ possï¿œvel utilizar o operador "=" para valores indefinidos. +view_dynagroup_exprBuilder_value_tooltip = A string de pesquisa da expressï¿œo +view_dynagroup_expression = Expressï¿œo +view_dynagroup_expressionBuilderIconTooltip = Construtor de Expressï¿œo +view_dynagroup_expressionSet = Conjunto de Expressï¿œes +view_dynagroup_lastCalculationTime = ï¿œltimo cï¿œlculo +view_dynagroup_loadDefinitionFailure = Falha ao carregar as definiᅵᅵes [{0}] +view_dynagroup_loadDefinitionMissing = Nï¿œo existe definiᅵᅵo para o grupo com ID [{0}] view_dynagroup_mixed = Misturado -view_dynagroup_newGroupDefinition = Nova Definição de Grupo -view_dynagroup_nextCalculationTime = Próximo cálculo -view_dynagroup_permDenied = Você não possui permissões para visualizar o grupo -view_dynagroup_recalcFailure = Falha ao recalcular essa definição +view_dynagroup_newGroupDefinition = Nova Definiᅵᅵo de Grupo +view_dynagroup_nextCalculationTime = Prï¿œximo cï¿œlculo +view_dynagroup_permDenied = Vocï¿œ nï¿œo possui permissï¿œes para visualizar o grupo +view_dynagroup_recalcFailure = Falha ao recalcular essa definiᅵᅵo view_dynagroup_recalcFailureSelection = Failed to recalculated the selected group definitions view_dynagroup_recalcSuccessful = You have successfully recalculated this group definition view_dynagroup_recalcSuccessfulSelection = You have successfully recalculated [{0}] group definitions @@ -1928,7 +1931,7 @@ widget_resourceFactoryWizard_createSubmit = A requisi\u00E7\u00E3o para cria\u00 widget_resourceFactoryWizard_createSubmitType = A requisi\u00E7\u00E3o para cria\u00E7\u00E3o de um recurso do tipo [{0}] foi submetida com sucesso. widget_resourceFactoryWizard_createWizardTitle = Criar novo recurso do tipo [{0}] widget_resourceFactoryWizard_createWizardWindowTitle = Assistente para Cria\u00E7\u00E3o de Recurso -widget_resourceFactoryWizard_editConfigStepName = Opções de implantação +widget_resourceFactoryWizard_editConfigStepName = Opᅵᅵes de implantaᅵᅵo widget_resourceFactoryWizard_execute1 = Falha ao criar novo recurso - vers\u00E3o do pacote inexistente widget_resourceFactoryWizard_execute2 = Falha ao criar novo recurso widget_resourceFactoryWizard_failedToDeleteVersion = Falha ao excluir a vers\u00E3o do pacote durante o cancelamento da cria\u00E7\u00E3o do recurso @@ -1941,7 +1944,7 @@ widget_resourceFactoryWizard_infoStepName = Informa\u00E7\u00E3o do Recurso widget_resourceFactoryWizard_infoStep_loadFail = Falha ao recuperar Arquiteturas dispon\u00EDveis. widget_resourceFactoryWizard_namePrompt = Novo Nome do Recurso widget_resourceFactoryWizard_templatePrompt = Modelo de Propriedades para Conex\u00E3o -widget_resourceFactoryWizard_timeoutHelp = Duração do timeout. Se especificado irá sobrescrever o timeout padrão para criação de recursos filhos (no RHQ Agent). Útil principalmente para ações muito longas, como a implantação de uma aplição muito grande. Geralmente utilizado devido a tentativas que sofreram timeout anteriormente. +widget_resourceFactoryWizard_timeoutHelp = Duraᅵᅵo do timeout. Se especificado irï¿œ sobrescrever o timeout padrï¿œo para criaᅵᅵo de recursos filhos (no RHQ Agent). ï¿œtil principalmente para aᅵᅵes muito longas, como a implantaᅵᅵo de uma apliᅵᅵo muito grande. Geralmente utilizado devido a tentativas que sofreram timeout anteriormente. widget_resourceFactoryWizard_uploadFailure = Falha ao realizar o upload do arquivo widget_resourceFactoryWizard_uploadFileStepName = Upload do Arquivo do Recurso widget_resourceFactoryWizard_uploadInProgress = Upload em andamento... Esse processo pode demorar alguns minutos para ser finalizado em caso de arquivos muito grandes. 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 79816c5..4bda92e 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 @@ -1116,6 +1116,9 @@ view_dashboards_title = \u7edf\u8ba1\u8868\u76d8 ##view_drift_changeSets = Change Sets ##view_drift_changeSets_resourceViewTitle = Resource Drift Change Sets ##view_drift_changeset_tree_loadFailure = Failed to load drift change set tree. +##view_drift_delete_configConfirm = Delete the selected drift configuration(s)? +##view_drift_delete_configConfirmAll = Delete all drift configurations? +##view_drift_failure_deleteConfigs = Failed to delete some or all drift configurations. ##view_drift_table_baseDir = Base Directory ##view_drift_table_changeSet = Change Set ##view_drift_table_newFile = New 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 3ea9cf7..0e57f45 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 @@ -23,7 +23,6 @@ import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
import java.io.File; import java.io.InputStream; -import java.util.Iterator; import java.util.List;
import javax.ejb.EJB; @@ -55,10 +54,12 @@ 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.DriftConfigurationDefinition; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.DriftConfigurationComparator.CompareMode; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.RHQConstants; @@ -184,6 +185,7 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + @Deprecated public int deleteDrifts(Subject subject, String[] driftIds) { // avoid big transactions by doing this one at a time. if this is too slow we can chunk in bigger increments. int result = 0; @@ -246,6 +248,8 @@ public class DriftManagerBean implements DriftManagerLocal { @Override public void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName) {
+ // TODO security check! + switch (entityContext.getType()) { case Resource: int resourceId = entityContext.getResourceId(); @@ -254,24 +258,27 @@ public class DriftManagerBean implements DriftManagerLocal { throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); }
- for (Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = i.next(); + DriftConfiguration doomedDriftConfig = null; + for (DriftConfiguration dc : resource.getDriftConfigurations()) { if (dc.getName().equals(driftConfigName)) { - i.remove(); - entityManager.merge(resource); + doomedDriftConfig = dc; + break; + } + } + + if (doomedDriftConfig != null) { + resource.getDriftConfigurations().remove(doomedDriftConfig); + entityManager.remove(doomedDriftConfig); + entityManager.merge(resource);
+ try { AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService(); - try { - service.unscheduleDriftDetection(resourceId, dc); - } catch (Exception e) { - log.warn(" Unable to inform agent of unscheduled drift detection [" + dc + "]", e); - } - - break; + service.unscheduleDriftDetection(resourceId, doomedDriftConfig); + } catch (Exception e) { + log.warn(" Unable to inform agent of unscheduled drift detection [" + doomedDriftConfig + "]", e); } } - break;
default: @@ -367,12 +374,22 @@ public class DriftManagerBean implements DriftManagerLocal { }
// Update or add the driftConfig as necessary + DriftConfigurationComparator comparator = new DriftConfigurationComparator( + CompareMode.ONLY_INCLUDES_EXCLUDES); boolean isUpdated = false; for (DriftConfiguration dc : resource.getDriftConfigurations()) { if (dc.getName().equals(driftConfig.getName())) { - dc.setConfiguration(driftConfig.getConfiguration()); - isUpdated = true; - break; + // compare the includes/excludes filters only - if they are different, abort. + // you cannot update drift config that changes 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()); + isUpdated = true; + break; + } else { + throw new IllegalArgumentException( + "You cannot change an existing drift configuration's includes/excludes filters."); + } } }
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 3ac01b2..725c964 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 @@ -65,6 +65,7 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR * @param driftConfig * * @return the number of Drift records deleted + * @deprecated this will be removed, we will only support deleting changesets in the future */ int deleteDrifts(Subject subject, String[] driftIds);
commit cd4ad2d1d1a044faad89eeeffc53ec00463928b4 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 01:20:57 2011 -0400
be able to compare in three modes: 1. compare only base info (ignoring filters), 2. compare only filters (ignoring base info), 3. compare both base info and 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 index c88e5b1..a081157 100644 --- 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 @@ -37,46 +37,68 @@ import org.rhq.core.domain.drift.DriftConfiguration.Filter; */ public class DriftConfigurationComparator implements Comparator<DriftConfiguration> {
- private final boolean ignoreIncludesExcludes; - - public DriftConfigurationComparator(boolean ignoreIncludesExcludes) { - this.ignoreIncludesExcludes = ignoreIncludesExcludes; + public enum CompareMode { + /** + * The comparator will only check the base information: name, enabled, interval, basedirectory. + * The includes/excludes filters will be ignored. + */ + ONLY_BASE_INFO, + + /** + * The comparator will only check the includes/excludes filters. + * The base information will be ignored (see {@link #ONLY_BASE_INFO} for what those are). + */ + ONLY_INCLUDES_EXCLUDES, + + /** + * The comparator will check both the includes/excludes filters and + * the base information (see {@link #ONLY_BASE_INFO} for what those are). + */ + BOTH_BASE_INFO_AND_INCLUDES_EXCLUDES; + }; + + private final CompareMode compareMode; + + public DriftConfigurationComparator(CompareMode mode) { + this.compareMode = mode; }
@Override public int compare(DriftConfiguration dc1, DriftConfiguration dc2) { - if (dc1.getName() != null) { - if (dc2.getName() != null) { - int results = dc1.getName().compareTo(dc2.getName()); - if (results != 0) { - return results; + if (compareMode != CompareMode.ONLY_INCLUDES_EXCLUDES) { + 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 { - 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! } - } else if (dc2.getName() != null) { - return -1; // dc1's name is null, but dc2's name is not null, not equal! - }
- 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; + 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! } - } else if (dc2.getBasedir() != null) { - return -1; // dc1's basedir is null, but dc2's basedir is not null, not equal! - }
- if (dc1.getInterval() != dc2.getInterval()) { - return dc1.getInterval() < dc2.getInterval() ? -1 : 1; - } + if (dc1.getInterval() != dc2.getInterval()) { + return dc1.getInterval() < dc2.getInterval() ? -1 : 1; + }
- if (dc1.isEnabled() != dc2.isEnabled()) { - return dc1.isEnabled() ? 1 : -1; // so false sorts before true, seems logical to me + if (dc1.isEnabled() != dc2.isEnabled()) { + return dc1.isEnabled() ? 1 : -1; // so false sorts before true, seems logical to me + } }
- if (!this.ignoreIncludesExcludes) { + if (compareMode != CompareMode.ONLY_BASE_INFO) { List<Filter> filters1 = dc1.getIncludes(); List<Filter> filters2 = dc2.getIncludes(); int results = compareFilters(filters1, filters2); 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 dffc811..c4f2857 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,12 +15,13 @@ 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.DriftConfigurationDefinition.BaseDirValueContext;
public class DriftConfigurationTest { @Test public void getCompareIgnoreIncludesExcludes() { - DriftConfigurationComparator comparator = new DriftConfigurationComparator(true); + DriftConfigurationComparator comparator = new DriftConfigurationComparator(CompareMode.ONLY_BASE_INFO);
DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); DriftConfiguration dc2 = new DriftConfiguration(new Configuration()); @@ -74,13 +75,14 @@ public class DriftConfigurationTest { assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal (ignoring includes/excludes) " + dc2;
// now show that our non-ignoring comparator would detect a different - comparator = new DriftConfigurationComparator(false); + comparator = new DriftConfigurationComparator(CompareMode.BOTH_BASE_INFO_AND_INCLUDES_EXCLUDES); assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal (not ignoring includes/excludes) " + dc2; }
@Test - public void getCompareIncludesExcludes() { - DriftConfigurationComparator comparator = new DriftConfigurationComparator(false); + public void getCompareBaseInfoAndIncludesExcludes() { + DriftConfigurationComparator comparator = new DriftConfigurationComparator( + CompareMode.BOTH_BASE_INFO_AND_INCLUDES_EXCLUDES);
DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); DriftConfiguration dc2 = new DriftConfiguration(new Configuration()); @@ -95,6 +97,44 @@ public class DriftConfigurationTest { dc2.setInterval(1000L); dc2.setName("the-name");
+ getCompareBaseInfoAndIncludesExcludes(comparator, dc1, dc2); + } + + @Test + public void getCompareOnlyIncludesExcludes() { + DriftConfigurationComparator comparator = new DriftConfigurationComparator(CompareMode.ONLY_INCLUDES_EXCLUDES); + + DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); + DriftConfiguration dc2 = new DriftConfiguration(new Configuration()); + + dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.resourceConfiguration, "foo")); + dc1.setEnabled(false); + dc1.setInterval(1111L); + dc1.setName("some-name"); + + dc2.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); + dc2.setEnabled(true); + dc2.setInterval(2222L); + dc2.setName("another-name"); + + getCompareBaseInfoAndIncludesExcludes(comparator, dc1, dc2); + } + + /** + * Used by two main tests - we are to pass in a comparator that compares both base info + * and filters (with dc1 and dc2 having the same base info to make sure that data is compared too) + * and then we are to pass in a comparator that compares only the filters (with dc1 and + * dc2 having different base info to make sure that data is ignored). + * + * Note that when first called, comparator is assumed to see that dc1 and dc2 are the same. + * + * @param comparator used to test changes in filters + * @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) { + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check
dc1.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1"));
commit d7d4da5a8f6caa7e78c85b0929f9834a16e73996 Author: John Mazzitelli mazz@redhat.com Date: Fri Aug 12 01:04:18 2011 -0400
add API to add includes/excludes to drift config add ability to compare drift configs (either checking or ignoring includes/excludes)
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 b8be2b2..4f92e3b 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 @@ -54,8 +54,6 @@ import org.rhq.core.domain.resource.Resource; * * This object also has an optional relationship with a Resource. * - * TODO: this is missing setters for includes/excludes filters. We should add those. - * * @author John Sanda * @author John Mazzitelli * @author Jay Shaughnessy @@ -186,6 +184,16 @@ public class DriftConfiguration implements Serializable { } }
+ @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; @@ -301,7 +309,10 @@ public class DriftConfiguration implements Serializable {
@Override public int hashCode() { - return 13 * (path.hashCode() + pattern.hashCode()); + int result = 1; + result = 31 * result + path.hashCode(); + result = 31 * result + pattern.hashCode(); + return result; }
@Override @@ -323,6 +334,10 @@ public class DriftConfiguration implements Serializable {
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);
@@ -392,6 +407,34 @@ public class DriftConfiguration implements Serializable { 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) { 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 new file mode 100644 index 0000000..c88e5b1 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftConfigurationComparator.java @@ -0,0 +1,120 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.rhq.core.domain.drift; + +import java.util.Comparator; +import java.util.List; + +import org.rhq.core.domain.drift.DriftConfiguration.Filter; + +/** + * Compares two {@link DriftConfiguration} objects. The comparison can either + * compare includes/excludes filters or ignore them. Will also compare + * name, interval, enabled flag and base directory. + * + * @author John Mazzitelli + */ +public class DriftConfigurationComparator implements Comparator<DriftConfiguration> { + + private final boolean ignoreIncludesExcludes; + + public DriftConfigurationComparator(boolean ignoreIncludesExcludes) { + this.ignoreIncludesExcludes = ignoreIncludesExcludes; + } + + @Override + public int compare(DriftConfiguration dc1, DriftConfiguration dc2) { + 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.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! + } + + if (dc1.getInterval() != dc2.getInterval()) { + return dc1.getInterval() < dc2.getInterval() ? -1 : 1; + } + + if (dc1.isEnabled() != dc2.isEnabled()) { + return dc1.isEnabled() ? 1 : -1; // so false sorts before true, seems logical to me + } + + if (!this.ignoreIncludesExcludes) { + 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/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftConfigurationTest.java index 1440cf3..dffc811 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,9 +15,151 @@ 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.DriftConfigurationDefinition.BaseDirValueContext;
public class DriftConfigurationTest { @Test + public void getCompareIgnoreIncludesExcludes() { + DriftConfigurationComparator comparator = new DriftConfigurationComparator(true); + + DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); + DriftConfiguration dc2 = new DriftConfiguration(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; + dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.fileSystem, "/foo")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + dc1.setEnabled(true); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + dc1.setInterval(1000L); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + dc1.setName("the-name"); + 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.fileSystem, "/foo")); + dc2.setEnabled(true); + dc2.setInterval(1000L); + dc2.setName("the-name"); + + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; + + dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "/foo")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should have different basedir than " + dc2; + + dc1.setBasedir(dc2.getBasedir()); // put them back to the same value + dc1.setEnabled(!dc2.isEnabled()); + assert comparator.compare(dc1, dc2) < 0 : dc1 + " should have different enabled than " + dc2; + + dc1.setEnabled(dc2.isEnabled()); // put them back to the same value + dc1.setInterval(dc2.getInterval() + 2222L); + assert comparator.compare(dc1, dc2) > 0 : dc1 + " should have different interval than " + dc2; + + dc1.setInterval(dc2.getInterval()); // put them back to the same value + dc1.setName("zzzzz" + dc2.getName()); + assert comparator.compare(dc1, dc2) > 0 : dc1 + " should have different name than " + dc2; + + dc1.setName(dc2.getName()); // put them back to the same value + 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.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); + dc2.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); + dc1.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); + dc2.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal (ignoring includes/excludes) " + dc2; + + // now show that our non-ignoring comparator would detect a different + comparator = new DriftConfigurationComparator(false); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal (not ignoring includes/excludes) " + dc2; + } + + @Test + public void getCompareIncludesExcludes() { + DriftConfigurationComparator comparator = new DriftConfigurationComparator(false); + + DriftConfiguration dc1 = new DriftConfiguration(new Configuration()); + DriftConfiguration dc2 = new DriftConfiguration(new Configuration()); + + dc1.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); + dc1.setEnabled(true); + dc1.setInterval(1000L); + dc1.setName("the-name"); + + dc2.setBasedir(new DriftConfiguration.BaseDirectory(BaseDirValueContext.pluginConfiguration, "hello.world")); + dc2.setEnabled(true); + dc2.setInterval(1000L); + dc2.setName("the-name"); + + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check + + dc1.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + + dc2.addInclude(new DriftConfiguration.Filter("ipath1", "ipattern1")); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + + // add a second include to see that we test multiple filters + dc1.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + + dc2.addInclude(new DriftConfiguration.Filter("ipath2", "ipattern2")); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + + // side test just to see null patterns work + dc1.addInclude(new DriftConfiguration.Filter("ipath3", null)); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + + dc2.addInclude(new DriftConfiguration.Filter("ipath3", null)); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + + // now test excludes + + dc1.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + + dc2.addExclude(new DriftConfiguration.Filter("epath1", "epattern1")); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + + // add a second exclude to see that we test multiple filters + dc1.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + + dc2.addExclude(new DriftConfiguration.Filter("epath2", "epattern2")); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should now be equal " + dc2; + assert comparator.compare(dc2, dc1) == 0 : dc2 + " should now be equal " + dc1; + + // now test that we have the same number of filters but they differ + + dc1.addInclude(new DriftConfiguration.Filter("ipathA", "ipatternA")); + dc2.addInclude(new DriftConfiguration.Filter("ipathZ", "ipatternZ")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + 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()); + assert comparator.compare(dc1, dc2) == 0 : dc1 + " should equal " + dc2; // sanity check + dc1.addExclude(new DriftConfiguration.Filter("epathA", "epatternA")); + dc2.addExclude(new DriftConfiguration.Filter("epathZ", "epatternZ")); + assert comparator.compare(dc1, dc2) != 0 : dc1 + " should not equal " + dc2; + assert comparator.compare(dc2, dc1) != 0 : dc2 + " should not equal " + dc1; + } + + @Test public void getName() { String name = "test"; Configuration config = new Configuration(); @@ -108,11 +250,11 @@ public class DriftConfigurationTest { assertEquals(actual, expected, "Failed to get drift configuration excludes filters"); }
- PropertyMap newInclude(String path, String pattern) { + private PropertyMap newInclude(String path, String pattern) { return new PropertyMap("include", new PropertySimple("path", path), new PropertySimple("pattern", pattern)); }
- PropertyMap newExclude(String path, String pattern) { + private PropertyMap newExclude(String path, String pattern) { return new PropertyMap("exclude", new PropertySimple("path", path), new PropertySimple("pattern", pattern)); } }
commit fb70d8047ad5bc29929ededc58c7d14828edd05e Author: Ian Springer ian.springer@redhat.com Date: Thu Aug 11 15:42:12 2011 -0400
include MANAGE_DRIFT and CONFIGURE_READ in the permissions initially granted to the superuser and allResources roles during dbsetup; cosmetic formatting cleanup in ResourcePermission
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/authz-data.xml b/modules/core/dbutils/src/main/scripts/dbsetup/authz-data.xml index 99d0c00..d17e907 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/authz-data.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/authz-data.xml @@ -35,14 +35,15 @@
<!-- associate the root users with all security permissions --> <table name="RHQ_SUBJECT_ROLE_MAP"> - <data SUBJECT_ID="1" ROLE_ID="1"/> <!-- overlord user --> - <data SUBJECT_ID="2" ROLE_ID="1"/> + <data SUBJECT_ID="1" ROLE_ID="1"/> <!-- rhqadmin user --> + <data SUBJECT_ID="2" ROLE_ID="1"/> </table>
<table name="RHQ_PERMISSION"> - <!-- give super-user-role all permissions (resource perms is mainly just to show on view-role page) --> + <!-- give super-user-role all permissions + (explicitly add resource perms, even though they are implied by MANAGE_INVENTORY) --> <data ROLE_ID="1" OPERATION="0"/> <!-- Permission.MANAGE_SECURITY --> <data ROLE_ID="1" OPERATION="1"/> <!-- Permission.MANAGE_INVENTORY --> <data ROLE_ID="1" OPERATION="2"/> <!-- Permission.MANAGE_SETTINGS --> @@ -57,10 +58,13 @@ <data ROLE_ID="1" OPERATION="8"/> <!-- Permission.MANAGE_MEASUREMENTS --> <data ROLE_ID="1" OPERATION="9"/> <!-- Permission.MANAGE_CONTENT --> <data ROLE_ID="1" OPERATION="10"/> <!-- Permission.CONTROL --> - <data ROLE_ID="1" OPERATION="11"/> <!-- Permission.CONFIGURE --> + <data ROLE_ID="1" OPERATION="11"/> <!-- Permission.CONFIGURE_WRITE --> + <data ROLE_ID="1" OPERATION="13"/> <!-- Permission.CONFIGURE_READ --> <data ROLE_ID="1" OPERATION="14"/> <!-- Permission.MANAGE_EVENTS --> + <data ROLE_ID="1" OPERATION="16"/> <!-- Permission.MANAGE_DRIFT -->
- <!-- give all-resources-role all permissions (resource perms is mainly just to show on view-role page) --> + <!-- give all-resources-role MANAGE_INVENTORY and MANAGE_BUNDLE permissions + (explicitly add resource perms as well, even though they are implied by MANAGE_INVENTORY) --> <data ROLE_ID="2" OPERATION="1"/> <!-- Permission.MANAGE_INVENTORY --> <data ROLE_ID="2" OPERATION="12"/> <!-- Permission.MANAGE_BUNDLE --> <!-- resource permissions start here--> @@ -72,8 +76,10 @@ <data ROLE_ID="2" OPERATION="8"/> <!-- Permission.MANAGE_MEASUREMENTS --> <data ROLE_ID="2" OPERATION="9"/> <!-- Permission.MANAGE_CONTENT --> <data ROLE_ID="2" OPERATION="10"/> <!-- Permission.CONTROL --> - <data ROLE_ID="2" OPERATION="11"/> <!-- Permission.CONFIGURE --> + <data ROLE_ID="2" OPERATION="11"/> <!-- Permission.CONFIGURE_WRITE --> + <data ROLE_ID="2" OPERATION="13"/> <!-- Permission.CONFIGURE_READ --> <data ROLE_ID="2" OPERATION="14"/> <!-- Permission.MANAGE_EVENTS --> + <data ROLE_ID="2" OPERATION="16"/> <!-- Permission.MANAGE_DRIFT --> </table>
</dbsetup> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourcePermission.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourcePermission.java index 5f53af5..265fc4b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourcePermission.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourcePermission.java @@ -49,7 +49,7 @@ public class ResourcePermission implements Serializable { this.permissions = Permission.RESOURCE_ALL; }
- public ResourcePermission(// + public ResourcePermission( // boolean measure, // boolean inventory, // boolean control, // @@ -58,8 +58,9 @@ public class ResourcePermission implements Serializable { boolean configureRead, // boolean configureWrite, // boolean content, // - boolean createChildResources,// - boolean deleteResource, boolean drift) { + boolean createChildResources, // + boolean deleteResource, // + boolean drift) {
this.permissions = new HashSet<Permission>();
commit b7d5d48dc2f7d038f3ef1f8eecd078f05c21adbb Author: Ian Springer ian.springer@redhat.com Date: Thu Aug 11 15:40:44 2011 -0400
[BZ 729965] fix regression where a non-admin user would get an exception if they tried to view a Resource they are authorized to view (https://bugzilla.redhat.com/show_bug.cgi?id=729965)
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 f0b1308..16fd8e6 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 @@ -2438,7 +2438,8 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 11 ), " // CONFIGURE_WRITE + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 9 ), " // MANAGE_CONTENT + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 6 ), " // CREATE_CHILD_RESOURCES - + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 5 ))"; // DELETE_RESOURCES + + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 5 ), " // DELETE_RESOURCES + + " ( SELECT count(p) FROM %alias%.implicitGroups g JOIN g.roles r JOIN r.subjects s JOIN r.permissions p WHERE s.id = %subjectId% AND p = 16 ))"; // MANAGE_DRIFT compositeProjection = compositeProjection.replace("%subjectId%", String.valueOf(subject.getId())); } compositeProjection = compositeProjection.replace("%alias%", criteria.getAlias());
commit 5134f1e7f56086a377a74203cdb829b84187fc5b Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 11 15:00:50 2011 -0400
[BZ - 730065 - (Drift) Detail views don't go away when navigating directly to a new subtab] Fix an issue where an existing but not visible details view was not properly cleaned up.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java index 7178269..3223cad 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/AbstractTableSection.java @@ -387,6 +387,8 @@ public abstract class AbstractTableSection<DS extends RPCDataSource, ID> extends Log.debug("Refreshing data for Table [" + getClass().getName() + "]..."); refresh(); } + // if the detailsHolder is visible then gracefully switch views, otherwise just + // clean up any lingering details holder and show the table view. if (detailsHolder != null && detailsHolder.isVisible()) { detailsHolder.animateHide(AnimationEffect.WIPE, new AnimationCallback() { @Override @@ -397,6 +399,9 @@ public abstract class AbstractTableSection<DS extends RPCDataSource, ID> extends } }); } else { + if (detailsHolder != null) { + SeleniumUtility.destroyMembers(detailsHolder); + } contents.animateShow(AnimationEffect.WIPE); } }
commit 4e2cb62bacb2cdd76494d907f5ce06437e1846aa Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 11 13:35:34 2011 -0400
add tests
diff --git a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java index 8757540..fc27760 100644 --- a/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java +++ b/modules/common/ant-bundle/src/test/java/org/rhq/bundle/ant/type/AbstractBundleTypeTest.java @@ -23,6 +23,8 @@
package org.rhq.bundle.ant.type;
+import java.util.ArrayList; +import java.util.List; import java.util.regex.Pattern;
import org.testng.annotations.Test; @@ -32,6 +34,72 @@ public class AbstractBundleTypeTest { public void testGetPattern() { Pattern regex;
+ regex = assertPatternsRegex("/basedir", "(/basedir/(easy\.txt))|(/basedir/(test\.txt))", "easy.txt", + "test.txt"); + assert regex.matcher("/basedir/easy.txt").matches(); + assert regex.matcher("/basedir/test.txt").matches(); + assert !regex.matcher("/basedir/easyXtxt").matches(); + assert !regex.matcher("/basedir/testXtxt").matches(); + assert !regex.matcher("/basedir/easy.txtX").matches(); + assert !regex.matcher("/basedir/test.txtX").matches(); + assert !regex.matcher("/basedirX/easy.txt").matches(); + assert !regex.matcher("/basedirX/test.txt").matches(); + assert !regex.matcher("easy.txt").matches() : "missing basedir"; + assert !regex.matcher("test.txt").matches() : "missing basedir"; + + regex = assertPatternsRegex("AB CD", "(AB CD/([^/]*\.txt))|(AB CD/(test\.[^/]*))", "*.txt", "test.*"); + assert regex.matcher("AB CD/easy.txt").matches(); + assert regex.matcher("AB CD/test.xml").matches(); + assert regex.matcher("AB CD/test.txt").matches(); + assert regex.matcher("AB CD/test.").matches(); + assert regex.matcher("AB CD/test.wotgorilla?").matches(); + assert regex.matcher("AB CD/.txt").matches(); + assert !regex.matcher("AB CD/txt").matches(); + assert !regex.matcher("AB CD/Xtxt").matches(); + assert !regex.matcher("AB CD/testX").matches() : "missing the dot"; + assert !regex.matcher("AB CD/easy.txtX").matches(); + assert !regex.matcher("AB CDX/easy.txt").matches(); + assert !regex.matcher("AB CDX/test.xml").matches(); + assert !regex.matcher("easy.txt").matches() : "missing basedir"; + assert !regex.matcher("test.txt").matches() : "missing basedir"; + + regex = assertPatternsRegex("A", "(A/(.*.\.txt))|(A/(sub/.*[^/]*\.xml))", "**/?.txt", "sub/**/*.xml"); + assert regex.matcher("A/1.txt").matches(); + assert regex.matcher("A/BB/CCC/1.txt").matches(); + //assert !regex.matcher("A/12.txt").matches(); // TODO: THIS ASSERT FAILS! FIX THIS!! + //assert !regex.matcher("A/B/C/12.txt").matches(); // TODO: THIS ASSERT FAILS! FIX THIS!! + assert regex.matcher("A/sub/foo.xml").matches(); + assert regex.matcher("A/sub/BB/CCC/1.xml").matches(); + assert regex.matcher("A/sub/.xml").matches(); + assert !regex.matcher("A/.txt").matches() : "? infers at least one and only one - this has nothing to match the ?"; + assert !regex.matcher("A/1.txtX").matches(); + assert !regex.matcher("A/subX/foo.xml").matches(); + assert !regex.matcher("A/subX/BB/CCC/1.xml").matches(); + assert !regex.matcher("A/sub/foo.xmlX").matches(); + assert !regex.matcher("1.txt").matches() : "missing basedir"; + assert !regex.matcher("sub/foo.xml").matches() : "missing basedir"; + } + + private Pattern assertPatternsRegex(String baseDir, String expectedPattern, String... patterns) { + List<FileSet> fileSets = new ArrayList<FileSet>(); + for (String pattern : patterns) { + FileSet fileSet = new FileSet(); + fileSet.setIncludes(pattern); + fileSet.setDir(baseDir); + fileSets.add(fileSet); + } + Pattern regex = AbstractBundleType.getPattern(fileSets); + + assert regex != null : "The regex was not able to be produced - it was null"; + assert expectedPattern.equals(regex.pattern()) : "The expected pattern [" + expectedPattern + + "] did not match the actual pattern [" + regex.pattern() + "]"; + + return regex; + } + + public void testBuildIncludePatternRegex() { + Pattern regex; + regex = assertIncludePatternRegex("easy.txt", "easy\.txt", "easy.txt"); assert !regex.matcher("easyXtxt").matches() : "should not have matched, is the . escaped?"; assert !regex.matcher("Xeasy.txt").matches();
commit d4c783edf61fe52b6560f1e3c2b548eff864547e Merge: c803094 c0ba25b Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 11 16:04:34 2011 +0200
Merge remote-tracking branch 'origin/master' into feature/config-sync
commit c803094678b5e84f7c3a6fd85a5a226a7c664c7f Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 11 15:16:21 2011 +0200
Added a bunch of tests for metric template importer.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index dc09ef0..eefb452 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -63,13 +63,13 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M private static final Log LOG = LogFactory.getLog(MetricTemplateImporter.class);
private static final boolean UPDATE_SCHEDULES_DEFAULT = false; - private static final String UPDATE_ALL_SCHEDULES_PROPERTY = "updateAllSchedules"; - private static final String METRIC_NAME_PROPERTY = "metricName"; - private static final String RESOURCE_TYPE_NAME_PROPERTY = "resourceTypeName"; - private static final String RESOURCE_TYPE_PLUGIN_PROPERTY = "resourceTypePlugin"; - private static final String UPDATE_SCHEDULES_PROPERTY = "updateSchedules"; - private static final String METRIC_UPDATE_OVERRIDES_PROPERTY = "metricUpdateOverrides"; - private static final String METRIC_UPDATE_OVERRIDE = "metricUpdateOverride"; + public static final String UPDATE_ALL_SCHEDULES_PROPERTY = "updateAllSchedules"; + public static final String METRIC_NAME_PROPERTY = "metricName"; + public static final String RESOURCE_TYPE_NAME_PROPERTY = "resourceTypeName"; + public static final String RESOURCE_TYPE_PLUGIN_PROPERTY = "resourceTypePlugin"; + public static final String UPDATE_SCHEDULES_PROPERTY = "updateSchedules"; + public static final String METRIC_UPDATE_OVERRIDES_PROPERTY = "metricUpdateOverrides"; + public static final String METRIC_UPDATE_OVERRIDE_PROPERTY = "metricUpdateOverride";
private static class CollectionIntervalAndUpdateSchedules { public long collectionInterval; @@ -134,7 +134,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M PropertyDefinitionSimple resourceTypePlugin = new PropertyDefinitionSimple(RESOURCE_TYPE_PLUGIN_PROPERTY, "The name of the plugin defining the resource type that defines the metric", true, PropertySimpleType.STRING); PropertyDefinitionSimple updateSchedules = new PropertyDefinitionSimple(UPDATE_SCHEDULES_PROPERTY, "Whether to update the schedules of this metric on existing resources", true, PropertySimpleType.BOOLEAN);
- PropertyDefinitionMap metricUpdateOverride = new PropertyDefinitionMap(METRIC_UPDATE_OVERRIDE, null, true, metricName, resourceTypeName, resourceTypePlugin, updateSchedules); + PropertyDefinitionMap metricUpdateOverride = new PropertyDefinitionMap(METRIC_UPDATE_OVERRIDE_PROPERTY, null, true, metricName, resourceTypeName, resourceTypePlugin, updateSchedules); PropertyDefinitionList metricUpdateOverrides = new PropertyDefinitionList(METRIC_UPDATE_OVERRIDES_PROPERTY, "Per metric settings", false, metricUpdateOverride);
def.put(metricUpdateOverrides); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java index 78c9d29..e792c0e 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java @@ -23,15 +23,25 @@ import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame;
import java.util.Collections; +import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.Query;
+import org.hamcrest.Description; import org.jmock.Expectations; +import org.jmock.Mockery; +import org.jmock.api.Action; +import org.jmock.api.Invocation; 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.PropertyList; +import org.rhq.core.domain.configuration.PropertyMap; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.measurement.NumericType; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.sync.entity.MetricTemplate; @@ -41,78 +51,384 @@ import org.rhq.enterprise.server.sync.importers.MetricTemplateImporter; import org.rhq.test.JMockTest;
/** - * TODO fix the bug in the importer that doesn't disable the schedules - * * @author Lukas Krejci */ @Test public class MetricTemplateImporterTest extends JMockTest {
+ private static class TestPrerequisities { + private EntityManager em; + private Query q; + private MeasurementScheduleManagerLocal msm; + private List<MeasurementDefinition>[] consecutiveMatchingResults; + private boolean expectationsOnQueryParameters = true; + + private class ReturnNextResultAction implements Action { + private int currentIndex = 0; + + @Override + public void describeTo(Description descr) { + descr.appendText("Returning the result of a faked query for matching measurement definitions: "); + if (currentIndex < consecutiveMatchingResults.length) { + descr.appendValue(consecutiveMatchingResults[currentIndex]); + } else { + descr.appendText("already returned all available results. Current index is ") + .appendText(Integer.toString(currentIndex)).appendText(" while only ") + .appendText(Integer.toString(consecutiveMatchingResults.length)) + .appendText(" results are available."); + } + } + + @Override + public Object invoke(Invocation invocation) throws Throwable { + return consecutiveMatchingResults[currentIndex++]; + } + + } + + public TestPrerequisities(Mockery context) { + em = context.mock(EntityManager.class); + msm = context.mock(MeasurementScheduleManagerLocal.class); + q = context.mock(Query.class); + } + + public Query getQuery() { + return q; + } + + public EntityManager getEntityManager() { + return em; + } + + public MeasurementScheduleManagerLocal getMeasurementScheduleManager() { + return msm; + } + + public void setConsecutiveResultsOfMatchingQuery(List<MeasurementDefinition>... consecutiveResults) { + consecutiveMatchingResults = consecutiveResults; + } + + public void setExpectationsOnQueryParameters(boolean value) { + expectationsOnQueryParameters = value; + } + + public void addExpectations(Expectations expectations) { + expectations.allowing(em).createNamedQuery( + expectations.with(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME)); + expectations.will(Expectations.returnValue(q)); + + if (expectationsOnQueryParameters) { + expectations.allowing(q).setParameter(expectations.with(Expectations.any(String.class)), + expectations.with(Expectations.any(Object.class))); + } + + expectations.allowing(q).getResultList(); + expectations.will(new ReturnNextResultAction()); + } + }; + + private static final ResourceType FAKE_RESOURCE_TYPE = new ResourceType("fake", "fake", ResourceCategory.PLATFORM, + null); + + @SuppressWarnings("unchecked") public void testNonMatchingMeasurementDefinitionsAreIgnored() { - //mocks we are going to need - final EntityManager em = context.mock(EntityManager.class); - final MeasurementScheduleManagerLocal msm = context.mock(MeasurementScheduleManagerLocal.class); + final TestPrerequisities prereqs = new TestPrerequisities(context);
//some data to supply - final ResourceType rt = new ResourceType("fake", "fake", ResourceCategory.PLATFORM, null); - final MeasurementDefinition def = new MeasurementDefinition(rt, "fake"); + MeasurementDefinition def = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "fake"); def.setId(1); def.setDefaultOn(true); - + def.setDefaultInterval(1000); + //setup the expected behavior context.checking(new Expectations() { { - Query q = context.mock(Query.class); - - //fake the entity manager returning no results for the first metric template - //we try to import and the def for the second metric template we import - - allowing(em).createNamedQuery(with(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME)); - will(returnValue(q)); - - allowing(q).setParameter(with(any(String.class)), with(any(Object.class))); - allowing(q).getResultList(); - will(onConsecutiveCalls(returnValue(Collections.emptyList()), returnValue(Collections.singletonList(def)))); - + prereqs.addExpectations(this); + + MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager(); + //this is what we expect the measurement schedule manager msm to be - //called with with the importer finishes its work. + //called with when the importer finishes its work. one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); - } + one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(false)); + } }); - - MetricTemplateImporter importer = new MetricTemplateImporter(null, em, msm); - + + MetricTemplateImporter importer = + new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager()); + MetricTemplate nonMatching = new MetricTemplate(); - MetricTemplate matching = new MetricTemplate(def); - + MetricTemplate matching = new MetricTemplate(def); + + //now we setup the prerequisites to return the faked results from the database + //for the non-matching template, we want the "database" to return no results + //while for the matching template, we want the "database" to return our own def. + prereqs.setConsecutiveResultsOfMatchingQuery(Collections.<MeasurementDefinition> emptyList(), + Collections.singletonList(def)); + importer.configure(null); - + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); - + assertNull(matcher.findMatch(nonMatching), "The non-matching metric template shouldn't have been matched."); - assertSame(matcher.findMatch(matching), def, "The matching metric template should have found the defined measurement definition"); - + assertSame(matcher.findMatch(matching), def, + "The matching metric template should have found the defined measurement definition"); + + //this is the "meat" of the test.. + //we call update() twice but only get 1 actual change pour down to database + //and the importer not choking on this. importer.update(null, nonMatching); importer.update(def, matching); - + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called //correctly by the importer. importer.finishImport(); } - + + @SuppressWarnings("unchecked") public void testCanUpdateEnablements() { - + MeasurementDefinition defToEnable = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "enabled"); + MeasurementDefinition defToDisable = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "disable"); + + defToEnable.setId(1); + defToEnable.setDefaultOn(true); + defToEnable.setDefaultInterval(1000); + + defToDisable.setId(2); + defToDisable.setDefaultOn(false); + defToDisable.setDefaultInterval(2000); + + final TestPrerequisities prereqs = new TestPrerequisities(context); + + context.checking(new Expectations() { + { + prereqs.addExpectations(this); + MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager(); + + //this is what we expect the measurement schedule manager msm to be + //called with when the importer finishes its work. + one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); + one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 2 })); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(false)); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(false)); + } + }); + + prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(defToEnable), + Collections.singletonList(defToDisable)); + + MetricTemplateImporter importer = + new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager()); + + importer.configure(null); + + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); + + MetricTemplate match1 = new MetricTemplate(defToEnable); + MetricTemplate match2 = new MetricTemplate(defToDisable); + + assertSame(matcher.findMatch(match1), defToEnable, + "The matching metric template should have found the defined measurement definition"); + assertSame(matcher.findMatch(match2), defToDisable, + "The matching metric template should have found the defined measurement definition"); + + importer.update(defToEnable, match1); + importer.update(defToDisable, match2); + + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called + //correctly by the importer. + importer.finishImport(); + } - + + @SuppressWarnings("unchecked") public void testCanUpdateSchedules() { - - } - - public void testGlobalUpdateSchedulesSwitch() { - + MeasurementDefinition def = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "def"); + def.setId(1); + def.setDefaultOn(true); + def.setDefaultInterval(1000); + + final TestPrerequisities prereqs = new TestPrerequisities(context); + + context.checking(new Expectations() { + { + prereqs.addExpectations(this); + + MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager(); + + one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); + one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true)); + } + }); + + prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(def)); + + MetricTemplateImporter importer = + new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager()); + + Configuration importConfig = new Configuration(); + importConfig.put(new PropertySimple(MetricTemplateImporter.UPDATE_ALL_SCHEDULES_PROPERTY, true)); + + importer.configure(importConfig); + + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); + + MetricTemplate template = new MetricTemplate(def); + + assertSame(matcher.findMatch(template), def, + "The matching metric template should have found the defined measurement definition"); + + importer.update(def, template); + + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called + //correctly by the importer. + importer.finishImport(); } - + + @SuppressWarnings("unchecked") public void testPerMetricUpdateScheduleOverrides() { + MeasurementDefinition updatedDef = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "def"); + updatedDef.setId(1); + updatedDef.setDefaultOn(true); + updatedDef.setDefaultInterval(1000); + MeasurementDefinition notUpdatedDef = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "ndef"); + notUpdatedDef.setId(2); + notUpdatedDef.setDefaultOn(true); + notUpdatedDef.setDefaultInterval(2000); + + final TestPrerequisities prereqs = new TestPrerequisities(context); + + context.checking(new Expectations() { + { + prereqs.addExpectations(this); + + MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager(); + + one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1, 2 })); + one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[0])); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(true)); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(false)); + } + }); + + prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(updatedDef), + Collections.singletonList(notUpdatedDef)); + + MetricTemplateImporter importer = + new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager()); + + Configuration importConfig = new Configuration(); + + //this is the default, but let's be specific here so that this doesn't start failing if we change the + //default in the future. + importConfig.put(new PropertySimple(MetricTemplateImporter.UPDATE_ALL_SCHEDULES_PROPERTY, false)); + + //set the def to update the schedules anyway + PropertyList list = new PropertyList(MetricTemplateImporter.METRIC_UPDATE_OVERRIDES_PROPERTY); + importConfig.put(list); + PropertyMap map = new PropertyMap(MetricTemplateImporter.METRIC_UPDATE_OVERRIDE_PROPERTY); + list.add(map); + map.put(new PropertySimple(MetricTemplateImporter.METRIC_NAME_PROPERTY, "def")); + map.put(new PropertySimple(MetricTemplateImporter.RESOURCE_TYPE_NAME_PROPERTY, FAKE_RESOURCE_TYPE.getName())); + map.put(new PropertySimple(MetricTemplateImporter.RESOURCE_TYPE_PLUGIN_PROPERTY, FAKE_RESOURCE_TYPE.getPlugin())); + map.put(new PropertySimple(MetricTemplateImporter.UPDATE_SCHEDULES_PROPERTY, true)); + + importer.configure(importConfig); + + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); + + MetricTemplate template1 = new MetricTemplate(updatedDef); + MetricTemplate template2 = new MetricTemplate(notUpdatedDef); + + assertSame(matcher.findMatch(template1), updatedDef, + "The matching metric template should have found the defined measurement definition"); + assertSame(matcher.findMatch(template2), notUpdatedDef, + "The matching metric template should have found the defined measurement definition"); + + importer.update(updatedDef, template1); + importer.update(notUpdatedDef, template2); + + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called + //correctly by the importer. + importer.finishImport(); + } + + public void testNullConfigurationInterpretedAsDefault() { + //this doesn't need to be implemented as long as at least one of the other + //test methods passes null to the importer.configure() and succeeds. + testNonMatchingMeasurementDefinitionsAreIgnored(); + } + + @SuppressWarnings("unchecked") + public void testDistinguishingBetweenNormalAndPerMinuteTemplates() { + MeasurementDefinition normalDef = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "def"); + MeasurementDefinition perMinuteDef = new MeasurementDefinition(FAKE_RESOURCE_TYPE, "def"); + + normalDef.setId(1); + normalDef.setDefaultOn(true); + normalDef.setDefaultInterval(1000); + + perMinuteDef.setId(2); + perMinuteDef.setDefaultOn(false); + perMinuteDef.setDefaultInterval(2000); + perMinuteDef.setRawNumericType(NumericType.TRENDSUP);
+ final TestPrerequisities prereqs = new TestPrerequisities(context); + prereqs.setExpectationsOnQueryParameters(false); + + context.checking(new Expectations() { + { + prereqs.setExpectationsOnQueryParameters(false); + prereqs.addExpectations(this); + + exactly(2).of(prereqs.getQuery()).setParameter(with("name"), with(any(Object.class))); + exactly(2).of(prereqs.getQuery()).setParameter(with("resourceTypeName"), with(any(Object.class))); + exactly(2).of(prereqs.getQuery()).setParameter(with("resourceTypePlugin"), with(any(Object.class))); + oneOf(prereqs.getQuery()).setParameter(with("perMinute"), with(0)); + oneOf(prereqs.getQuery()).setParameter(with("perMinute"), with(1)); + + MeasurementScheduleManagerLocal msm = prereqs.getMeasurementScheduleManager(); + + one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); + one(msm).disableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 2 })); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 1 }), with(1000L), with(false)); + one(msm).updateDefaultCollectionIntervalForMeasurementDefinitions(with(any(Subject.class)), + with(new int[] { 2 }), with(2000L), with(false)); + } + }); + + prereqs.setConsecutiveResultsOfMatchingQuery(Collections.singletonList(normalDef), + Collections.singletonList(perMinuteDef)); + + MetricTemplateImporter importer = + new MetricTemplateImporter(null, prereqs.getEntityManager(), prereqs.getMeasurementScheduleManager()); + + importer.configure(null); + + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); + + MetricTemplate template1 = new MetricTemplate(normalDef); + MetricTemplate template2 = new MetricTemplate(perMinuteDef); + + assertSame(matcher.findMatch(template1), normalDef, + "The matching metric template should have found the defined measurement definition"); + assertSame(matcher.findMatch(template2), perMinuteDef, + "The matching metric template should have found the defined measurement definition"); + + importer.update(normalDef, template1); + importer.update(perMinuteDef, template2); + + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called + //correctly by the importer. + importer.finishImport(); } }
commit afdad06ba4760825ab70934572ceb2d09548edad Author: Lukas Krejci lkrejci@redhat.com Date: Thu Aug 11 15:15:29 2011 +0200
When updateAllSchedules property was explicitly set to false, the per-metric overrides weren't considered.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index 66caf35..dc09ef0 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -254,7 +254,9 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
String updateAll = importConfiguration.getSimpleValue(UPDATE_ALL_SCHEDULES_PROPERTY, null); if (updateAll != null) { - return Boolean.parseBoolean(updateAll); + if(Boolean.parseBoolean(updateAll)) { + return true; + } }
PropertyList perMetricOverrides = importConfiguration.getList(METRIC_UPDATE_OVERRIDES_PROPERTY);
commit b9a4732396aa7df4933cc859ab06d2e30396285a Author: John Sanda jsanda@redhat.com Date: Wed Aug 10 22:11:16 2011 -0400
Initial support for persisting drift file entities in mongodb
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 ef4a185..737d2c1 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 @@ -42,6 +42,10 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil @Transient private MongoDBChangeSet changeSet;
+ private MongoDBFile oldFile; + + private MongoDBFile newFile; + public MongoDBChangeSetEntry() { }
@@ -139,19 +143,21 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Override public MongoDBFile getOldDriftFile() { - return null; + return oldFile; }
@Override public void setOldDriftFile(MongoDBFile oldDriftFile) { + oldFile = oldDriftFile; }
@Override public MongoDBFile getNewDriftFile() { - return null; + return newFile; }
@Override public void setNewDriftFile(MongoDBFile newDriftFile) { + newFile = newDriftFile; } } diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java index 6a40465..b771ae3 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java @@ -2,53 +2,56 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.entities;
import java.io.Serializable;
-import com.google.code.morphia.annotations.Entity; -import com.google.code.morphia.annotations.Id; +import com.google.code.morphia.annotations.Embedded;
import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus;
-@Entity +@Embedded public class MongoDBFile implements Serializable, DriftFile {
private static final long serialVersionUID = 1L;
- @SuppressWarnings("unused") - @Id private String hash;
+ private Long ctime = System.currentTimeMillis(); + + private Long size; + + private DriftFileStatus status; + @Override public String getHashId() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return hash; }
@Override public void setHashId(String hashId) { - //To change body of implemented methods use File | Settings | File Templates. + hash = hashId; }
@Override public Long getCtime() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return ctime; }
@Override public Long getDataSize() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return size; }
@Override public void setDataSize(Long size) { - //To change body of implemented methods use File | Settings | File Templates. + this.size = size; }
@Override public DriftFileStatus getStatus() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return status; }
@Override public void setStatus(DriftFileStatus status) { - //To change body of implemented methods use File | Settings | File Templates. + this.status = status; } } 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 93fde79..9f2ed2a 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 @@ -42,6 +42,7 @@ import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED; import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED; import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; +import static org.rhq.core.domain.drift.DriftFileStatus.EMPTY; import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder; import static org.rhq.test.AssertUtils.assertPropertiesMatch; import static org.testng.Assert.assertNotNull; @@ -51,7 +52,7 @@ public class ChangeSetDAOTest {
// Tests need to be disabled when committed/pushed to the remote repo until we get // mongodb installed on the hudson slave - static final boolean ENABLED = false; + static final boolean ENABLED = true;
Mongo connection;
@@ -96,13 +97,24 @@ public class ChangeSetDAOTest { }
@Test(enabled = ENABLED) - public void saveAndLoadChangeSetWithOneEntry() throws Exception { + public void saveAndLoadChangeSetWithAddedFileEntry() throws Exception { MongoDBChangeSet expected = new MongoDBChangeSet(); expected.setCategory(DRIFT); expected.setResourceId(1); expected.setDriftConfigurationId(1); expected.setVersion(1); - expected.add(new MongoDBChangeSetEntry("foo", FILE_ADDED)); + + MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(); + entry.setCategory(FILE_ADDED); + entry.setPath("foo"); + + MongoDBFile file = new MongoDBFile(); + file.setDataSize(1024L); + file.setHashId("a1b2c3d4"); + file.setStatus(EMPTY); + + entry.setNewDriftFile(file); + expected.add(entry);
dao.save(expected);
commit 0b67a1e97a1f23157b0b87307ac4ca0aad916844 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 10 17:39:11 2011 -0400
enforce the name convention in the SLSB - this protects the name when creating drift configs outside of the GWT UI (such as from a CLI client)
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 36551ca..a409e1f 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 @@ -57,6 +57,11 @@ public class DriftConfigurationDefinition implements Serializable { public static final String PROP_PATH = "path"; // for both include and exclude public static final String PROP_PATTERN = "pattern"; // for both include and exclude
+ // because we know drift config names will actually be used by the agent's plugin container as directories names, + // we must make sure they are restricted to only be characters valid for file system pathnames. + // Thus, we only allow config names to only include spaces or "." or "-" or alphanumeric or "_" characters. + public static final String PROP_NAME_REGEX_PATTERN = "[ \.\-\w]+"; + public static final boolean DEFAULT_ENABLED = false; public static final long DEFAULT_INTERVAL = 1800L;
@@ -108,11 +113,7 @@ public class DriftConfigurationDefinition implements Serializable { pd.setConfigurationDefinition(INSTANCE);
RegexConstraint constrait = new RegexConstraint(); - // because we know these names will actually be used by the agent's plugin container as directories names, - // we must make sure they are restricted to only be characters valid for file system pathnames. - // Thus, we only allow config names to only include spaces or "." or "-" or alphanumeric or "_" characters. - String pattern = "[ \.\-\w]+"; - constrait.setDetails(pattern); + constrait.setDetails(PROP_NAME_REGEX_PATTERN); pd.addConstraints(constrait);
return pd; 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 e7cd21d..3ea9cf7 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 @@ -55,6 +55,7 @@ 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.DriftConfigurationDefinition; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.drift.JPADrift; @@ -350,6 +351,13 @@ public class DriftManagerBean implements DriftManagerLocal {
@Override public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) { + + // before we do anything, make sure the drift config name is valid + if (!driftConfig.getName().matches(DriftConfigurationDefinition.PROP_NAME_REGEX_PATTERN)) { + throw new IllegalArgumentException("Drift configuration name contains invalid characters: " + + driftConfig.getName()); + } + switch (entityContext.getType()) { case Resource: int resourceId = entityContext.getResourceId(); @@ -360,8 +368,7 @@ public class DriftManagerBean implements DriftManagerLocal {
// Update or add the driftConfig as necessary boolean isUpdated = false; - for (Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = i.next(); + for (DriftConfiguration dc : resource.getDriftConfigurations()) { if (dc.getName().equals(driftConfig.getName())) { dc.setConfiguration(driftConfig.getConfiguration()); isUpdated = true;
commit 3e27a645226607b0c629070e02eee1fc3dd09eda Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 10 17:31:49 2011 -0400
explicitly declare "throws RuntimeException" so GWT can properly receive exceptions from the server
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 ff195c8..60065d9 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 @@ -147,6 +147,6 @@ public interface DriftGWTService extends RemoteService { * @param entityContext * @param driftConfig */ - void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig); + void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig) 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 f1ea5db..95e6d19 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 @@ -83,7 +83,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public void detectDrift(EntityContext entityContext, DriftConfiguration driftConfig) { + public void detectDrift(EntityContext entityContext, DriftConfiguration driftConfig) throws RuntimeException { try { this.driftManager.detectDrift(getSessionSubject(), entityContext, driftConfig); } catch (Throwable t) { @@ -92,7 +92,8 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) { + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) + throws RuntimeException { try { PageList<? extends DriftChangeSet<?>> results = driftManager.findDriftChangeSetsByCriteria( getSessionSubject(), criteria); @@ -137,7 +138,8 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) + throws RuntimeException { try { return driftManager.createSnapshot(subject, criteria); } catch (Throwable t) { @@ -156,7 +158,8 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig) { + public void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig) + throws RuntimeException { try { this.driftManager.updateDriftConfiguration(getSessionSubject(), entityContext, driftConfig); } catch (Throwable t) {
commit 5b301553d975fb4d28c6787e4037f808282bc02b Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 10 16:55:11 2011 -0400
provide regex so GWT config editor enforces restrictions on the drift config names
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 3b4576d..36551ca 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 @@ -28,6 +28,7 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; import org.rhq.core.domain.configuration.definition.PropertySimpleType; +import org.rhq.core.domain.configuration.definition.constraint.RegexConstraint;
/** * The drift subsystem has a fixed configuration definition. That is, its property definitions @@ -105,6 +106,15 @@ public class DriftConfigurationDefinition implements Serializable { pd.setOrder(0); pd.setAllowCustomEnumeratedValue(false); pd.setConfigurationDefinition(INSTANCE); + + RegexConstraint constrait = new RegexConstraint(); + // because we know these names will actually be used by the agent's plugin container as directories names, + // we must make sure they are restricted to only be characters valid for file system pathnames. + // Thus, we only allow config names to only include spaces or "." or "-" or alphanumeric or "_" characters. + String pattern = "[ \.\-\w]+"; + constrait.setDetails(pattern); + pd.addConstraints(constrait); + return pd; }
commit 750b70e3f7788e26e4cde01214592fbf8146ee39 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 10 16:44:56 2011 -0400
[BZ - 698591 - Can not store preferences] Remove concurrent pref updates and only explicitly store the pref if the autopersist mechanism is not already doing it, making sure to now have the autopersister invoke the proper persistCallback as opposed to just its own.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java index ce43aa4..25fed3a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/preferences/UserPreferences.java @@ -85,28 +85,45 @@ public class UserPreferences { this.autoPersister = new UserPreferenceChangeListener() { @Override public void onPreferenceChange(UserPreferenceChangeEvent event) { - persist(event.name); + persist(event); }
@Override public void onPreferenceRemove(UserPreferenceChangeEvent event) { - persist(event.name); + persist(event); }
- private void persist(final String preferenceThatChanged) { + private void persist(final UserPreferenceChangeEvent event) { + store(new AsyncCallback<Subject>() { @Override public void onSuccess(Subject result) { + if (event instanceof AutoPersistAwareChangeEvent) { + AutoPersistAwareChangeEvent apaEvent = (AutoPersistAwareChangeEvent) event; + AsyncCallback<Subject> persistCallback = apaEvent.getPersistCallback(); + if (null != persistCallback) { + persistCallback.onSuccess(result); + } + } + // Don't announce anything to message center, this should happen under the covers - just refresh the current page. // But we should not blindly refresh - if we are changing preferences that should not affect the current // page, don't refresh as this could cause additional and unnecessary server-side hits (BZ 680167) - if (!preferencesThatShouldNotCauseRefresh.contains(preferenceThatChanged)) { + if (!preferencesThatShouldNotCauseRefresh.contains(event.getName())) { CoreGUI.refresh(); } }
@Override public void onFailure(Throwable caught) { + if (event instanceof AutoPersistAwareChangeEvent) { + AutoPersistAwareChangeEvent apaEvent = (AutoPersistAwareChangeEvent) event; + AsyncCallback<Subject> persistCallback = apaEvent.getPersistCallback(); + if (null != persistCallback) { + persistCallback.onFailure(caught); + } + } + CoreGUI.getErrorHandler().handleError("Cannot store preferences", caught); } }); @@ -126,25 +143,25 @@ public class UserPreferences { return getPreferenceAsIntegerSet(UserPreferenceNames.RESOURCE_HEALTH_RESOURCES); }
- public void setFavoriteResources(Set<Integer> resourceIds, AsyncCallback<Subject> callback) { - setPreference(UserPreferenceNames.RESOURCE_HEALTH_RESOURCES, resourceIds); - store(callback); + public void setFavoriteResources(Set<Integer> resourceIds, AsyncCallback<Subject> persistCallback) { + setPreference(UserPreferenceNames.RESOURCE_HEALTH_RESOURCES, resourceIds, persistCallback); + storeIfNotAutoPersisted(persistCallback); }
public Set<Integer> getFavoriteResourceGroups() { return getPreferenceAsIntegerSet(UserPreferenceNames.GROUP_HEALTH_GROUPS); }
- public void setFavoriteResourceGroups(Set<Integer> resourceGroupIds, AsyncCallback<Subject> callback) { - setPreference(UserPreferenceNames.GROUP_HEALTH_GROUPS, resourceGroupIds); - store(callback); + public void setFavoriteResourceGroups(Set<Integer> resourceGroupIds, AsyncCallback<Subject> persistCallback) { + setPreference(UserPreferenceNames.GROUP_HEALTH_GROUPS, resourceGroupIds, persistCallback); + storeIfNotAutoPersisted(persistCallback); }
public List<Integer> getRecentResources() { return this.getPreferenceAsIntegerList(UserPreferenceNames.RECENT_RESOURCES); }
- public void addRecentResource(Integer resourceId, AsyncCallback<Subject> callback) { + public void addRecentResource(Integer resourceId, AsyncCallback<Subject> persistCallback) { List<Integer> recentResources = getRecentResources(); if (!recentResources.isEmpty() && recentResources.get(0).equals(resourceId)) { return; @@ -157,15 +174,15 @@ public class UserPreferences { if (size > 10) { recentResources.remove(10); } - setPreference(UserPreferenceNames.RECENT_RESOURCES, recentResources); - store(callback); + setPreference(UserPreferenceNames.RECENT_RESOURCES, recentResources, persistCallback); + storeIfNotAutoPersisted(persistCallback); }
public List<Integer> getRecentResourceGroups() { return getPreferenceAsIntegerList(UserPreferenceNames.RECENT_RESOURCE_GROUPS); }
- public void addRecentResourceGroup(Integer resourceGroupId, AsyncCallback<Subject> callback) { + public void addRecentResourceGroup(Integer resourceGroupId, AsyncCallback<Subject> persistCallback) { List<Integer> recentResourceGroups = getRecentResourceGroups(); if (!recentResourceGroups.isEmpty() && recentResourceGroups.get(0).equals(resourceGroupId)) { return; @@ -178,8 +195,8 @@ public class UserPreferences { if (size > 5) { recentResourceGroups.remove(5); } - setPreference(UserPreferenceNames.RECENT_RESOURCE_GROUPS, recentResourceGroups); - store(callback); + setPreference(UserPreferenceNames.RECENT_RESOURCE_GROUPS, recentResourceGroups, persistCallback); + storeIfNotAutoPersisted(persistCallback); }
public int getPageRefreshInterval() { @@ -190,9 +207,9 @@ public class UserPreferences { return getPreferenceAsInteger(UserPreferenceNames.PAGE_REFRESH_PERIOD); }
- public void setPageRefreshInterval(int refreshInterval, AsyncCallback<Subject> callback) { - setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval)); - store(callback); + public void setPageRefreshInterval(int refreshInterval, AsyncCallback<Subject> persistCallback) { + setPreference(UserPreferenceNames.PAGE_REFRESH_PERIOD, String.valueOf(refreshInterval), persistCallback); + storeIfNotAutoPersisted(persistCallback); }
protected String getPreference(String name) { @@ -221,6 +238,10 @@ public class UserPreferences { }
protected void setPreference(String name, Collection<?> value) { + setPreference(name, value, null); + } + + protected void setPreference(String name, Collection<?> value, AsyncCallback<Subject> persistCallback) { StringBuilder buffer = new StringBuilder(); boolean first = true; for (Object item : value) { @@ -231,10 +252,14 @@ public class UserPreferences { } buffer.append(item); } - setPreference(name, buffer.toString()); + setPreference(name, buffer.toString(), persistCallback); }
protected void setPreference(String name, String value) { + setPreference(name, value, null); + } + + protected void setPreference(String name, String value, AsyncCallback<Subject> persistCallback) { PropertySimple prop = this.userConfiguration.getSimple(name); String oldValue = null; if (prop == null) { @@ -244,20 +269,24 @@ public class UserPreferences { prop.setStringValue(value); }
- UserPreferenceChangeEvent event = new UserPreferenceChangeEvent(name, value, oldValue); + UserPreferenceChangeEvent event = new AutoPersistAwareChangeEvent(name, value, oldValue, persistCallback); for (UserPreferenceChangeListener listener : changeListeners) { listener.onPreferenceChange(event); } }
protected void unsetPreference(String name) { + unsetPreference(name, null); + } + + protected void unsetPreference(String name, AsyncCallback<Subject> persistCallback) { PropertySimple doomedProp = this.userConfiguration.getSimple(name);
// it's possible property was already removed, and thus this operation becomes a no-op if (doomedProp != null) { String oldValue = doomedProp.getStringValue(); this.userConfiguration.remove(name); - UserPreferenceChangeEvent event = new UserPreferenceChangeEvent(name, null, oldValue); + UserPreferenceChangeEvent event = new AutoPersistAwareChangeEvent(name, null, oldValue, persistCallback); for (UserPreferenceChangeListener listener : changeListeners) { listener.onPreferenceRemove(event); } @@ -271,8 +300,16 @@ public class UserPreferences { } }
- public void store(AsyncCallback<Subject> callback) { - this.subjectService.updateSubject(this.subject, callback); + private void storeIfNotAutoPersisted(AsyncCallback<Subject> persistCallback) { + // if not auto persisted then perform store of the preference change, otherwise it + // is assumed autopersist will take care of it. + if (null == this.autoPersister) { + store(persistCallback); + } + } + + public void store(AsyncCallback<Subject> persistCallback) { + this.subjectService.updateSubject(this.subject, persistCallback); }
public Configuration getConfiguration() { @@ -338,4 +375,20 @@ public class UserPreferences { public void addChangeListener(UserPreferenceChangeListener listener) { changeListeners.add(listener); } + + private static class AutoPersistAwareChangeEvent extends UserPreferenceChangeEvent { + + private AsyncCallback<Subject> persistCallback; + + public AutoPersistAwareChangeEvent(String name, String newValue, String oldValue, + AsyncCallback<Subject> persistCallback) { + + super(name, newValue, oldValue); + this.persistCallback = persistCallback; + } + + public AsyncCallback<Subject> getPersistCallback() { + return persistCallback; + } + } }
commit 546319b35709f020275f7c22f8ae4613c8d91e06 Author: John Mazzitelli mazz@redhat.com Date: Wed Aug 10 13:19:39 2011 -0400
have gwt compiler ignore the domain sync package - it is for the CLI, not GWT client
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml index e7840c1..d4a69f6 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml @@ -32,7 +32,8 @@ <source path="client"/> <source path="domain"> <!-- Exclude any domain classes that can not be used client-side due to use of unsupported class use --> - <exclude name="**/JPADriftFileBits.*"/> + <exclude name="**/JPADriftFileBits.*"/> <!-- a server-side entity that requires SQL Blob support --> + <exclude name="sync/**"/> <!-- a server-side package used by the CLI to export system settings --> </source>
<!--<generate-with class="org.rhq.core.rebind.RecordBuilderGenerator">
commit 5cd8d7e8fbf9811c6f572ef4b00293bff9b1ce68 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 10 11:31:03 2011 -0400
- Remove defunct TableSection2 - Change
public class Table<DS extends RPCDataSource<?, ?>>
back to
public class Table<DS extends RPCDataSource>
Eclipse did not complain but the gwt compiler does not like the resulting unchecked situations in subclasses. We'd have to make changes to a lot of files, so just leave it unchecked.
here
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 6e8bbcc..0572369 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 @@ -100,7 +100,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Greg Hinkle * @author Ian Springer */ -public class Table<DS extends RPCDataSource<?, ?>> extends LocatableHLayout implements RefreshableView { +public class Table<DS extends RPCDataSource> extends LocatableHLayout implements RefreshableView {
protected static final String FIELD_ID = "id"; protected static final String FIELD_NAME = "name"; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection2.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection2.java deleted file mode 100644 index 28beafe..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/TableSection2.java +++ /dev/null @@ -1,367 +0,0 @@ -package org.rhq.enterprise.gui.coregui.client.components.table; - -import com.allen_sauer.gwt.log.client.Log; -import com.google.gwt.user.client.History; -import com.smartgwt.client.data.Criteria; -import com.smartgwt.client.data.SortSpecifier; -import com.smartgwt.client.types.AnimationEffect; -import com.smartgwt.client.types.VerticalAlignment; -import com.smartgwt.client.widgets.AnimationCallback; -import com.smartgwt.client.widgets.Canvas; -import com.smartgwt.client.widgets.events.DoubleClickEvent; -import com.smartgwt.client.widgets.events.DoubleClickHandler; -import com.smartgwt.client.widgets.grid.CellFormatter; -import com.smartgwt.client.widgets.grid.ListGrid; -import com.smartgwt.client.widgets.grid.ListGridField; -import com.smartgwt.client.widgets.grid.ListGridRecord; -import com.smartgwt.client.widgets.layout.VLayout; - -import org.rhq.enterprise.gui.coregui.client.BookmarkableView; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.DetailsView; -import org.rhq.enterprise.gui.coregui.client.ViewPath; -import org.rhq.enterprise.gui.coregui.client.components.buttons.BackButton; -import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; -import org.rhq.enterprise.gui.coregui.client.util.StringUtility; -import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; -import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; - -public abstract class TableSection2 <DS extends RPCDataSource> extends Table<DS> implements BookmarkableView { - - private VLayout detailsHolder; - private Canvas detailsView; - private String basePath; - private boolean escapeHtmlInDetailsLinkColumn; - private boolean initialDisplay; - - protected TableSection2(String locatorId, String tableTitle) { - super(locatorId, tableTitle); - } - - protected TableSection2(String locatorId, String tableTitle, Criteria criteria) { - super(locatorId, tableTitle, criteria); - } - - protected TableSection2(String locatorId, String tableTitle, SortSpecifier[] sortSpecifiers) { - super(locatorId, tableTitle, sortSpecifiers); - } - - protected TableSection2(String locatorId, String tableTitle, Criteria criteria, SortSpecifier[] sortSpecifiers) { - super(locatorId, tableTitle, sortSpecifiers, criteria); - } - - protected TableSection2(String locatorId, String tableTitle, boolean autoFetchData) { - super(locatorId, tableTitle, autoFetchData); - } - - protected TableSection2(String locatorId, String tableTitle, SortSpecifier[] sortSpecifiers, - String[] excludedFieldNames) { - super(locatorId, tableTitle, null, sortSpecifiers, excludedFieldNames); - } - - protected TableSection2(String locatorId, String tableTitle, Criteria criteria, SortSpecifier[] sortSpecifiers, - String[] excludedFieldNames) { - super(locatorId, tableTitle, criteria, sortSpecifiers, excludedFieldNames); - } - - protected TableSection2(String locatorId, String tableTitle, Criteria criteria, SortSpecifier[] sortSpecifiers, - String[] excludedFieldNames, boolean autoFetchData) { - super(locatorId, tableTitle, criteria, sortSpecifiers, excludedFieldNames, autoFetchData); - } - - @Override - protected void onInit() { - super.onInit(); - - this.initialDisplay = true; - - detailsHolder = new LocatableVLayout(extendLocatorId("tableSection")); - detailsHolder.setAlign(VerticalAlignment.TOP); - //detailsHolder.setWidth100(); - //detailsHolder.setHeight100(); - detailsHolder.setMargin(4); - detailsHolder.hide(); - - addMember(detailsHolder); - - // if the detailsView is already defined it means we want the details view to be rendered prior to - // the master view, probably due to a direct navigation or refresh (like F5 when sitting on the details page) - if (null != detailsView) { - switchToDetailsView(); - } - } - - /** - * The default implementation wraps the {@link #getDetailsLinkColumnCellFormatter()} column with the - * {@link #getDetailsLinkColumnCellFormatter()}. This is typically the 'name' column linking to the detail - * view, given the 'id'. Also, establishes a double click handler for the row which invokes - * {@link #showDetails(com.smartgwt.client.widgets.grid.ListGridRecord)}</br> - * </br> - * In general, in overrides, call super.configureTable *after* manipulating the ListGrid fields. - * - * @see org.rhq.enterprise.gui.coregui.client.components.table.Table#configureTable() - */ - @Override - protected void configureTable() { - if (isDetailsEnabled()) { - ListGrid grid = getListGrid(); - - // Make the value of some specific field a link to the details view for the corresponding record. - ListGridField field = (grid != null) ? grid.getField(getDetailsLinkColumnName()) : null; - if (field != null) { - field.setCellFormatter(getDetailsLinkColumnCellFormatter()); - } - - setListGridDoubleClickHandler(new DoubleClickHandler() { - @Override - public void onDoubleClick(DoubleClickEvent event) { - ListGrid listGrid = (ListGrid) event.getSource(); - ListGridRecord[] selectedRows = listGrid.getSelection(); - if (selectedRows != null && selectedRows.length == 1) { - showDetails(selectedRows[0]); - } - } - }); - } - } - - protected boolean isDetailsEnabled() { - return true; - } - - public void setEscapeHtmlInDetailsLinkColumn(boolean escapeHtmlInDetailsLinkColumn) { - this.escapeHtmlInDetailsLinkColumn = escapeHtmlInDetailsLinkColumn; - } - - /** - * Override if you don't want FIELD_NAME to be wrapped ina link. - * @return the name of the field to be wrapped, or null if no field should be wrapped. - */ - protected String getDetailsLinkColumnName() { - return FIELD_NAME; - } - - /** - * Override if you don't want the detailsLinkColumn to have the default link wrapper. - * @return the desired CellFormatter. - */ - protected CellFormatter getDetailsLinkColumnCellFormatter() { - return new CellFormatter() { - public String format(Object value, ListGridRecord record, int i, int i1) { - if (value == null) { - return ""; - } - String recordId = getId(record); - String detailsUrl = "#" + getBasePath() + "/" + recordId; - String formattedValue = (escapeHtmlInDetailsLinkColumn) ? StringUtility.escapeHtml(value.toString()) - : value.toString(); - return SeleniumUtility.getLocatableHref(detailsUrl, formattedValue, null); - } - }; - } - - /** - * Shows the details view for the given record of the table. - * - * The default implementation of this method assumes there is an - * id attribute on the record and passes it to {@link #showDetails(String)}. - * Subclasses are free to override this behavior. Subclasses usually - * will need to set the {@link #setDetailsView(Canvas) details view} - * explicitly. - * - * @param record the record whose details are to be shown - */ - public void showDetails(ListGridRecord record) { - if (record == null) { - throw new IllegalArgumentException("'record' parameter is null."); - } - - String id = getId(record); - showDetails(id); - } - - /** - * Returns the details canvas with information on the item given its list grid record. - * - * The default implementation of this method is to assume there is an - * id attribute on the record and pass that ID to {@link #getDetailsView(String)}. - * Subclasses are free to override this - which you usually want to do - * if you know the full details of the item are stored in the record attributes - * and thus help avoid making a round trip to the DB. - * - * @param record the record of the item whose details to be shown; ; null if empty details view should be shown. - */ - public Canvas getDetailsView(ListGridRecord record) { - String id = getId(record); - return getDetailsView(id); - } - - protected String getId(ListGridRecord record) { - String id = null; - if (record != null) { - id = record.getAttribute("id"); - } - if (id == null || id.length() == 0) { - String msg = MSG.view_tableSection_error_noId(this.getClass().toString()); - CoreGUI.getErrorHandler().handleError(msg); - throw new IllegalStateException(msg); - } - return id; - } - - /** - * Shows empty details for a new item being created. - * This method is usually called when a user clicks a 'New' button. - * - * @see #showDetails(ListGridRecord) - */ - public void newDetails() { - History.newItem(basePath + "/0"); - } - - /** - * Shows the details for an item has the given ID. - * This method is usually called when a user goes to the details - * page via a bookmark, double-cick on a list view row, or direct link. - * - * @param id the id of the row whose details are to be shown; Should be a valid id. - * - * @see #showDetails(ListGridRecord) - * - * @throws IllegalArgumentException if id is null or empty string - */ - public void showDetails(String id) { - if (id == null || id.length() == 0) { - History.newItem(basePath + "/" + id); - } else { - String msg = MSG.view_tableSection_error_badId(this.getClass().toString(), id); - CoreGUI.getErrorHandler().handleError(msg); - throw new IllegalArgumentException(msg); - } - } - - /** - * Returns the details canvas with information on the item that has the given ID. - * Note that an empty details view should be returned if the id passed in is 0 (as would - * be the case if a new item is to be created using the details view). - * - * @param id the id of the details to be shown; will be null if an empty details view should be shown. - */ - public abstract Canvas getDetailsView(String id); - - @Override - public void renderView(ViewPath viewPath) { - this.basePath = viewPath.getPathToCurrent(); - - if (!viewPath.isEnd()) { - String id = viewPath.getCurrent().getPath(); - this.detailsView = getDetailsView(id); - if (this.detailsView instanceof BookmarkableView) { - ((BookmarkableView) this.detailsView).renderView(viewPath); - } - switchToDetailsView(); - } else { - switchToTableView(); - } - } - - protected String getBasePath() { - return this.basePath; - } - - /** - * For use by subclasses that want to define their own details view. - * - * @param detailsView the new details view - */ - protected void setDetailsView(Canvas detailsView) { - this.detailsView = detailsView; - } - - /** - * Switches to viewing the details canvas, hiding the table. This does not - * do anything with reloading data or switching to the selected row in the table; - * this only changes the visibility of canvases. - */ - protected void switchToDetailsView() { - Canvas contents = getTableContents(); - - // If the Table has not yet been initialized then ignore - if (contents != null) { - if (contents.isVisible()) { - contents.animateHide(AnimationEffect.WIPE, new AnimationCallback() { - @Override - public void execute(boolean b) { - buildDetailsView(); - } - }); - } else { - /* - * if the programmer chooses to go directly from the detailView in create-mode to the - * detailsView in edit-mode, the content canvas will already be hidden, which means the - * animateHide would be a no-op (the event won't fire). this causes the detailsHolder - * to keep a reference to the previous detailsView (the one in create-mode) instead of the - * newly returned reference from getDetailsView(String) that was called when the renderView - * methods were called hierarchically down to render the new detailsView in edit-mode. - * therefore, we need to explicitly destroy what's already there (presumably the detailsView - * in create-mode), and then rebuild it (presumably the detailsView in edit-mode). - */ - SeleniumUtility.destroyMembers(detailsHolder); - - buildDetailsView(); - } - } - } - - private void buildDetailsView() { - detailsView.setWidth100(); - detailsView.setHeight100(); - - boolean isEditable = (detailsView instanceof DetailsView && ((DetailsView) detailsView).isEditable()); - if (!isEditable) { - // Only add the "Back to List" button if the details are definitely not editable, because if they are - // editable, a Cancel button should already be provided by the details view. - BackButton backButton = new BackButton(extendLocatorId("BackButton"), MSG.view_tableSection_backButton(), - basePath); - detailsHolder.addMember(backButton); - VLayout verticalSpacer = new LocatableVLayout(extendLocatorId("verticalSpacer")); - verticalSpacer.setHeight(8); - detailsHolder.addMember(verticalSpacer); - } - - detailsHolder.addMember(detailsView); - detailsHolder.animateShow(AnimationEffect.WIPE); - } - - /** - * Switches to viewing the table, hiding the details canvas. - */ - protected void switchToTableView() { - final Canvas contents = getTableContents(); - if (contents != null) { - // If this is not the initial display of the table, refresh the table's data. Otherwise, a refresh would be - // redundant, since the data was just loaded when the table was drawn. - if (this.initialDisplay) { - this.initialDisplay = false; - } else { - Log.debug("Refreshing data for Table [" + getClass().getName() + "]..."); - refresh(); - } - if (detailsHolder != null && detailsHolder.isVisible()) { - detailsHolder.animateHide(AnimationEffect.WIPE, new AnimationCallback() { - @Override - public void execute(boolean b) { - SeleniumUtility.destroyMembers(detailsHolder); - - contents.animateShow(AnimationEffect.WIPE); - } - }); - } else { - contents.animateShow(AnimationEffect.WIPE); - } - } - } - - - -}
commit c2e7d07ee333009f8a5dbf6ce8365aca2f03e3c4 Author: John Sanda jsanda@redhat.com Date: Wed Aug 10 10:38:15 2011 -0400
Change set files no longer store directories
By only storing files in the change set file, a lot of logic in DriftDetector is simplified. With this commit we now detect files in new or deleted directories.
diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java index 68b7163..7d9b8f1 100644 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java @@ -19,12 +19,44 @@
package org.rhq.common.drift;
-public interface ChangeSetReader extends Iterable<DirectoryEntry> { +/** + * Reads change set file in a sequential fashion. Note that class extends {@link Iterable} + * which means you can iterate over change set files as follows: + * <pre> + * ChangeSetReader reader = ... + * for (FileEntry entry : reader) { + * ... + * } + * </pre> + */ +public interface ChangeSetReader extends Iterable<FileEntry> {
+ /** + * Returns the headers from change set file. This method can be called multiple times. + * Given a properly formatted change set file, this method should never return null. + * + * @return The change set headers + * + * @throws ChangeSetReaderException If an error occurs reading the file or the headers + * are not formatted correctly. + */ Headers getHeaders() throws ChangeSetReaderException;
- DirectoryEntry readDirectoryEntry() throws ChangeSetReaderException; + /** + * Read and return the next file entry or null if the end of the file has been reached. + * + * @return The next file entry + * + * @throws ChangeSetReaderException if an IO error occurs or if the file entry is not + * properly formatted. + */ + FileEntry read() throws ChangeSetReaderException;
+ /** + * Closes the reader. + * + * @throws ChangeSetReaderException if an IO error occurs + */ void close() throws ChangeSetReaderException;
} 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 417f512..a935e66 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 @@ -31,7 +31,6 @@ import org.apache.commons.logging.LogFactory;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import static java.lang.Integer.parseInt; import static org.rhq.common.drift.FileEntry.addedFileEntry; import static org.rhq.common.drift.FileEntry.changedFileEntry; import static org.rhq.common.drift.FileEntry.removedFileEntry; @@ -90,45 +89,33 @@ public class ChangeSetReaderImpl implements ChangeSetReader { }
@Override - public DirectoryEntry readDirectoryEntry() throws ChangeSetReaderException { + public FileEntry read() throws ChangeSetReaderException { try { - String dirLine = reader.readLine(); - if (null == dirLine) { + String line = reader.readLine(); + if (line == null) { return null; }
- int index = dirLine.indexOf(" "); - // TODO should we throw a parse exception if index is < 1 - int numFiles = parseInt(dirLine.substring(0, index)); - DirectoryEntry dirEntry = new DirectoryEntry(dirLine.substring(index + 1)); - - for (int i = 0; i < numFiles; ++i) { - String line = reader.readLine(); - if (line.charAt(0) == 'A') { // file added - String sha = line.substring(2, 66); - String fileName = line.substring(69); - - dirEntry.add(addedFileEntry(fileName, sha)); - } else if (line.charAt(0) == 'C') { // file changed - String newSha = line.substring(2, 66); - String oldSha = line.substring(67, 131); - String fileName = line.substring(132); - - dirEntry.add(changedFileEntry(fileName, oldSha, newSha)); - } else if (line.charAt(0) == 'R') { - String sha = line.substring(4, 68); - String fileName = line.substring(69); - - dirEntry.add(removedFileEntry(fileName, sha)); - } else { - log.error("An error occurred while parsing " + metaDataFile.getAbsolutePath() + ": " + - line.charAt(0) + " is not a recognized drift change set category code."); - throw new ChangeSetReaderException(line.charAt(0) + " is not a recognized drift change set " + - "category code."); - } + if (line.charAt(0) == 'A') { // file added + String sha = line.substring(2, 66); + String fileName = line.substring(69); + return addedFileEntry(fileName, sha); + } + if (line.charAt(0) == 'C') { // file modified + String newSha = line.substring(2, 66); + String oldSha = line.substring(67, 131); + String fileName = line.substring(132); + return changedFileEntry(fileName, oldSha, newSha); + } + if (line.charAt(0) == 'R') { // file deleted + String sha = line.substring(4, 68); + String fileName = line.substring(69); + return removedFileEntry(fileName, sha); }
- return dirEntry; + log.error("An error occurred while parsing " + metaDataFile.getAbsolutePath() + ": " + + line.charAt(0) + " is not a recognized drift change set category code."); + throw new ChangeSetReaderException(line.charAt(0) + " is not a recognized drift change set category code."); } catch (IOException e) { log.error("An error ocurred while parsing " + metaDataFile.getAbsolutePath() + ": " + e.getMessage()); throw new ChangeSetReaderException("An error ocurred while parsing " + metaDataFile.getAbsolutePath(), e); @@ -147,15 +134,15 @@ public class ChangeSetReaderImpl implements ChangeSetReader { }
@Override - public Iterator<DirectoryEntry> iterator() { + public Iterator<FileEntry> iterator() {
- return new Iterator<DirectoryEntry>() { + return new Iterator<FileEntry>() {
- private DirectoryEntry next; + private FileEntry next;
{ try { - next = readDirectoryEntry(); + next = read(); } catch (IOException e) { throw new RuntimeException("Failed to create iterator: " + e); } @@ -167,13 +154,16 @@ public class ChangeSetReaderImpl implements ChangeSetReader { }
@Override - public DirectoryEntry next() { + public FileEntry next() { try { - DirectoryEntry previous = next; - next = readDirectoryEntry(); + FileEntry previous = next; + next = read(); + if (next == null) { + close(); + } return previous; } catch (IOException e) { - throw new RuntimeException("Failed to get next " + DirectoryEntry.class.getName() + ": " + e); + throw new RuntimeException("Failed to get next " + FileEntry.class.getName() + ": " + e); } }
diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java index 4ea79c9..44bf20e 100644 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java @@ -22,19 +22,17 @@ package org.rhq.common.drift; import java.io.IOException;
/** - * Generates a drift change set file. A change set is stored as a UTF-8 text file. It - * consists of file paths with some associated meta data. Files are grouped by directory. - * The meta data includes the SHA-256 hash, the old SHA-256 hash (if one exists), the - * file name, and a single character code indicating whether the file has been added, - * changed, or removed in this change set. The codes are taken from + * Generates a change set file. A change set is stored as a UTF-8 text file. It consists of + * file paths with some associated meta data. The meta data includes the SHA-256 hash, the + * old SHA-256 hash (if one exists), and a single character code indicating whether the file + * has been added, changed, or removed in the change set. The codes are taken from * {@link org.rhq.core.domain.drift.DriftCategory DriftCategory}. * <br/> * <br/> * The current format of the change set file is: * <pre> - * HEADER - * DRIFT_ENTRY - * FILE_ENTRY (1..N) + * HEADERS + * FILE_ENTRY (1..N) * </pre> * where HEADER corresponds to {@link Headers} and the header fields are written out in the * following order: @@ -46,8 +44,6 @@ import java.io.IOException; * <li>change set type flag indicating whether this is a coverage or drift changeset</li> * </ul> * <br/> - * DRIFT_ENTRY has two field that are space delimited. The first is the number of files - * included in DRIFT_ENTRY. The second is the relative path of the directory, that is * <br/> * FILE_ENTRY has four, space-delimited fields - type, new_sha, old_sha, file_name.<br/> * Here is an example change set: @@ -57,26 +53,31 @@ import java.io.IOException; * 2345 * Core Server JARs * /var/lib/myserver - * 2 lib - * C 1706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c 1536b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c foo.jar - * A 2706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a 0 bar.jar - * 1 conf - * R 0 2206b5af8e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a foo.conf + * C 1706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c 1536b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c lib/foo.jar + * A 2706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a 0 lib/bar.jar + * R 0 2206b5af8e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a conf/foo.conf * </pre> * - * For the first directory entry, notice that the old_sha field has a value of 0 for bar.jar. - * This is because it is a new file, and there is no previous SHA-256 hash for the file. For - * the second directory entry, notice that the new_sha field has a value of 0 for foo.conf. - * This is because the file has been removed and so there is no new SHA-256 hash. + * Note that the file paths in each entry are relative to the path in the base directory + * header. For the entry with a path of lib/bar.jar notice that the old_sha field has a + * value of 0. This is because it is a new file, and there is no previous SHA-256 hash for + * the file. For the entry with conf/foo.conf as its path, notices that the new_sha field + * has a value of 0 for foo.conf. This is because the file has been deleted and so there is + * no new SHA-256 hash. + * <p/> + * Lastly and importantly, the format of this file is still subject to change. Additional + * headers may be added, maybe allowing for optional headers. The format of the file entry + * may change as well. Currently a place holder value of 0 is used to indicate the lack + * of a SHA-256 hash. That place holder is not really needed and may go away. */ public interface ChangeSetWriter {
/** * - * @param dirEntry + * @param entry * @throws IOException */ - void writeDirectoryEntry(DirectoryEntry dirEntry) throws IOException; + void write(FileEntry entry) throws IOException;
void close() throws IOException;
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 d822d40..b694540 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 @@ -53,21 +53,18 @@ public class ChangeSetWriterImpl implements ChangeSetWriter { writer.write(headers.getType().code() + "\n"); }
- public void writeDirectoryEntry(DirectoryEntry dirEntry) throws IOException { - writer.write(dirEntry.getNumberOfFiles() + " " + dirEntry.getDirectory() + "\n"); - for (FileEntry entry : dirEntry) { - switch (entry.getType()) { - case FILE_ADDED: - writer.write(entry.getType().code() + " " + entry.getNewSHA() + " 0 " + entry.getFile() + "\n"); - break; - case FILE_CHANGED: - writer.write(entry.getType().code() + " " + entry.getNewSHA() + " " + entry.getOldSHA() + " " + - entry.getFile() + "\n"); - break; - case FILE_REMOVED: - writer.write(entry.getType().code() + " 0 " + entry.getOldSHA() + " " + entry.getFile() + "\n"); - break; - } + public void write(FileEntry entry) throws IOException { + switch (entry.getType()) { + case FILE_ADDED: + writer.write(entry.getType().code() + " " + entry.getNewSHA() + " 0 " + entry.getFile() + "\n"); + break; + case FILE_CHANGED: + writer.write(entry.getType().code() + " " + entry.getNewSHA() + " " + entry.getOldSHA() + " " + + entry.getFile() + "\n"); + break; + case FILE_REMOVED: + writer.write(entry.getType().code() + " 0 " + entry.getOldSHA() + " " + entry.getFile() + "\n"); + break; } }
diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java b/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java deleted file mode 100644 index fabcc7e..0000000 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.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.common.drift; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -public class DirectoryEntry implements Iterable<FileEntry>, Serializable { - - private static final long serialVersionUID = 1L; - - private String directory; - - private List<FileEntry> files = new ArrayList<FileEntry>(); - - public DirectoryEntry(String directory) { - this.directory = directory; - } - - public String getDirectory() { - return directory; - } - - public DirectoryEntry add(FileEntry entry) { - files.add(entry); - return this; - } - - public DirectoryEntry remove(FileEntry entry) { - FileEntry entryToRemove = null; - int i = 0; - for (FileEntry fileEntry : files) { - if (entry.getFile().equals(fileEntry.getFile())) { - entryToRemove = fileEntry; - break; - } - ++i; - } - if (entryToRemove != null) { - files.remove(i); - } - return this; - } - - public int getNumberOfFiles() { - return files.size(); - } - - public Iterator<FileEntry> iterator() { - return files.iterator(); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "[directory: " + directory + "]"; - } -} 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 db4955c..c6bd763 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 @@ -9,7 +9,6 @@ import org.rhq.core.util.MessageDigestGenerator; import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.rhq.test.AssertUtils.assertPropertiesMatch; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull;
public class ChangeSetReaderImplTest {
@@ -17,15 +16,14 @@ public class ChangeSetReaderImplTest {
@Test @SuppressWarnings("unchecked") - public void readDirectoryEntryWithFileAdded() throws Exception { + public void readFileAddedEntry() throws Exception { String sha = sha256("myconf.conf"); String changeset = "1\n" + "1\n" + "file-added-test\n" + "myresource\n" + "C\n" + - "1 myresource/conf\n" + - "A " + sha + " 0 myconf.conf"; + "A " + sha + " 0 conf/myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
@@ -39,28 +37,23 @@ public class ChangeSetReaderImplTest {
assertHeadersEquals(actualHeaders, expectedHeaders);
- DirectoryEntry dirEntry = reader.readDirectoryEntry(); + FileEntry expectedFileEntry = new FileEntry(sha, "0", "conf/myconf.conf", "A"); + FileEntry actualFileEntry = reader.read(); reader.close();
- assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1); - - FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry(sha, "0", "myconf.conf", "A"); - assertFileEntryEquals(actualFileEntry, expectedFileEntry); }
@Test @SuppressWarnings("unchecked") - public void readDirectoryEntryWithFileRemoved() throws Exception { + public void readFileRemovedEntry() throws Exception { String sha = sha256("myconf.conf"); String changeset = "1\n" + "1\n" + "file-removed-test\n" + "myresource\n" + "C\n" + - "1 myresource/conf\n" + - "R 0 " + sha + " myconf.conf"; + "R 0 " + sha + " conf/myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
@@ -74,20 +67,16 @@ public class ChangeSetReaderImplTest {
assertHeadersEquals(actualHeaders, expectedHeaders);
- DirectoryEntry dirEntry = reader.readDirectoryEntry(); + FileEntry expectedFileEntry = new FileEntry("0", sha, "conf/myconf.conf", "R"); + FileEntry actualFileEntry = reader.read(); reader.close();
- assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1); - - FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry("0", sha, "myconf.conf", "R"); - assertFileEntryEquals(actualFileEntry, expectedFileEntry); }
@Test @SuppressWarnings("unchecked") - public void readDirectoryEntryWithFileChanged() throws Exception { + public void readChangedFileEntry() throws Exception { String oldSha = sha256("myconf.conf.old"); String newSha = sha256("myconf.conf.new"); String changeset = "1\n" + @@ -95,8 +84,7 @@ public class ChangeSetReaderImplTest { "file-changed-test\n" + "myresource\n" + "C\n" + - "1 myresource/conf\n" + - "C " + newSha + " " + oldSha + " myconf.conf"; + "C " + newSha + " " + oldSha + " conf/myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
@@ -110,28 +98,23 @@ public class ChangeSetReaderImplTest {
assertHeadersEquals(actualHeaders, expectedHeaders);
- DirectoryEntry dirEntry = reader.readDirectoryEntry(); + FileEntry expectedFileEntry = new FileEntry(newSha, oldSha, "conf/myconf.conf", "C"); + FileEntry actualFileEntry = reader.read(); reader.close();
- assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1); - - FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry(newSha, oldSha, "myconf.conf", "C"); - assertFileEntryEquals(actualFileEntry, expectedFileEntry); }
@Test @SuppressWarnings("unchecked") - public void readEntryWithAddedFileThatHasSpaces() throws Exception { + public void readFileEntryWithSpacesInPath() throws Exception { String sha = sha256("file with spaces.conf"); String changeset = "1\n" + "1\n" + "file-name-test\n" + "myresource\n" + "C\n" + - "1 myresource/conf\n" + - "A " + sha + " 0 file with spaces.conf"; + "A " + sha + " 0 conf/file with spaces.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
@@ -145,14 +128,10 @@ public class ChangeSetReaderImplTest {
assertHeadersEquals(actualHeaders, expectedHeaders);
- DirectoryEntry dirEntry = reader.readDirectoryEntry(); + FileEntry expectedFileEntry = new FileEntry(sha, "0", "conf/file with spaces.conf", "A"); + FileEntry actualFileEntry = reader.read(); reader.close();
- assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1); - - FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry(sha, "0", "file with spaces.conf", "A"); - assertFileEntryEquals(actualFileEntry, expectedFileEntry); }
@@ -168,47 +147,44 @@ public class ChangeSetReaderImplTest {
@Test @SuppressWarnings("unchecked") - public void iterateOverChangeSetWithMultipledDirectoryEntries() throws Exception { + public void iterateOverChangeSetWithMultipleEntries() throws Exception { String changeset = "1\n" + "1\n" + "multiple-dir-entries-test\n" + "myresource\n" + "C\n" + - "1 conf\n" + - "A " + sha256("resource.conf") + " 0 resource.conf\n" + - "1 lib\n" + - "A " + sha256("resource.jar") + " 0 resource.jar"; + "A " + sha256("resource.conf") + " 0 conf/resource.conf\n" + + "A " + sha256("resource.jar") + " 0 lib/resource.jar";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); - int numDirEntries = 0; + int numEntries = 0;
- for (DirectoryEntry dirEntry : reader) { - ++numDirEntries; + for (FileEntry entry : reader) { + ++numEntries; }
- assertEquals(numDirEntries, 2, "Expected iterator to return two directory entries"); + assertEquals(numEntries, 2, "Expected iterator to return two file entries"); }
@Test @SuppressWarnings("unchecked") - public void iterateOverChangeSetOneDirectoryEntry() throws Exception { + public void iterateOverChangeSetWithOneEntry() throws Exception { String sha = sha256("resource.conf"); String changeset = "1\n" + "1\n" + "single-dir-entry-test\n" + "myresource\n" + "C\n" + - "1 conf\n" + - "A " + sha + " 0 resource.conf\n"; + "A " + sha + " 0 conf/resource.conf\n";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); - int numDirEntries = 0; + int numEntries = 0;
- for (DirectoryEntry dirEntry : reader) { - ++numDirEntries; + for (FileEntry entry : reader) { + ++numEntries; }
- assertEquals(numDirEntries, 1, "Expected iterator to return one directory entry"); + assertEquals(numEntries, 1, "Expected iterator to return one file entry"); }
@Test @@ -225,34 +201,19 @@ public class ChangeSetReaderImplTest { "C\n";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); - int numDirEntries = 0; + int numEntries = 0;
- for (DirectoryEntry dirEntry : reader) { - ++numDirEntries; + for (FileEntry entry : reader) { + ++numEntries; }
- assertEquals(numDirEntries, 0, "Expected iterator to return zero directory entries"); + assertEquals(numEntries, 0, "Expected iterator to return zero file entries"); }
void assertHeadersEquals(Headers actual, Headers expected) { assertPropertiesMatch(expected, actual, "Failed to parse change set headers"); }
- /** - * Verifies that the directory entry name (i.e., path) and number of files match the - * specified values. - * - * @param dirEntry - * @param path - * @param numberOfFiles - */ - void assertDirectoryEntryEquals(DirectoryEntry dirEntry, String path, int numberOfFiles) { - assertNotNull(dirEntry, "Expected non-null directory entry"); - assertEquals(dirEntry.getDirectory(), path, "The directory name/path is wrong"); - assertEquals(dirEntry.getNumberOfFiles(), numberOfFiles, "The number of files for the directory entry is " + - "wrong"); - } - void assertFileEntryEquals(FileEntry actual, FileEntry expected) { assertEquals(actual.getType(), expected.getType(), "The first column, the entry type, is wrong"); assertEquals(actual.getNewSHA(), expected.getNewSHA(), "The second column, the new SHA-256, is wrong"); 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 433634b..e9efddd 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 @@ -56,7 +56,7 @@ public class ChangeSetWriterImplTest {
@Test @SuppressWarnings("unchecked") - public void writeDirectoryEntryWithAddedFile() throws Exception { + public void writeFiledAddedEntry() throws Exception { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "added-file-test"); @@ -70,27 +70,21 @@ public class ChangeSetWriterImplTest {
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
- writer.writeDirectoryEntry(new DirectoryEntry("conf").add( - addedFileEntry("myconf.conf", "a34ef6"))); + writer.write(addedFileEntry("conf/myconf.conf", "a34ef6")); writer.close();
File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + - " - five for the header followed by two for a directory entry."); - + assertEquals(lines.size(), 6, "Expected to find seven lines in " + metaDataFile.getPath() + + " - five for the header followed by one file entry."); assertHeadersEquals(lines, headers); - - assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + - "the number of lines in the entry followed by the directory path."); - - assertFileEntryEquals(lines.get(6), "A a34ef6 0 myconf.conf"); + assertFileEntryEquals(lines.get(5), "A a34ef6 0 conf/myconf.conf"); }
@Test @SuppressWarnings("unchecked") - public void writeDirectoryEntryWithRemovedFile() throws Exception { + public void writeFileRemovedEntry() throws Exception { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "removed-file-test"); @@ -103,27 +97,21 @@ public class ChangeSetWriterImplTest {
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
- writer.writeDirectoryEntry(new DirectoryEntry("conf").add( - removedFileEntry("myconf.conf", "a34ef6"))); + writer.write(removedFileEntry("conf/myconf.conf", "a34ef6")); writer.close();
File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + - " - five for the header followed by two for a directory entry."); - + assertEquals(lines.size(), 6, "Expected to find six lines in " + metaDataFile.getPath() + + " - five for the header followed by one file entry."); assertHeadersEquals(lines, headers); - - assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + - "the number of lines in the entry followed by the directory path."); - - assertFileEntryEquals(lines.get(6), "R 0 a34ef6 myconf.conf"); + assertFileEntryEquals(lines.get(5), "R 0 a34ef6 conf/myconf.conf"); }
@Test @SuppressWarnings("unchecked") - public void writeDirectoryEntryWithChangedFile() throws Exception { + public void writeFileChangedEntry() throws Exception { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "changed-file-test"); @@ -136,22 +124,16 @@ public class ChangeSetWriterImplTest {
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
- writer.writeDirectoryEntry(new DirectoryEntry("conf").add( - changedFileEntry("myconf.conf", "a34ef6", "c2d55f"))); + writer.write(changedFileEntry("conf/myconf.conf", "a34ef6", "c2d55f")); writer.close();
File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + - " - five for the header followed by two for a directory entry."); - + assertEquals(lines.size(), 6, "Expected to find six lines in " + metaDataFile.getPath() + + " - five for the header followed by one file entry."); assertHeadersEquals(lines, headers); - - assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + - "the number of lines in the entry followed by the directory path."); - - assertFileEntryEquals(lines.get(6), "C c2d55f a34ef6 myconf.conf"); + assertFileEntryEquals(lines.get(5), "C c2d55f a34ef6 conf/myconf.conf"); }
/** diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DirectoryAnalyzer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DirectoryAnalyzer.java deleted file mode 100644 index fa55085..0000000 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DirectoryAnalyzer.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.rhq.core.pc.drift; - -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.rhq.common.drift.DirectoryEntry; -import org.rhq.common.drift.FileEntry; -import org.rhq.core.util.MessageDigestGenerator; - -import static org.rhq.common.drift.FileEntry.addedFileEntry; -import static org.rhq.common.drift.FileEntry.changedFileEntry; -import static org.rhq.common.drift.FileEntry.removedFileEntry; - -public class DirectoryAnalyzer { - - private File basedir; - - private DirectoryEntry dirEntry; - - private List<FileEntry> filesAdded = new ArrayList<FileEntry>(); - - private List<FileEntry> filesRemoved = new ArrayList<FileEntry>(); - - private List<FileEntry> filesChanged = new ArrayList<FileEntry>(); - - private MessageDigestGenerator digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); - - public DirectoryAnalyzer(File basedir, DirectoryEntry directoryEntry) { - this.basedir = basedir; - dirEntry = directoryEntry; - } - - public List<FileEntry> getFilesAdded() { - return filesAdded; - } - - public List<FileEntry> getFilesRemoved() { - return filesRemoved; - } - - public List<FileEntry> getFilesChanged() { - return filesChanged; - } - - public void run() throws IOException { - File dir = new File(basedir, dirEntry.getDirectory()); - // TODO handle directories - Set<String> files = fileNames(dir.listFiles(new FileFilter() { - @Override - public boolean accept(File path) { - return path.isFile(); - } - })); - Map<String, FileEntry> fileEntries = createFileEntriesMap(); - List<String> processed = new ArrayList<String>(); - - for (String file : files) { - if (!fileEntries.containsKey(file)) { - filesAdded.add(addedFileEntry(file, sha256(new File(dir, file)))); - processed.add(file); - } - } - files.removeAll(processed); - - for (String file : fileEntries.keySet()) { - if (!files.contains(file)) { - filesRemoved.add(removedFileEntry(file, fileEntries.get(file).getNewSHA())); - } - } - - for (String file : files) { - FileEntry entry = fileEntries.get(file); - String currentHash = sha256(new File(dir, file)); - if (!currentHash.equals(entry.getNewSHA())) { - filesChanged.add(changedFileEntry(file, entry.getNewSHA(), currentHash)); - } - } - } - - private Set<String> fileNames(File... files) { - Set<String> set = new TreeSet<String>(); - for (File file : files) { - set.add(file.getName()); - } - return set; - } - - private Map<String, FileEntry> createFileEntriesMap() { - Map<String, FileEntry> map = new TreeMap<String, FileEntry>(); - for (FileEntry entry : dirEntry) { - map.put(entry.getFile(), entry); - } - return map; - } - - private Set<String> dirEntryFileNames() { - Set<String> set = new TreeSet<String>(); - for (FileEntry entry : dirEntry) { - set.add(entry.getFile()); - } - return set; - } - - private String sha256(File file) throws IOException { - return digestGenerator.calcDigestString(file); - } - -} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionException.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionException.java new file mode 100644 index 0000000..c75f992 --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/drift/DriftDetectionException.java @@ -0,0 +1,39 @@ +/* + * 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.pc.drift; + +public class DriftDetectionException extends RuntimeException { + + public DriftDetectionException() { + super(); + } + + public DriftDetectionException(String message) { + super(message); + } + + public DriftDetectionException(String message, Throwable cause) { + super(message, cause); + } + + public DriftDetectionException(Throwable cause) { + super(cause); + } +} 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 868073e..708a003 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,27 +19,30 @@
package org.rhq.core.pc.drift;
-import static java.util.Collections.EMPTY_LIST; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; - import java.io.File; import java.io.IOException; -import java.util.Collection; -import java.util.Stack; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.commons.io.DirectoryWalker; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetWriter; -import org.rhq.common.drift.DirectoryEntry; 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.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.forEachFile;
public class DriftDetector implements Runnable { private Log log = LogFactory.getLog(DriftDetector.class); @@ -81,7 +84,6 @@ public class DriftDetector implements Runnable { }
DriftConfiguration driftConfig = schedule.getDriftConfiguration(); - int resourceId = schedule.getResourceId(); DriftChangeSetCategory changeSetType = null; int changes = 0;
@@ -106,74 +108,89 @@ public class DriftDetector implements Runnable { } }
- private int generateDriftChangeSet(DriftDetectionSchedule schedule) throws IOException { - File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration())); + private int generateDriftChangeSet(final DriftDetectionSchedule schedule) throws IOException { + final File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration()));
- ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, - DRIFT)); - ChangeSetWriter coverageWriter = changeSetMgr.getChangeSetWriterForUpdate(schedule.getResourceId(), + final ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), + createHeaders(schedule, DRIFT)); + final ChangeSetReader coverageReader = changeSetMgr.getChangeSetReader(schedule.getResourceId(), + schedule.getDriftConfiguration().getName()); + final ChangeSetWriter coverageWriter = changeSetMgr.getChangeSetWriterForUpdate(schedule.getResourceId(), createHeaders(schedule, COVERAGE)); - ChangeSetReader reader = changeSetMgr.getChangeSetReader(schedule.getResourceId(), schedule - .getDriftConfiguration().getName()); - - int changes = 0; - - for (DirectoryEntry dirEntry : reader) { - DirectoryAnalyzer analyzer = new DirectoryAnalyzer(basedir, dirEntry); - analyzer.run(); + final AtomicInteger changes = new AtomicInteger(0);
- if (analyzer.getFilesAdded().size() > 0 || analyzer.getFilesRemoved().size() > 0 - || analyzer.getFilesChanged().size() > 0) { - DirectoryEntry driftDirEntry = new DirectoryEntry(dirEntry.getDirectory()); - DirectoryEntry coverageDirEntry = new DirectoryEntry(dirEntry.getDirectory()); - - // add new files to the directory entry - for (FileEntry entry : analyzer.getFilesAdded()) { - driftDirEntry.add(entry); - ++changes; - coverageDirEntry.add(entry); - } + final Set<File> processedFiles = new HashSet<File>();
- // add removed files to the directory entry - for (FileEntry entry : analyzer.getFilesRemoved()) { - driftDirEntry.add(entry); - ++changes; - dirEntry.remove(entry); - } - - // add changed files to the directory entry - for (FileEntry entry : analyzer.getFilesChanged()) { - driftDirEntry.add(entry); - ++changes; - dirEntry.remove(entry); - coverageDirEntry.add(entry); + // First look for files that have either been modified or deleted + for (FileEntry entry : coverageReader) { + File file = new File(basedir, entry.getFile()); + if (!file.exists()) { + // The file has been deleted since the last scan + driftWriter.write(removedFileEntry(entry.getFile(), entry.getNewSHA())); + changes.incrementAndGet(); + } else { + processedFiles.add(file); + String currentSHA = sha256(file); + if (!currentSHA.equals(entry.getNewSHA())) { + // The file has been updated + FileEntry modifiedEntry = changedFileEntry(entry.getFile(), entry.getNewSHA(), currentSHA); + driftWriter.write(modifiedEntry); + coverageWriter.write(modifiedEntry); + changes.incrementAndGet(); + } else { + // The file has not changed + coverageWriter.write(entry); } + } + }
- // add the remaining unchanged files to the coverage entry - for (FileEntry entry : dirEntry) { - coverageDirEntry.add(entry); + // Now we need to do a directory tree scan to look for newly added files + forEachFile(basedir, new FileVisitor() { + @Override + public void visit(File file) { + try { + if (processedFiles.contains(file)) { + return; + } + FileEntry newEntry = addedFileEntry(relativePath(basedir, file), sha256(file)); + driftWriter.write(newEntry); + coverageWriter.write(newEntry); + changes.incrementAndGet(); + } 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); } - - driftWriter.writeDirectoryEntry(driftDirEntry); - coverageWriter.writeDirectoryEntry(coverageDirEntry); - } else { - coverageWriter.writeDirectoryEntry(dirEntry); } - } + }); + driftWriter.close(); coverageWriter.close(); changeSetMgr.updateChangeSet(schedule.getResourceId(), createHeaders(schedule, COVERAGE));
- return changes; + return changes.get(); }
- private void generateCoverageChangeSet(DriftDetectionSchedule schedule) throws IOException { - ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, + private void generateCoverageChangeSet(final DriftDetectionSchedule schedule) throws IOException { + final ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, COVERAGE));
- DirectoryScanner scanner = new DirectoryScanner(schedule.getResourceId(), schedule.getDriftConfiguration(), - writer); - scanner.scan(); + final File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration())); + + forEachFile(basedir, new FileVisitor() { + @Override + public void visit(File file) { + try { + writer.write(addedFileEntry(relativePath(basedir, file), sha256(file))); + } catch (IOException e) { + log.error("An error occurred while generating a coverage change set for " + schedule + ": " + + e.getMessage()); + throw new DriftDetectionException("An error occurred while generating a coverage change set for " + + schedule, e); + } + } + }); + writer.close(); }
private String relativePath(File basedir, File file) { @@ -202,52 +219,4 @@ public class DriftDetector implements Runnable { return headers; }
- // TODO Do not use DirectoryWalker - // Want to do the file scan iteratively to keep memory overhead as low as possible. - private class DirectoryScanner extends DirectoryWalker { - - int resourceId; - DriftConfiguration driftConfig; - ChangeSetWriter writer; - Stack<DirectoryEntry> stack = new Stack<DirectoryEntry>(); - - public DirectoryScanner(int resourceId, DriftConfiguration driftConfig, ChangeSetWriter writer) { - this.resourceId = resourceId; - this.driftConfig = driftConfig; - this.writer = writer; - } - - public void scan() throws IOException { - walk(new File(basedir(resourceId, driftConfig)), EMPTY_LIST); - } - - @SuppressWarnings("unchecked") - @Override - protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException { - stack.push(new DirectoryEntry(relativePath(new File(basedir(resourceId, driftConfig)), directory))); - } - - @SuppressWarnings("unchecked") - @Override - protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { - DirectoryEntry dirEntry = stack.pop(); - if (dirEntry.getNumberOfFiles() > 0) { - writer.writeDirectoryEntry(dirEntry); - } - } - - @SuppressWarnings("unchecked") - @Override - protected void handleFile(File file, int depth, Collection results) throws IOException { - DirectoryEntry dirEntry = stack.peek(); - dirEntry.add(FileEntry.addedFileEntry(file.getName(), sha256(file))); - } - - @SuppressWarnings("unchecked") - @Override - protected void handleEnd(Collection results) throws IOException { - writer.close(); - } - } - } \ 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 73bb8b2..c035824 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 @@ -1,7 +1,5 @@ package org.rhq.core.pc.drift;
-import static org.rhq.core.util.file.FileUtil.copyFile; - import java.io.File; import java.io.IOException; import java.util.List; @@ -10,11 +8,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.common.drift.ChangeSetReader; -import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.domain.drift.DriftFile;
+import static org.rhq.core.util.file.FileUtil.copyFile; + public class DriftFilesSender implements Runnable {
private Log log = LogFactory.getLog(DriftFilesSender.class); @@ -72,16 +71,11 @@ public class DriftFilesSender implements Runnable {
private File find(DriftFile driftFile) throws IOException { ChangeSetReader reader = changeSetMgr.getChangeSetReader(resourceId, headers.getDriftConfigurationName()); - DirectoryEntry dirEntry = reader.readDirectoryEntry();
- while (dirEntry != null) { - for (FileEntry fileEntry : dirEntry) { - if (fileEntry.getNewSHA().equals(driftFile.getHashId())) { - File dir = new File(headers.getBasedir(), dirEntry.getDirectory()); - return new File(dir, fileEntry.getFile()); - } + for (FileEntry entry : reader) { + if (entry.getNewSHA().equals(driftFile.getHashId())) { + return new File(headers.getBasedir(), entry.getFile()); } - dirEntry = reader.readDirectoryEntry(); } return null; } 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 a914bfe..88cda7f 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 @@ -20,21 +20,17 @@ package org.rhq.core.pc.drift;
import java.io.File; -import java.util.List;
import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetWriter; -import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.Headers; import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import static java.util.Arrays.asList; import static org.rhq.common.drift.FileEntry.addedFileEntry; import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; -import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; @@ -57,13 +53,13 @@ public class ChangeSetManagerImplTest extends DriftTest { String serverConfHash = sha256(serverConf);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); - writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server.conf", serverConfHash))); + writer.write(addedFileEntry("conf/server.conf", serverConfHash)); writer.close();
ChangeSetReader reader = changeSetMgr.getChangeSetReader(resourceId(), config);
assertNotNull(reader, "Expected to get a change set reader when change set exists"); - assertReaderOpenedOnChangeSet(reader, asList("conf", "1")); + assertReaderOpenedOnChangeSet(reader); }
@Test @@ -76,7 +72,7 @@ public class ChangeSetManagerImplTest extends DriftTest { Headers headers = createHeaders(config, COVERAGE);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); - writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server.conf", sha256(serverConf)))); + writer.write(addedFileEntry("conf/server.conf", sha256(serverConf))); writer.close();
assertTrue(changeSetMgr.changeSetExists(resourceId(), headers), "Expected to find change set file."); @@ -89,30 +85,10 @@ public class ChangeSetManagerImplTest extends DriftTest { "Did not expect to find change set file."); }
- /** - * Verifies that a {@link ChangeSetReader} has been opened on the expected change set. - * This method first verifies that the reader is not null. It then reads the first - * {@link DirectoryEntry} from the reader and verifies that the directory and - * numberOfFiles properties match the expected values specified in dirEntry. - * <p/> - * This method does not rigorously check the entire contents of the change set file - * because that is handled by {@link ChangeSetReader} tests; rather, it aims to inspect - * just enough info to verify that the reader is opened on the correct change set. - * - * @param reader The ChangeSetReader returned from the ChangeSetManager under test - * @param dirEntry A list of strings representing the first line of a directory entry. - * The list should consist of two elements. The first being the directory path and the - * second being the number of files in the entry. - * @throws Exception - */ - void assertReaderOpenedOnChangeSet(ChangeSetReader reader, List<String> dirEntry) throws Exception { + void assertReaderOpenedOnChangeSet(ChangeSetReader reader) throws Exception { assertNotNull(reader, "The " + ChangeSetReader.class.getSimpleName() + " should not be null.");
- DirectoryEntry actual = reader.readDirectoryEntry(); - assertNotNull(actual, "Expected to find a directory entry"); - assertEquals(actual.getDirectory(), dirEntry.get(0), "The directory entry path is wrong"); - assertEquals(Integer.toString(actual.getNumberOfFiles()), dirEntry.get(1), - "The number of files for the directory entry is wrong"); + assertNotNull(reader.read(), "Expected to find a file entry"); }
Headers createHeaders(String driftConfigName, DriftChangeSetCategory type) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DirectoryAnalyzerTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DirectoryAnalyzerTest.java deleted file mode 100644 index 8f9588f..0000000 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DirectoryAnalyzerTest.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.rhq.core.pc.drift; - -import java.io.File; - -import org.testng.annotations.Test; - -import org.rhq.common.drift.DirectoryEntry; -import org.rhq.core.domain.drift.DriftConfiguration; - -import static java.util.Arrays.asList; -import static org.apache.commons.io.FileUtils.touch; -import static org.apache.commons.io.FileUtils.writeLines; -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.test.AssertUtils.assertCollectionMatchesNoOrder; - -public class DirectoryAnalyzerTest extends DriftTest { - - @SuppressWarnings("unchecked") - @Test - public void detectAddedFile() throws Exception { - DriftConfiguration config = driftConfiguration("added-files-test", resourceDir.getAbsolutePath()); - File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - - File changeSetDir = changeSetDir(config.getName()); - - // Generate the initial, coverage change set - writeChangeSet(changeSetDir, - config.getName(), - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 1", - sha256(server1Conf) + " 0 server-1.conf A", - "" - ); - - // Create some drift - File server2Conf = new File(confDir, "server-2.conf"); - touch(server2Conf); - - DirectoryAnalyzer analyzer = new DirectoryAnalyzer(resourceDir, new DirectoryEntry("conf") - .add(addedFileEntry(server1Conf.getName(), sha256(server1Conf)))); - analyzer.run(); - - assertCollectionMatchesNoOrder(asList(addedFileEntry("server-2.conf", sha256(server2Conf))), - analyzer.getFilesAdded(), "Failed to detect added file."); - } - - @SuppressWarnings("unchecked") - @Test - public void detectRemovedFile() throws Exception { - DriftConfiguration config = driftConfiguration("added-files-test", resourceDir.getAbsolutePath()); - File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - File server2Conf = new File(confDir, "server-2.conf"); - touch(server2Conf); - - String server2ConfHash = sha256(server2Conf); - - File changeSetDir = changeSetDir(config.getName()); - - // Generate the initial, coverage change set - writeChangeSet(changeSetDir, - config.getName(), - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 1", - sha256(server1Conf) + " 0 server-1.conf A", - server2ConfHash + " 0 server-2.conf A", - "" - ); - - // create some drift - server2Conf.delete(); - - DirectoryAnalyzer analyzer = new DirectoryAnalyzer(resourceDir, new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", sha256(server1Conf))) - .add(addedFileEntry("server-2.conf", server2ConfHash))); - analyzer.run(); - - assertCollectionMatchesNoOrder(asList(removedFileEntry("server-2.conf", server2ConfHash)), - analyzer.getFilesRemoved(), "Failed to detect removed file."); - } - - @SuppressWarnings("unchecked") - @Test - public void detectChangedFile() throws Exception { - DriftConfiguration config = driftConfiguration("changed-files-test", resourceDir.getAbsolutePath()); - File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - - String server1ConfHash = sha256(server1Conf); - File changeSetDir = changeSetDir(config.getName()); - - // generate the initial, coverage changes set - writeChangeSet(changeSetDir, - config.getName(), - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 1", - sha256(server1Conf) + " 0 server-1.conf A", - "" - ); - - // create some drift - writeLines(server1Conf, asList("This is a test", "Testing a changed file")); - - DirectoryAnalyzer analyzer = new DirectoryAnalyzer(resourceDir, new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", server1ConfHash))); - analyzer.run(); - - assertCollectionMatchesNoOrder(asList(changedFileEntry("server-1.conf", server1ConfHash, sha256(server1Conf))), - analyzer.getFilesChanged(), "Failed to detect changed files."); - } -} 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 9e59e61..5d25e9d 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 @@ -23,30 +23,29 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; -import java.util.Collection; import java.util.List;
-import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetReaderImpl; import org.rhq.common.drift.ChangeSetWriter; -import org.rhq.common.drift.DirectoryEntry; 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 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.assertNotNull; import static org.testng.Assert.assertTrue;
public class DriftDetectorTest extends DriftTest { @@ -74,7 +73,10 @@ public class DriftDetectorTest extends DriftTest { @Test public void excludeEmptyDirsFromCoverageChangeSet() throws Exception { File confDir = mkdir(resourceDir, "conf"); - touch(new File(confDir, "server.conf")); + File serverConf = createRandomFile(confDir, "server.conf"); + + // create an empty directory + File libDir = mkdir(resourceDir, "lib");
DriftConfiguration driftConfig = driftConfiguration("coverage-test", resourceDir.getAbsolutePath());
@@ -82,43 +84,19 @@ public class DriftDetectorTest extends DriftTest { detector.run();
File changeSet = changeSet(driftConfig.getName(), COVERAGE); + Headers headers = createHeaders(driftConfig, COVERAGE); + List<FileEntry> expected = asList(addedFileEntry("conf/server.conf", sha256(serverConf)));
- assertHeaderEquals(changeSet, createHeaders(driftConfig, COVERAGE)); - assertThatChangeSetDoesNotContainEmptyDirs(changeSet); - } - - @SuppressWarnings("unchecked") - @Test - public void usePeriodAsNameOfBasedirDirectoryEntry() throws Exception { - File data1 = new File(resourceDir, "data-1.txt"); - touch(data1); - File data2 = new File(resourceDir, "data-2.txt"); - touch(data2); - - DriftConfiguration driftConfig = driftConfiguration("basedir-entry-test", resourceDir.getAbsolutePath()); - - scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), driftConfig)); - detector.run(); - - DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), driftConfig); - - scheduleQueue.addSchedule(schedule); - detector.run(); - - assertChangeSetContainsDirEntry(changeSet(driftConfig.getName(), COVERAGE), - new DirectoryEntry(".") - .add(addedFileEntry("data-1.txt", sha256(data1))) - .add(addedFileEntry("data-2.txt", sha256(data2)))); + assertHeaderEquals(changeSet, headers); + assertFileEntriesMatch("Only files should be included in a change set.", expected, changeSet); }
@SuppressWarnings("unchecked") @Test public void includeMultipleFilesInDirInCoverageChangeSet() throws Exception { File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - File server2Conf = new File(confDir, "server-2.conf"); - touch(server2Conf); + File server1Conf = createRandomFile(confDir, "server-1.conf"); + File server2Conf = createRandomFile(confDir, "server-2.conf");
DriftConfiguration config = driftConfiguration("multiple-files-test", resourceDir.getAbsolutePath());
@@ -126,24 +104,23 @@ public class DriftDetectorTest extends DriftTest { 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)));
assertHeaderEquals(changeSet, createHeaders(config, COVERAGE)); - assertChangeSetContainsDirEntry(changeSet, - new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", sha256(server1Conf))) - .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + assertFileEntriesMatch("Each file in a directory should be included in a coverage change set", entries, + changeSet); }
@SuppressWarnings("unchecked") @Test public void includedSiblingDirsInCoverageChangeSet() throws Exception { File confDir = mkdir(resourceDir, "conf"); - File serverConf = new File(confDir, "server.conf"); - touch(serverConf); + File serverConf = createRandomFile(confDir, "server.conf");
File libDir = mkdir(resourceDir, "lib"); - File serverLib = new File(libDir, "server.jar"); - touch(serverLib); + File serverLib = createRandomFile(libDir, "server.jar");
DriftConfiguration config = driftConfiguration("sibling-dirs-test", resourceDir.getAbsolutePath());
@@ -151,25 +128,23 @@ public class DriftDetectorTest extends DriftTest { detector.run();
File changeSet = changeSet(config.getName(), COVERAGE); + List<FileEntry> entries = asList( + addedFileEntry("conf/server.conf", sha256(serverConf)), + addedFileEntry("lib/server.jar", sha256(serverLib)));
assertHeaderEquals(changeSet, createHeaders(config, COVERAGE)); - - assertChangeSetContainsDirEntry(changeSet, - new DirectoryEntry("conf").add(addedFileEntry("server.conf", sha256(serverConf)))); - assertChangeSetContainsDirEntry(changeSet, - new DirectoryEntry("lib").add(addedFileEntry("server.jar", sha256(serverLib)))); + assertFileEntriesMatch("A coverage change set should include files from multiple, sibling directories", + entries, changeSet); }
@SuppressWarnings("unchecked") @Test public void includeNestedDirsInCoverageChangeSet() throws Exception { File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); + File server1Conf = createRandomFile(confDir, "server-1.conf");
File subConfDir = mkdir(confDir, "subconf"); - File server2Conf = new File(subConfDir, "server-2.conf"); - touch(server2Conf); + File server2Conf = createRandomFile(subConfDir, "server-2.conf");
DriftConfiguration config = driftConfiguration("nested-dirs-test", resourceDir.getAbsolutePath());
@@ -177,13 +152,13 @@ public class DriftDetectorTest extends DriftTest { 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)));
assertHeaderEquals(changeSet, createHeaders(config, COVERAGE)); - - assertChangeSetContainsDirEntry(changeSet, - new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); - assertChangeSetContainsDirEntry(changeSet, - new DirectoryEntry("conf/subconf").add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + assertFileEntriesMatch("A coverage change set should include files in nested sub directories", entries, + changeSet); }
@SuppressWarnings("unchecked") @@ -218,39 +193,75 @@ public class DriftDetectorTest extends DriftTest { DriftConfiguration config = driftConfiguration("file-added-drift-test", resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); + File server1Conf = createRandomFile(confDir, "server-1.conf");
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); - writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); + writer.write(addedFileEntry("conf/server-1.conf", sha256(server1Conf))); writer.close();
// Create some drift - File server2Conf = new File(confDir, "server-2.conf"); - touch(server2Conf); + File server2Conf = createRandomFile(confDir, "server-2.conf");
scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config)); detector.run();
File driftChangeSet = changeSet(config.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)); + 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)), + addedFileEntry("conf/server-2.conf", sha256(server2Conf))); + + // verify that the coverage change set was updated + assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); + assertFileEntriesMatch("The coverage change set was not updated as expected", coverageEntries, + coverageChangeSet); + } + + @SuppressWarnings("unchecked") + @Test + public void includeModifiedFileInDriftChangeSet() throws Exception { + DriftConfiguration config = driftConfiguration("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)); + writer.write(addedFileEntry("conf/server-1.conf", oldHash)); + writer.close(); + + // create some drift + server1Conf.delete(); + server1Conf = createRandomFile(confDir, "server-1.conf"); + String newHash = sha256(server1Conf); + + scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config)); + detector.run(); + + File driftChangeSet = changeSet(config.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)); - assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") - .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + assertFileEntriesMatch("The drift change set does not match the expected values", driftEntries, driftChangeSet);
File coverageChangeSet = changeSet(config.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)); - assertChangeSetContainsDirEntry(coverageChangeSet, new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", sha256(server1Conf))) - .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + assertFileEntriesMatch("The coverage change set was not updated as expected", coverageEntries, + coverageChangeSet); }
- // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") @Test(enabled = false) public void includeFiledAddedInNewDirectoryInDriftChangeSet() throws Exception { @@ -260,7 +271,7 @@ public class DriftDetectorTest extends DriftTest { File server1Conf = createRandomFile(confDir, "server-1.conf");
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); - writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); + writer.write(addedFileEntry("conf/server-1.conf", sha256(server1Conf))); writer.close();
// create some drift @@ -271,10 +282,22 @@ public class DriftDetectorTest extends DriftTest { detector.run();
File driftChangeSet = changeSet(config.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)); + 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)), + addedFileEntry("conf/subconf/server-2.conf", sha256(server2Conf)));
- assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("subconf") - .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + // verify that the coverage change set was updated + assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); + assertFileEntriesMatch("The coverage change set was not updated as expected", coverageEntries, + coverageChangeSet); }
@SuppressWarnings("unchecked") @@ -283,17 +306,14 @@ public class DriftDetectorTest extends DriftTest { DriftConfiguration config = driftConfiguration("file-removed-drift-test", resourceDir.getAbsolutePath());
File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - File server2Conf = new File(confDir, "server-2.conf"); - touch(server2Conf); + File server1Conf = createRandomFile(confDir, "server-1.conf"); + File server2Conf = createRandomFile(confDir, "server-2.conf");
String server2ConfHash = sha256(server2Conf);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); - writer.writeDirectoryEntry(new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", sha256(server1Conf))) - .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.write(addedFileEntry("conf/server-1.conf", sha256(server1Conf))); + writer.write(addedFileEntry("conf/server-2.conf", server2ConfHash)); writer.close();
// create some drift @@ -303,22 +323,22 @@ public class DriftDetectorTest extends DriftTest { detector.run();
File driftChangeSet = changeSet(config.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)); - assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") - .add(removedFileEntry("server-2.conf", server2ConfHash))); + 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(addedFileEntry("conf/server-1.conf", sha256(server1Conf)));
assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); - assertChangeSetContainsDirEntry(coverageChangeSet, new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", sha256(server1Conf)))); + assertFileEntriesMatch("The coverage change set was not updated as expected", coverageEntries, + coverageChangeSet); }
- // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") @Test(enabled = false) public void includeFilesInRemovedDirectoryInDriftChangeSet() throws Exception { @@ -329,7 +349,7 @@ public class DriftDetectorTest extends DriftTest { String server1Hash = sha256(server1Conf);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); - writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", server1Hash))); + writer.write(addedFileEntry("conf/server-1.conf", server1Hash)); writer.close();
// create some drift @@ -337,12 +357,20 @@ public class DriftDetectorTest extends DriftTest { confDir.delete();
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)); + assertFileEntriesMatch("The drift change set does not match the expected values", driftEntries, driftChangeSet);
- assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") - .add(removedFileEntry("server-1.conf", server1Hash))); + // verify that the coverage change set was updated + File coverageChangeSet = changeSet(config.getName(), COVERAGE); + List<FileEntry> coverageEntries = emptyList(); + + assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); + assertFileEntriesMatch("The coverage change set was not updated as expected", coverageEntries, + coverageChangeSet); }
void assertHeaderEquals(File changeSet, Headers expected) throws Exception { @@ -352,31 +380,15 @@ public class DriftDetectorTest extends DriftTest { "expected values"); }
- void assertThatChangeSetDoesNotContainEmptyDirs(File changeSet) throws Exception { - ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new FileReader(changeSet))); - DirectoryEntry dirEntry = reader.readDirectoryEntry(); - - while (dirEntry != null) { - Assert.assertTrue(dirEntry.getNumberOfFiles() > 0, "The change set file should not include empty " - + "directories"); - dirEntry = reader.readDirectoryEntry(); - } - } - - void assertChangeSetContainsDirEntry(File changeSet, DirectoryEntry expected) throws Exception { + void assertFileEntriesMatch(String msg, List<FileEntry> expected, File changeSet) throws Exception { + List<FileEntry> actual = new ArrayList<FileEntry>(); ChangeSetReader reader = new ChangeSetReaderImpl(changeSet); - DirectoryEntry actual = null;
- for (DirectoryEntry entry : reader) { - if (entry.getDirectory().equals(expected.getDirectory())) { - actual = entry; - break; - } + for (FileEntry entry : reader) { + actual.add(entry); }
- assertNotNull(actual, "Failed to find " + expected + " in " + changeSet.getPath()); - assertCollectionMatchesNoOrder(fileEntries(expected), fileEntries(actual), "File entries for " + - expected + " in change set " + changeSet.getPath() + " do not match"); + assertCollectionMatchesNoOrder(msg, expected, actual); }
Headers createHeaders(DriftConfiguration driftConfig, DriftChangeSetCategory type) { @@ -390,12 +402,4 @@ public class DriftDetectorTest extends DriftTest { return headers; }
- Collection<FileEntry> fileEntries(DirectoryEntry dirEntry) { - List<FileEntry> list = new ArrayList<FileEntry>(); - for (FileEntry entry : dirEntry) { - list.add(entry); - } - return list; - } - } 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 30ebe6a..bace111 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 @@ -27,7 +27,6 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetWriter; -import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.Headers; import org.rhq.core.domain.drift.DriftChangeSetCategory; import org.rhq.core.domain.drift.DriftFile; @@ -70,9 +69,8 @@ public class DriftFilesSenderTest extends DriftTest { Headers headers = createHeaders(driftConfigName, COVERAGE);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); - writer.writeDirectoryEntry(new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", server1ConfHash)) - .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.write(addedFileEntry("conf/server-1.conf", server1ConfHash)); + writer.write(addedFileEntry("conf/server-2.conf", server2ConfHash)); writer.close();
sender.setDriftFiles(driftFiles(server1ConfHash, server2ConfHash)); @@ -107,12 +105,10 @@ public class DriftFilesSenderTest extends DriftTest { Headers headers = createHeaders(driftConfigName, COVERAGE);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); - writer.writeDirectoryEntry(new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", server1ConfHash)) - .add(addedFileEntry("server-2.conf", server2ConfHash))); - writer.writeDirectoryEntry(new DirectoryEntry("lib") - .add(addedFileEntry("server-1.jar", server1JarHash)) - .add(addedFileEntry("server-2.jar", server2JarHash))); + writer.write(addedFileEntry("conf/server-1.conf", server1ConfHash)); + writer.write(addedFileEntry("conf/server-2.conf", server2ConfHash)); + writer.write(addedFileEntry("lib/server-1.jar", server1JarHash)); + writer.write(addedFileEntry("lib/server-2.jar", server2JarHash)); writer.close();
// Note that the order of the drift files is random. When the server sends a request @@ -146,9 +142,8 @@ public class DriftFilesSenderTest extends DriftTest { Headers headers = createHeaders(driftConfigName, COVERAGE);
ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); - writer.writeDirectoryEntry(new DirectoryEntry("conf") - .add(addedFileEntry("server-1.conf", server1ConfHash)) - .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.write(addedFileEntry("conf/server-1.conf", server1ConfHash)); + writer.write(addedFileEntry("conf/server-2.conf", server2ConfHash)); writer.close();
// It is possible that the server can request a file that has been deleted since it diff --git a/modules/core/util/pom.xml b/modules/core/util/pom.xml index 4b50b78..dfa5bb8 100644 --- a/modules/core/util/pom.xml +++ b/modules/core/util/pom.xml @@ -38,6 +38,20 @@ <artifactId>i18nlog</artifactId> </dependency>
+ <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>test-utils</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + <version>1.4</version> + <scope>test</scope> + </dependency> + </dependencies>
<build> 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 d40f822..be7310f 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 @@ -33,6 +33,9 @@ import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.Deque; +import java.util.LinkedList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
@@ -319,4 +322,30 @@ public class FileUtil { public static String useForwardSlash(String path) { return path.replace('\', '/'); } + + /** + * Performs a breadth-first scan, calling <code>visitor</code> for each file in + * <code>directory</code>. Sub directories are scanned as well. Note that if + * <code>visitor</code> throws a RuntimeException it will not be called again as this + * method does not provide any exception handling. + * + * @param directory The directory over which to iterate + * @param visitor The callback to invoke for each file + */ + public static void forEachFile(File directory, FileVisitor visitor) { + Deque<File> directories = new LinkedList<File>(); + directories.push(directory); + + while(!directories.isEmpty()) { + File dir = directories.pop(); + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + directories.push(file); + } else { + visitor.visit(file); + } + } + } + } + } \ No newline at end of file diff --git a/modules/core/util/src/main/java/org/rhq/core/util/file/FileVisitor.java b/modules/core/util/src/main/java/org/rhq/core/util/file/FileVisitor.java new file mode 100644 index 0000000..c077896 --- /dev/null +++ b/modules/core/util/src/main/java/org/rhq/core/util/file/FileVisitor.java @@ -0,0 +1,37 @@ +/* + * 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.util.file; + +import java.io.File; + +/** + * A callback interface that is used with {@link FileUtil#forEachFile(java.io.File, FileVisitor)} + * to iterate over files in a directory tree. + */ +public interface FileVisitor { + + /** + * Invoked for each file in a directory tree. + * + * @param file The current in the iteration + */ + void visit(File file); + +} diff --git a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java index a3a8c44..cd53a06 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/file/FileUtilTest.java @@ -22,8 +22,18 @@ */ package org.rhq.core.util.file;
+import java.io.File; +import java.util.ArrayList; +import java.util.List; + import org.testng.annotations.Test;
+import static java.util.Arrays.asList; +import static org.apache.commons.io.FileUtils.deleteDirectory; +import static org.apache.commons.io.FileUtils.toFile; +import static org.apache.commons.io.FileUtils.touch; +import static org.rhq.test.AssertUtils.assertCollectionEqualsNoOrder; + @Test public class FileUtilTest { public void testStripDriveLetter() { @@ -109,4 +119,98 @@ public class FileUtilTest { assert FileUtil.stripDriveLetter(str) == null; assert str.toString().equals("hello:world/hello"); } + + @Test + public void visitEachFileInDir() throws Exception { + File dir = new File(toFile(getClass().getResource(".")), "visit-each-file-in-dir"); + deleteDirectory(dir); + dir.mkdirs(); + + File file1 = new File(dir, "file-1"); + touch(file1); + File file2 = new File(dir, "file-2"); + touch(file2); + + List<File> expectedFiles = asList(file1, file2); + final List<File> actualFiles = new ArrayList<File>(); + + FileUtil.forEachFile(dir, new FileVisitor() { + @Override + public void visit(File file) { + actualFiles.add(file); + } + }); + + assertCollectionEqualsNoOrder(expectedFiles, actualFiles, + "Expected to visit all files in directory"); + } + + @Test + public void visitFilesInSubdirectories() throws Exception { + File dir = new File(toFile(getClass().getResource(".")), "visit-files-in-sub-dirs"); + deleteDirectory(dir); + dir.mkdirs(); + + File file1 = new File(dir, "file-1"); + touch(file1); + + File subdir1 = new File(dir, "subdir-1"); + subdir1.mkdir(); + + File file2 = new File(subdir1, "file-2"); + touch(file2); + + File subdir2 = new File(dir, "subdir-2"); + + File file3 = new File(subdir2, "file-3"); + touch(file3); + + List<File> expectedFiles = asList(file1, file2, file3); + final List<File> actualFiles = new ArrayList<File>(); + + FileUtil.forEachFile(dir, new FileVisitor() { + @Override + public void visit(File file) { + actualFiles.add(file); + } + }); + + assertCollectionEqualsNoOrder(expectedFiles, actualFiles, + "Expected to visit files in sub directories"); + } + + @Test + public void visitFilesInNestedSubDirectories() throws Exception { + File dir = new File(toFile(getClass().getResource(".")), "visit-files-in-nested-sub-dirs"); + deleteDirectory(dir); + dir.mkdirs(); + + File file1 = new File(dir, "file-1"); + touch(file1); + + File subdir1 = new File(dir, "subdir-1"); + subdir1.mkdir(); + + File file2 = new File(subdir1, "file-2"); + touch(file2); + + File subdir2 = new File(subdir1, "subdir-2"); + + File file3 = new File(subdir2, "file-3"); + touch(file3); + + List<File> expectedFiles = asList(file1, file2, file3); + final List<File> actualFiles = new ArrayList<File>(); + + FileUtil.forEachFile(dir, new FileVisitor() { + @Override + public void visit(File file) { + actualFiles.add(file); + } + }); + + assertCollectionEqualsNoOrder(expectedFiles, actualFiles, + "Expected to visit files in nested sub directories"); + } + } 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 35c3115..163ad16 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,8 +19,6 @@ */ package org.rhq.enterprise.server.drift;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; - import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -28,7 +26,6 @@ import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -45,7 +42,6 @@ import org.hibernate.Hibernate;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetReaderImpl; -import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.clientapi.agent.drift.DriftAgentService; @@ -76,6 +72,8 @@ import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + /** * The SLSB method implementation needed to support the JPA (RHQ Default) Drift Server Plugin. * @@ -216,30 +214,21 @@ public class JPADriftServerBean implements JPADriftServerLocal { driftChangeSet = new JPADriftChangeSet(resource, version, category, config); entityManager.persist(driftChangeSet);
- for (DirectoryEntry dir = reader.readDirectoryEntry(); null != dir; dir = reader - .readDirectoryEntry()) { - - for (Iterator<FileEntry> i = dir.iterator(); i.hasNext();) { - FileEntry entry = i.next(); - JPADriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), - (List<JPADriftFile>) emptyDriftFiles); - JPADriftFile newDriftFile = getDriftFile(entry.getNewSHA(), - (List<JPADriftFile>) emptyDriftFiles); - - // TODO Figure out an efficient way to save coverage change sets. - // The initial/coverage change set could contain hundreds or even thousands - // of entries. We probably want to consider doing some kind of batch insert - // - // jsanda - - // use a path with only forward slashing to ensure consistent paths across reports - String path = new File(dir.getDirectory(), entry.getFile()).getPath(); - path = FileUtil.useForwardSlash(path); - JPADrift drift = new JPADrift(driftChangeSet, path, entry.getType(), oldDriftFile, - newDriftFile); - entityManager.persist(drift); - - } + for (FileEntry entry : reader) { + JPADriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), emptyDriftFiles); + JPADriftFile newDriftFile = getDriftFile(entry.getNewSHA(), emptyDriftFiles); + + // TODO Figure out an efficient way to save coverage change sets. + // The initial/coverage change set could contain hundreds or even thousands + // of entries. We probably want to consider doing some kind of batch insert + // + // jsanda + + // use a path with only forward slashing to ensure consistent paths across reports + String path = FileUtil.useForwardSlash(entry.getFile()); + JPADrift drift = new JPADrift(driftChangeSet, path, entry.getType(), oldDriftFile, + newDriftFile); + entityManager.persist(drift); } // send a message to the agent requesting the empty JPADriftFile content if (!emptyDriftFiles.isEmpty()) { 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 4c84169..b46f003 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 @@ -19,7 +19,6 @@ package org.rhq.enterprise.server.drift;
import java.io.File; -import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import java.util.Random; @@ -35,8 +34,6 @@ import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetWriter; import org.rhq.common.drift.ChangeSetWriterImpl; -import org.rhq.common.drift.DirectoryEntry; -import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.clientapi.agent.drift.DriftAgentService; import org.rhq.core.clientapi.server.drift.DriftServerService; @@ -68,7 +65,6 @@ 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.apache.commons.io.IOUtils.write; 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; @@ -154,7 +150,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
File changeSet1 = new File(changeSetsDir, "changeset-1.txt"); ChangeSetWriter writer = new ChangeSetWriterImpl(changeSet1, headers); - writer.writeDirectoryEntry(new DirectoryEntry("test").add(addedFileEntry("file-1", file1Hash))); + writer.write(addedFileEntry("test/file-1", file1Hash)); writer.close();
File changeSet1Zip = new File(changeSetsDir, "changeset-1.zip"); @@ -183,7 +179,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { File changeSet2 = new File(changeSetsDir, "changeset-2.txt");
writer = new ChangeSetWriterImpl(changeSet2, headers); - writer.writeDirectoryEntry(new DirectoryEntry("test").add(changedFileEntry("file-1", file1Hash, modifiedFile1Hash))); + writer.write(changedFileEntry("test/file-1", file1Hash, modifiedFile1Hash)); writer.close();
File changeSet2Zip = new File(changeSetsDir, "changeset-2.zip"); 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 989211f..cb22062 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 @@ -38,7 +38,6 @@ import org.bson.types.ObjectId;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetReaderImpl; -import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.domain.auth.Subject; @@ -116,15 +115,12 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC changeSet.setDriftConfigurationId(1); changeSet.setVersion(changeSetVersions++);
- for (DirectoryEntry dirEntry : reader) { - for (FileEntry fileEntry : dirEntry) { - String path = new File(dirEntry.getDirectory(), fileEntry.getFile()).getPath(); - path = FileUtil.useForwardSlash(path); - MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(); - entry.setCategory(fileEntry.getType()); - entry.setPath(path); - changeSet.add(entry); - } + for (FileEntry fileEntry : reader) { + String path = FileUtil.useForwardSlash(fileEntry.getFile()); + MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(); + entry.setCategory(fileEntry.getType()); + entry.setPath(path); + changeSet.add(entry); }
ds.save(changeSet); diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/GridFSTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/GridFSTest.java new file mode 100644 index 0000000..5a76a2b --- /dev/null +++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/GridFSTest.java @@ -0,0 +1,63 @@ +/* + * 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.server.plugins.drift.mongodb; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; + +import com.mongodb.DB; +import com.mongodb.Mongo; +import com.mongodb.gridfs.GridFS; +import com.mongodb.gridfs.GridFSDBFile; +import com.mongodb.gridfs.GridFSInputFile; + +import org.bson.types.ObjectId; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class GridFSTest { + + Mongo connection; + + DB db; + + @BeforeClass + public void initDB() throws Exception { + connection = new Mongo("localhost"); + connection.dropDatabase("rhqtest"); + db = connection.getDB("rhqtest"); + + } + + @Test(enabled = false) + public void writeFile() throws Exception { + GridFS gridFS = new GridFS(db); + File file = new File("/home/jsanda/clojure-plugin.tar"); + GridFSInputFile inputFile = gridFS.createFile(new FileInputStream(file), file.getName()); + + inputFile.save(); + + FileOutputStream stream = new FileOutputStream("/home/jsanda/gridfs-test.tar"); + GridFSDBFile gridFSDBFile = gridFS.findOne((ObjectId) inputFile.getId()); + gridFSDBFile.writeTo(stream); + } + +}
commit 1b01b3a1b11699eea2d6ca2c3ac6b5575eb04803 Merge: b1175b6 a519c56 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 10 08:51:45 2011 +0200
Merge remote-tracking branch 'origin/master' into feature/config-sync
commit b1175b682f43480ee7fa3480b0ae3390388030bb Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 10 08:43:45 2011 +0200
Some tests, more to come.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java index ae76e24..9399b62 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java @@ -25,7 +25,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; -import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; @@ -64,15 +63,15 @@ public class ExportingInputStream extends InputStream { public static final String VALIDATOR_ELEMENT = "validator"; public static final String ID_ATTRIBUTE = "id"; public static final String CLASS_ATTRIBUTE = "class"; - + private Set<Synchronizer<?, ?>> synchronizers; private Map<String, ExporterMessages> messagesPerExporter; private PipedInputStream inputStream; private PipedOutputStream exportOutput; private Thread exportRunner; - private Throwable uncaughtExporterException; + private Throwable unexpectedExporterException; private boolean zipOutput; - + /** * Constructs a new exporting input stream with the default buffer size of 64KB that zips up * the results. @@ -93,8 +92,8 @@ public class ExportingInputStream extends InputStream { * @param zip whether to zip the export data * @throws IOException on failure */ - public ExportingInputStream(Set<Synchronizer<?, ?>> synchronizers, Map<String, ExporterMessages> messagesPerExporter, - int size, boolean zip) throws IOException { + public ExportingInputStream(Set<Synchronizer<?, ?>> synchronizers, + Map<String, ExporterMessages> messagesPerExporter, int size, boolean zip) throws IOException { this.synchronizers = synchronizers; this.messagesPerExporter = messagesPerExporter; inputStream = new PipedInputStream(size); @@ -167,21 +166,14 @@ public class ExportingInputStream extends InputStream {
exportRunner.setDaemon(true); exportRunner.setName("Configuration Export Thread"); - exportRunner.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
- @Override - public void uncaughtException(Thread t, Throwable e) { - uncaughtExporterException = e; - } - }); - exportRunner.setContextClassLoader(Thread.currentThread().getContextClassLoader()); - + exportRunner.start(); }
- if (uncaughtExporterException != null) { - throw new IOException("The exporter thread failed with an uncaught exception.", uncaughtExporterException); + if (unexpectedExporterException != null) { + throw new IOException("The exporter thread failed with an uncaught exception.", unexpectedExporterException); } }
@@ -193,7 +185,7 @@ public class ExportingInputStream extends InputStream {
try { out = exportOutput; - if (zipOutput) { + if (zipOutput) { out = new GZIPOutputStream(out); } wrt = ofactory.createXMLStreamWriter(out, "UTF-8"); @@ -203,17 +195,17 @@ public class ExportingInputStream extends InputStream { }
exportPrologue(wrt); - + for (Synchronizer<?, ?> exp : synchronizers) { exportSingle(wrt, exp); } - - exportEpilogue(wrt); - + + exportEpilogue(wrt); + wrt.flush(); } catch (Exception e) { LOG.error("Error while exporting.", e); - throw new RuntimeException(e); + unexpectedExporterException = e; } finally { if (wrt != null) { try { @@ -242,12 +234,12 @@ public class ExportingInputStream extends InputStream { */ private void writeValidators(XMLStreamWriter wrt) throws XMLStreamException { Set<ConsistencyValidator> allValidators = new HashSet<ConsistencyValidator>(); - - for(Synchronizer<?, ?> syn : synchronizers) { + + for (Synchronizer<?, ?> syn : synchronizers) { allValidators.addAll(syn.getRequiredValidators()); } - - for(ConsistencyValidator cv : allValidators) { + + for (ConsistencyValidator cv : allValidators) { wrt.writeStartElement(VALIDATOR_ELEMENT); wrt.writeAttribute(CLASS_ATTRIBUTE, cv.getClass().getName()); cv.exportState(new ExportWriter(wrt)); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java index 1e593f9..66caf35 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/MetricTemplateImporter.java @@ -32,6 +32,9 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLStreamException;
+import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import org.rhq.core.clientapi.agent.configuration.ConfigurationUtility; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.Configuration; @@ -40,7 +43,6 @@ 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.configuration.definition.ConfigurationDefinition; -import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap; import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple; @@ -58,6 +60,8 @@ import org.rhq.enterprise.server.util.LookupUtil; */ public class MetricTemplateImporter implements Importer<MeasurementDefinition, MetricTemplate> {
+ private static final Log LOG = LogFactory.getLog(MetricTemplateImporter.class); + private static final boolean UPDATE_SCHEDULES_DEFAULT = false; private static final String UPDATE_ALL_SCHEDULES_PROPERTY = "updateAllSchedules"; private static final String METRIC_NAME_PROPERTY = "metricName"; @@ -71,7 +75,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M public long collectionInterval; public boolean updateSchedules;
- @Override + @Override public int hashCode() { return (int) collectionInterval * (updateSchedules ? 31 : 1); } @@ -100,8 +104,13 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M new HashMap<MetricTemplateImporter.CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>>(); private Configuration importConfiguration; private Unmarshaller unmarshaller; + private MeasurementScheduleManagerLocal measurementScheduleManager;
public MetricTemplateImporter(Subject subject, EntityManager entityManager) { + this(subject, entityManager, LookupUtil.getMeasurementScheduleManager()); + } + + public MetricTemplateImporter(Subject subject, EntityManager entityManager, MeasurementScheduleManagerLocal measurementScheduleManager) { try { this.subject = subject; this.entityManager = entityManager; @@ -110,6 +119,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M } catch (JAXBException e) { throw new IllegalStateException("Failed to initialize JAXB marshaller for MetricTemplate.", e); } + this.measurementScheduleManager = measurementScheduleManager; }
@Override @@ -145,15 +155,23 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
@Override public MeasurementDefinition findMatch(MetricTemplate object) { - Query q = entityManager.createNamedQuery(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME); + Query q = entityManager + .createNamedQuery(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME); q.setParameter("name", object.getMetricName()); q.setParameter("resourceTypeName", object.getResourceTypeName()); q.setParameter("resourceTypePlugin", object.getResourceTypePlugin()); q.setParameter("perMinute", object.isPerMinute() ? 1 : 0); - + List<?> results = q.getResultList();
if (results.isEmpty()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Failed to find a measurement definition corresponding to " + + object + + ". This means that the plugins in the source RHQ install were different than in this RHQ install " + + "but the DeployedAgentPluginsValidator failed to catch that. This most probably means that the " + + "export file has been tampered with. Letting the import continue because that might have been intentional change by the user."); + } return null; } else if (results.size() > 1) { throw new IllegalStateException( @@ -168,6 +186,10 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
@Override public void update(MeasurementDefinition entity, MetricTemplate exportedEntity) { + if (entity == null) { + return; + } + if (exportedEntity.isEnabled()) { definitionsToEnable.add(entity); } else { @@ -188,17 +210,17 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M
@Override public void finishImport() { - MeasurementScheduleManagerLocal sm = LookupUtil.getMeasurementScheduleManager(); - - sm.enableMeasurementTemplates(subject, getIdsFromDefs(definitionsToEnable)); - sm.disableMeasurementTemplates(subject, getIdsFromDefs(definitionsToDisable)); + measurementScheduleManager.enableMeasurementTemplates(subject, getIdsFromDefs(definitionsToEnable)); + measurementScheduleManager.disableMeasurementTemplates(subject, getIdsFromDefs(definitionsToDisable));
- for (Map.Entry<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> e : definitionsByCollectionIntervalAndUpdateSchedules.entrySet()) { - sm.updateDefaultCollectionIntervalForMeasurementDefinitions(subject, getIdsFromDefs(e.getValue()), e.getKey().collectionInterval, - e.getKey().updateSchedules); + for (Map.Entry<CollectionIntervalAndUpdateSchedules, List<MeasurementDefinition>> e : definitionsByCollectionIntervalAndUpdateSchedules + .entrySet()) { + measurementScheduleManager.updateDefaultCollectionIntervalForMeasurementDefinitions(subject, getIdsFromDefs(e.getValue()), + e.getKey().collectionInterval, e.getKey().updateSchedules); } }
+ private static int[] getIdsFromDefs(Collection<MeasurementDefinition> defs) { int[] ids = new int[defs.size()];
@@ -214,7 +236,7 @@ public class MetricTemplateImporter implements Importer<MeasurementDefinition, M CollectionIntervalAndUpdateSchedules key = new CollectionIntervalAndUpdateSchedules(); key.collectionInterval = metricTemplate.getDefaultInterval(); key.updateSchedules = shouldUpdateSchedules(metricTemplate); - + List<MeasurementDefinition> defs = definitionsByCollectionIntervalAndUpdateSchedules.get(key);
if (defs == null) { diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java index 195e080..6003e58 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/ExportingInputStreamTest.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.server.sync.test;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail;
import java.io.ByteArrayInputStream; import java.io.IOException; @@ -41,6 +42,7 @@ import javax.xml.stream.XMLStreamException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.jmock.Expectations; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -49,7 +51,6 @@ import org.w3c.dom.NodeList;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.sync.ExporterMessages; -import org.rhq.enterprise.server.sync.ExportException; import org.rhq.enterprise.server.sync.ExportWriter; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.NoSingleEntity; @@ -59,6 +60,7 @@ import org.rhq.enterprise.server.sync.exporters.Exporter; import org.rhq.enterprise.server.sync.exporters.ExportingIterator; import org.rhq.enterprise.server.sync.importers.Importer; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; +import org.rhq.test.JMockTest;
/** * @@ -66,7 +68,7 @@ import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; * @author Lukas Krejci */ @Test -public class ExportingInputStreamTest { +public class ExportingInputStreamTest extends JMockTest {
private static final Log LOG = LogFactory.getLog(ExportingInputStreamTest.class);
@@ -149,7 +151,7 @@ public class ExportingInputStreamTest { }
- public void testCanExport() throws Exception { + public void testSucessfulExport() throws Exception { List<String> list1 = Arrays.asList("a", "b", "c"); List<Integer> list2 = Arrays.asList(1, 2, 3);
@@ -223,6 +225,144 @@ public class ExportingInputStreamTest { } }
+ @Test(expectedExceptions = IOException.class) + public void testExceptionHandling_Exporter_getExportingIterator() throws Exception { + final Exporter<?, ?> failingExporter = context.mock(Exporter.class); + + final Synchronizer<?, ?> syncer = context.mock(Synchronizer.class); + + context.checking(new Expectations() { + { + RuntimeException failure = new RuntimeException("Injected failure"); + + allowing(failingExporter).getExportingIterator(); + will(throwException(failure)); + + allowing(syncer).getRequiredValidators(); + will(returnValue(Collections.emptySet())); + + allowing(syncer).getExporter(); + will(returnValue(failingExporter)); + } + }); + + Set<Synchronizer<?, ?>> syncers = this.<Synchronizer<?, ?>>asSet(syncer); + + InputStream export = new ExportingInputStream(syncers, new HashMap<String, ExporterMessages>(), 1024, false); + + readAll(new InputStreamReader(export, "UTF-8")); + + //this should never be invoked, because reading the input stream should cause the exporter + //to fail... + + fail("Successfully read the export even though one of the exporters threw an exception when asked for the exported entity iterator."); + } + + @Test(expectedExceptions = IOException.class) + public void testExceptionHandling_ExportingIterator_next() throws Exception { + final ExportingIterator<?> iterator = context.mock(ExportingIterator.class); + + final Exporter<?, ?> exporter = context.mock(Exporter.class); + + final Synchronizer<?, ?> syncer = context.mock(Synchronizer.class); + + context.checking(new Expectations() { + { + RuntimeException failure = new RuntimeException("Injected failure"); + + allowing(iterator).hasNext(); + will(returnValue(true)); + + allowing(iterator).next(); + will(onConsecutiveCalls(returnValue("Success"), throwException(failure))); + + allowing(iterator).export(with(any(ExportWriter.class))); + + allowing(iterator).getNotes(); + + allowing(exporter).getExportingIterator(); + will(returnValue(iterator)); + + allowing(exporter).getNotes(); + + allowing(syncer).getRequiredValidators(); + will(returnValue(Collections.emptySet())); + + allowing(syncer).getExporter(); + will(returnValue(exporter)); + } + }); + + Set<Synchronizer<?, ?>> syncers = this.<Synchronizer<?, ?>>asSet(syncer); + + InputStream export = new ExportingInputStream(syncers, new HashMap<String, ExporterMessages>(), 1024, false); + + readAll(new InputStreamReader(export, "UTF-8")); + + //this should never be invoked, because reading the input stream should cause the exporter + //to fail... + + fail("Successfully read the export even though one of the exporters threw an exception when asked for the next exported entity."); + } + + public void testExceptionHandling_ExportingIterator_export() throws Exception { + final ExportingIterator<?> iterator = context.mock(ExportingIterator.class); + final Exporter<?, ?> exporter = context.mock(Exporter.class); + final Synchronizer<?, ?> syncer = context.mock(Synchronizer.class); + + context.checking(new Expectations() { + { + RuntimeException failure = new RuntimeException("Injected failure"); + + allowing(iterator).hasNext(); + will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(false))); + + allowing(iterator).next(); + + allowing(iterator).export(with(any(ExportWriter.class))); + will(onConsecutiveCalls(returnValue(null), throwException(failure))); + + allowing(iterator).getNotes(); + + allowing(exporter).getExportingIterator(); + will(returnValue(iterator)); + + allowing(exporter).getNotes(); + + allowing(syncer).getRequiredValidators(); + will(returnValue(Collections.emptySet())); + + allowing(syncer).getExporter(); + will(returnValue(exporter)); + } + }); + + Set<Synchronizer<?, ?>> syncers = this.<Synchronizer<?, ?>>asSet(syncer); + + InputStream export = new ExportingInputStream(syncers, new HashMap<String, ExporterMessages>(), 1024, false); + + String exportContents = readAll(new InputStreamReader(export, "UTF-8")); + + LOG.warn("Export contents:\n" + exportContents); + + export = new ByteArrayInputStream(exportContents.getBytes("UTF-8")); + + DocumentBuilder bld = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + + Document doc = bld.parse(export); + + Element root = doc.getDocumentElement(); + + NodeList entities = root.getElementsByTagName(ExportingInputStream.ENTITY_EXPORT_ELEMENT); + + assertEquals(entities.getLength(), 2, "Unexpected number of exported elements"); + + //get the entity with the error + Element failedEntity = (Element) entities.item(1); + Node errorMessage = getDirectChildByTagName(failedEntity, ExportingInputStream.ERROR_MESSAGE_ELEMENT); + assertNotNull(errorMessage, "Could not find the error-message element at the entity that failed to export."); + } + private <T> LinkedHashSet<T> asSet(T... ts) { LinkedHashSet<T> ret = new LinkedHashSet<T>(); for (T t : ts) { diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java index 333dd69..a11a42c 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateExporterTest.java @@ -22,7 +22,6 @@ package org.rhq.enterprise.server.sync.test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
-import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; @@ -38,17 +37,15 @@ import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.jmock.Expectations; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
-import org.rhq.core.clientapi.descriptor.plugin.PluginDescriptor; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.MeasurementDefinitionCriteria; -import org.rhq.core.domain.measurement.DataType; -import org.rhq.core.domain.measurement.DisplayType; import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.plugin.Plugin; import org.rhq.core.domain.resource.ResourceCategory; @@ -58,14 +55,11 @@ import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.measurement.MeasurementDefinitionManagerLocal; import org.rhq.enterprise.server.resource.metadata.PluginManagerLocal; -import org.rhq.enterprise.server.resource.metadata.PluginStats; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.MetricTemplateSynchronizer; import org.rhq.enterprise.server.sync.Synchronizer; -import org.rhq.enterprise.server.sync.exporters.Exporter; -import org.rhq.enterprise.server.sync.exporters.MetricTemplateExporter; -import org.rhq.enterprise.server.sync.importers.MetricTemplateImporter; import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; +import org.rhq.test.JMockTest;
/** * @@ -73,142 +67,24 @@ import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; * @author Lukas Krejci */ @Test -public class MetricTemplateExporterTest { +public class MetricTemplateExporterTest extends JMockTest {
private static final Log LOG = LogFactory.getLog(MetricTemplateExporterTest.class);
- private MeasurementDefinitionManagerLocal measurementDefManagerStub = new MeasurementDefinitionManagerLocal() { - - @Override - public void removeMeasurementDefinition(MeasurementDefinition def) { - } - - @Override - public MeasurementDefinition getMeasurementDefinition(Subject subject, int definitionId) { - return null; - } - - @Override - public List<MeasurementDefinition> findMeasurementDefinitionsByResourceType(Subject user, int resourceTypeId, - DataType dataType, DisplayType displayType) { - return null; - } - - @Override - public List<MeasurementDefinition> findMeasurementDefinitionsByIds(Subject subject, - Integer[] measurementDefinitionIds) { - return null; - } - - @Override - public PageList<MeasurementDefinition> findMeasurementDefinitionsByCriteria(Subject subject, - MeasurementDefinitionCriteria criteria) { - List<MeasurementDefinition> ret = new ArrayList<MeasurementDefinition>(); - - ResourceType rt = new ResourceType("fakeType", "fakePlugin", ResourceCategory.PLATFORM, null); - - ret.add(new MeasurementDefinition(rt, "m1")); - ret.add(new MeasurementDefinition(rt, "m2")); - ret.add(new MeasurementDefinition(rt, "m3")); - - return new PageList<MeasurementDefinition>(ret, PageControl.getUnlimitedInstance()); - } - }; - - private PluginManagerLocal pluginManagerStub = new PluginManagerLocal() { - - @Override - public void setPluginEnabledFlag(Subject subject, int pluginId, boolean enabled) throws Exception { - } - - @Override - public boolean registerPluginTypes(Plugin newPlugin, PluginDescriptor pluginDescriptor, boolean newOrUpdated, - boolean forceUpdate) throws Exception { - return false; - } - - @Override - public void registerPlugin(Subject subject, Plugin plugin, PluginDescriptor metadata, File pluginFile, - boolean forceUpdate) throws Exception { - } - - @Override - public void purgePlugins(List<Plugin> plugins) { - } - - @Override - public void markPluginsForPurge(Subject subject, List<Integer> pluginIds) throws Exception { - } - - @Override - public boolean isReadyForPurge(Plugin plugin) { - return false; - } - - @Override - public boolean installPluginJar(Subject subject, Plugin newPlugin, PluginDescriptor pluginDescriptor, - File pluginFile) throws Exception { - return false; - } - - @Override - public List<Plugin> getPluginsByResourceTypeAndCategory(String resourceTypeName, - ResourceCategory resourceCategory) { - return null; - } - - @Override - public List<Plugin> getPlugins() { - return null; - } - - @Override - public List<PluginStats> getPluginStats(List<Integer> pluginIds) { - return null; - } - - @Override - public Plugin getPlugin(String name) { - return null; - } - - @Override - public List<Plugin> getInstalledPlugins() { - Plugin p = new Plugin("fakePlugin", null, "12345"); - p.setVersion("1.0.0.test"); - return Collections.singletonList(p); - } - - @Override - public List<Plugin> getAllPluginsById(List<Integer> pluginIds) { - return null; - } - - @Override - public List<Plugin> findPluginsMarkedForPurge() { - return null; - } - - @Override - public List<Plugin> findAllDeletedPlugins() { - return null; - } - - @Override - public void enablePlugins(Subject subject, List<Integer> pluginIds) throws Exception { - } - - @Override - public void disablePlugins(Subject subject, List<Integer> pluginIds) throws Exception { - } - - @Override - public void deletePlugins(Subject subject, List<Integer> pluginIds) throws Exception { - } - }; - public void testCanExport() throws Exception { - MetricTemplateSynchronizer exporter = new MetricTemplateSynchronizer(measurementDefManagerStub, pluginManagerStub); + final MeasurementDefinitionManagerLocal measurementDefinitionManager = context.mock(MeasurementDefinitionManagerLocal.class); + final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); + context.checking(new Expectations() { + { + allowing(measurementDefinitionManager).findMeasurementDefinitionsByCriteria(with(any(Subject.class)), with(any(MeasurementDefinitionCriteria.class))); + will(returnValue(getFakeMeasurementDefinitions())); + + allowing(pluginManager).getInstalledPlugins(); + will(returnValue(getFakeInstalledPlugins())); + } + }); + + MetricTemplateSynchronizer exporter = new MetricTemplateSynchronizer(measurementDefinitionManager, pluginManager);
Set<Synchronizer<?, ?>> exporters = new HashSet<Synchronizer<?, ?>>(); exporters.add(exporter); @@ -229,17 +105,17 @@ public class MetricTemplateExporterTest { // <entities id="org.rhq.enterprise.server.sync.exporters.MetricTemplatesExporter"> // <entity> // <data> - // <metricTemplate referencedEntityId="0" enabled="false" defaultInterval="0" metricName="m1" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> + // <metricTemplate referencedEntityId="1" enabled="false" defaultInterval="0" metricName="m1" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> // </data> // </entity> // <entity> // <data> - // <metricTemplate referencedEntityId="0" enabled="false" defaultInterval="0" metricName="m2" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> + // <metricTemplate referencedEntityId="2" enabled="false" defaultInterval="0" metricName="m2" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> // </data> // </entity> // <entity> // <data> - // <metricTemplate referencedEntityId="0" enabled="false" defaultInterval="0" metricName="m3" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> + // <metricTemplate referencedEntityId="3" enabled="false" defaultInterval="0" metricName="m3" resourceTypePlugin="fakePlugin" resourceTypeName="fakeType"></metricTemplate> // </data> // </entity> // </entities> @@ -282,9 +158,10 @@ public class MetricTemplateExporterTest {
for(int i = 0; i < metricTemplates.getLength(); ++i) { Element m = (Element) metricTemplates.item(i); - String expectedName = "m" + (i + 1); + String index = Integer.toString(i + 1); + String expectedName = "m" + index;
- assertEquals(m.getAttribute("referencedEntityId"), "0", "Unexpected referencedEntityId value"); + assertEquals(m.getAttribute("referencedEntityId"), index, "Unexpected referencedEntityId value"); assertEquals(m.getAttribute("enabled"), "false", "Unexpected enabled value"); assertEquals(m.getAttribute("defaultInterval"), "0", "Unexpected defaultInterval value"); assertEquals(m.getAttribute("metricName"), expectedName, "Unexpected metricName value"); @@ -329,4 +206,26 @@ public class MetricTemplateExporterTest {
return ret; } + + private static PageList<MeasurementDefinition> getFakeMeasurementDefinitions() { + List<MeasurementDefinition> ret = new ArrayList<MeasurementDefinition>(); + + ResourceType rt = new ResourceType("fakeType", "fakePlugin", ResourceCategory.PLATFORM, null); + + ret.add(new MeasurementDefinition(rt, "m1")); + ret.add(new MeasurementDefinition(rt, "m2")); + ret.add(new MeasurementDefinition(rt, "m3")); + + for(int i = 0; i < ret.size(); ++i) { + ret.get(i).setId(i + 1); + } + + return new PageList<MeasurementDefinition>(ret, PageControl.getUnlimitedInstance()); + } + + private static List<Plugin> getFakeInstalledPlugins() { + Plugin p = new Plugin("fakePlugin", null, "12345"); + p.setVersion("1.0.0.test"); + return Collections.singletonList(p); + } } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java new file mode 100644 index 0000000..78c9d29 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/MetricTemplateImporterTest.java @@ -0,0 +1,118 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.test; + +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertSame; + +import java.util.Collections; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.jmock.Expectations; +import org.testng.annotations.Test; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.resource.ResourceCategory; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.sync.entity.MetricTemplate; +import org.rhq.enterprise.server.measurement.MeasurementScheduleManagerLocal; +import org.rhq.enterprise.server.sync.importers.ExportedEntityMatcher; +import org.rhq.enterprise.server.sync.importers.MetricTemplateImporter; +import org.rhq.test.JMockTest; + +/** + * TODO fix the bug in the importer that doesn't disable the schedules + * + * @author Lukas Krejci + */ +@Test +public class MetricTemplateImporterTest extends JMockTest { + + public void testNonMatchingMeasurementDefinitionsAreIgnored() { + //mocks we are going to need + final EntityManager em = context.mock(EntityManager.class); + final MeasurementScheduleManagerLocal msm = context.mock(MeasurementScheduleManagerLocal.class); + + //some data to supply + final ResourceType rt = new ResourceType("fake", "fake", ResourceCategory.PLATFORM, null); + final MeasurementDefinition def = new MeasurementDefinition(rt, "fake"); + def.setId(1); + def.setDefaultOn(true); + + //setup the expected behavior + context.checking(new Expectations() { + { + Query q = context.mock(Query.class); + + //fake the entity manager returning no results for the first metric template + //we try to import and the def for the second metric template we import + + allowing(em).createNamedQuery(with(MeasurementDefinition.FIND_RAW_OR_PER_MINUTE_BY_NAME_AND_RESOURCE_TYPE_NAME)); + will(returnValue(q)); + + allowing(q).setParameter(with(any(String.class)), with(any(Object.class))); + allowing(q).getResultList(); + will(onConsecutiveCalls(returnValue(Collections.emptyList()), returnValue(Collections.singletonList(def)))); + + //this is what we expect the measurement schedule manager msm to be + //called with with the importer finishes its work. + one(msm).enableMeasurementTemplates(with(any(Subject.class)), with(new int[] { 1 })); + } + }); + + MetricTemplateImporter importer = new MetricTemplateImporter(null, em, msm); + + MetricTemplate nonMatching = new MetricTemplate(); + MetricTemplate matching = new MetricTemplate(def); + + importer.configure(null); + + ExportedEntityMatcher<MeasurementDefinition, MetricTemplate> matcher = importer.getExportedEntityMatcher(); + + assertNull(matcher.findMatch(nonMatching), "The non-matching metric template shouldn't have been matched."); + assertSame(matcher.findMatch(matching), def, "The matching metric template should have found the defined measurement definition"); + + importer.update(null, nonMatching); + importer.update(def, matching); + + //this should invoke the mocked measurement schedule manager and the expectations should check it gets called + //correctly by the importer. + importer.finishImport(); + } + + public void testCanUpdateEnablements() { + + } + + public void testCanUpdateSchedules() { + + } + + public void testGlobalUpdateSchedulesSwitch() { + + } + + public void testPerMetricUpdateScheduleOverrides() { + + } +} diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java index 30ba4ec..b44ed08 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java @@ -38,23 +38,21 @@ import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.jmock.Expectations; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
-import org.rhq.core.db.DatabaseType; import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.common.ProductInfo; -import org.rhq.core.domain.common.ServerDetails; import org.rhq.core.domain.sync.ExporterMessages; import org.rhq.core.domain.sync.entity.SystemSettings; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.Synchronizer; import org.rhq.enterprise.server.sync.SystemSettingsSynchronizer; -import org.rhq.enterprise.server.system.InvalidSystemConfigurationException; import org.rhq.enterprise.server.system.SystemManagerLocal; +import org.rhq.test.JMockTest;
/** * @@ -62,126 +60,32 @@ import org.rhq.enterprise.server.system.SystemManagerLocal; * @author Lukas Krejci */ @Test -public class SystemSettingsExporterTest { +public class SystemSettingsExporterTest extends JMockTest {
private static final Log LOG = LogFactory.getLog(MetricTemplateExporterTest.class);
- private SystemManagerLocal systemManagerStub = new SystemManagerLocal() { - - @Override - public long vacuumAppdef(Subject whoami) { - return 0; - } - - @Override - public long vacuum(Subject whoami, String[] tableNames) { - return 0; - } - - @Override - public long vacuum(Subject whoami) { - return 0; - } - - @Override - public void undeployInstaller() { - } - - @Override - public void setSystemConfiguration(Subject subject, Properties properties, boolean skipValidation) - throws Exception { - } - - @Override - public void scheduleConfigCacheReloader() { - } - - @Override - public long reindex(Subject whoami) { - return 0; - } - - @Override - public void reconfigureSystem(Subject whoami) { - } - - @Override - public void loadSystemConfigurationCacheInNewTx() { - } - - @Override - public void loadSystemConfigurationCache() { - } - - @Override - public boolean isExperimentalFeaturesEnabled() { - return false; - } - - @Override - public boolean isDebugModeEnabled() { - return false; - } - - @Override - public Properties getSystemConfiguration(Subject subject) { - HashMap<String, String> values = new HashMap<String, String>(); - values.put("BaseURL", "herethereandeverywhere"); - SystemSettings settings = new SystemSettings(values); - - return settings.toProperties(); - } - - @Override - public void validateSystemConfiguration(Subject subject, Properties properties) - throws InvalidSystemConfigurationException { - } - - @Override - public ServerDetails getServerDetails(Subject subject) { - return null; - } - - @Override - public ProductInfo getProductInfo(Subject subject) { - return null; - } - - @Override - public DatabaseType getDatabaseType() { - return null; - } - - @Override - public void enableHibernateStatistics() { - } - - @Override - public long analyze(Subject whoami) { - return 0; - } - - @Override - public org.rhq.core.domain.common.composite.SystemSettings getSystemSettings(Subject subject) { - return null; - } + public void testCanExport() throws Exception { + final SystemManagerLocal systemManager = context.mock(SystemManagerLocal.class);
+ context.checking(new Expectations() { + { + allowing(systemManager).getSystemConfiguration(with(any(Subject.class))); + will(returnValue(getFakeSystemConfiguration())); + } + });
- }; - - public void testCanExport() throws Exception { - SystemSettingsSynchronizer exporter = new SystemSettingsSynchronizer(systemManagerStub); + SystemSettingsSynchronizer exporter = new SystemSettingsSynchronizer(systemManager);
Set<Synchronizer<?, ?>> exporters = new HashSet<Synchronizer<?, ?>>(); exporters.add(exporter);
InputStream eis = new ExportingInputStream(exporters, new HashMap<String, ExporterMessages>(), 65536, false);
- String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); - - LOG.warn("Export contents:\n" + exportContents); - - eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8")); + String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); + + LOG.warn("Export contents:\n" + exportContents); + + eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8"));
// <?xml version="1.0" ?> // <configuration-export> @@ -253,15 +157,11 @@ public class SystemSettingsExporterTest { return null; }
- private static List<Node> getDirectChildrenByTagName(Node node, String tagName) { - List<Node> ret = new ArrayList<Node>(); - for (int i = 0; i < node.getChildNodes().getLength(); ++i) { - Node n = node.getChildNodes().item(i); - if (n.getNodeName().equals(tagName)) { - ret.add(n); - } - } + private static Properties getFakeSystemConfiguration() { + HashMap<String, String> values = new HashMap<String, String>(); + values.put("BaseURL", "herethereandeverywhere"); + SystemSettings settings = new SystemSettings(values);
- return ret; + return settings.toProperties(); } } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java new file mode 100644 index 0000000..a69e0c6 --- /dev/null +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsValidatorTest.java @@ -0,0 +1,29 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2011 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.enterprise.server.sync.test; + +/** + * + * + * @author Lukas Krejci + */ +public class SystemSettingsValidatorTest { + +}
commit 74dfa4b00d924d8b842240cb98233f0d31469de6 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 10 08:43:30 2011 +0200
Fixed the configuration export file XSD and the code that generates the export xml to correspond to each other.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java index 53e391c..ae76e24 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/ExportingInputStream.java @@ -262,7 +262,7 @@ public class ExportingInputStream extends InputStream { private void exportEpilogue(XMLStreamWriter wrt) throws XMLStreamException { wrt.writeEndDocument(); } - + /** * @param wrt * @param syn @@ -273,10 +273,10 @@ public class ExportingInputStream extends InputStream { ExporterMessages messages = new ExporterMessages();
messagesPerExporter.put(syn.getClass().getName(), messages); - + wrt.writeStartElement(ENTITIES_EXPORT_ELEMENT); wrt.writeAttribute(ID_ATTRIBUTE, syn.getClass().getName()); - + Exporter<?, ?> exp = syn.getExporter(); ExportingIterator<?> it = exp.getExportingIterator();
@@ -287,25 +287,32 @@ public class ExportingInputStream extends InputStream { it.next();
wrt.writeStartElement(ENTITY_EXPORT_ELEMENT); - + + wrt.writeStartElement(DATA_ELEMENT); + + Exception exportError = null; try { - wrt.writeStartElement(DATA_ELEMENT); it.export(new ExportWriter(wrt)); - wrt.writeEndElement(); - + } catch (XMLStreamException e) { + //there's not much we can do about these but to give up. + throw e; + } catch (Exception e) { + exportError = e; + } + + wrt.writeEndElement(); //data + + if (exportError == null) { String notes = it.getNotes(); - + if (notes != null) { messages.getPerEntityNotes().add(notes); wrt.writeStartElement(NOTES_ELEMENT); wrt.writeCharacters(notes); wrt.writeEndElement(); } - } catch (XMLStreamException e) { - //there's not much we can do about these but to give up. - throw e; - } catch (Exception e) { - String message = ThrowableUtil.getStackAsString(e); + } else { + String message = ThrowableUtil.getStackAsString(exportError); messages.getPerEntityErrorMessages().add(message); wrt.writeStartElement(ERROR_MESSAGE_ELEMENT); wrt.writeCharacters(message); @@ -314,17 +321,17 @@ public class ExportingInputStream extends InputStream {
wrt.writeEndElement(); //entity } - + String notes = exp.getNotes(); - + messages.setExporterNotes(notes); - + if (notes != null) { wrt.writeStartElement(NOTES_ELEMENT); wrt.writeCharacters(notes); wrt.writeEndElement(); } - + wrt.writeEndElement(); //entities }
diff --git a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd index cfc8d6b..a4c6d0d 100644 --- a/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd +++ b/modules/enterprise/server/xml-schemas/src/main/resources/rhq-configuration-export.xsd @@ -44,12 +44,10 @@ </xs:complexType>
<xs:complexType name="EntityExport"> - xs:choice - xs:sequence - <xs:element name="data" /> - <xs:element type="xs:string" name="notes"/> - </xs:sequence> - <xs:element type="xs:string" name="error-message" /> - </xs:choice> + xs:sequence + <xs:element name="data" /> + <xs:element type="xs:string" name="notes" minOccurs="0" maxOccurs="1"/> + <xs:element type="xs:string" name="error-message" minOccurs="0" maxOccurs="1"/> + </xs:sequence> </xs:complexType> </xs:schema> \ No newline at end of file
commit 09fa4f5d7780585302f740e7acd15029ff539da2 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 10 08:39:36 2011 +0200
Fixing NPE during import with default configuration.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java index 2bd48b3..d49df01 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java @@ -81,6 +81,9 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe @Override public void configure(Configuration importConfiguration) { this.importConfiguration = importConfiguration; + if (importConfiguration == null) { + this.importConfiguration = getImportConfigurationDefinition().getDefaultTemplate().getConfiguration(); + } }
@Override
commit 31b652eac862de655dc5a092aad0936c2e46206a Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 9 18:00:30 2011 -0400
Make the drift detection rate configurable
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainerConfiguration.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainerConfiguration.java index 6750a3a..1e7ba50 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainerConfiguration.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainerConfiguration.java @@ -86,6 +86,13 @@ public class PluginContainerConfiguration { + "measurement-collection-threadpoolsize"; public static final int MEASUREMENT_COLLECTION_THREADCOUNT_DEFAULT = 5;
+ // Drift ---------- + + private static final String DRIFT_DETECTION_INITIAL_DELAY_PROP = PROP_PREFIX + "drift-detection-initial-delay"; + public static final long DRIFT_DETECTION_INITIAL_DELAY_DEFAULT = 30L; // in seconds + private static final String DRIFT_DETECTION_PERIOD_PROP = PROP_PREFIX + "drift-detection-period"; + public static final long DRIFT_DETECTION_PERIOD_DEFAULT = 60L; // in seconds + // Content ----------
private static final String CONTENT_DISCOVERY_INITIAL_DELAY_PROP = PROP_PREFIX + "content-discovery-initial-delay"; @@ -467,6 +474,47 @@ public class PluginContainerConfiguration { }
/** + * Returns the length of time, in seconds, before drift detection first begins. + * + * @return initial delay in seconds + */ + public long getDriftDetectionInitialDelay() { + Long delay = (Long) configuration.get(DRIFT_DETECTION_INITIAL_DELAY_PROP); + return (delay == null) ? DRIFT_DETECTION_INITIAL_DELAY_DEFAULT : delay.longValue(); + } + + /** + * Sets the length of time, in seconds, before drift detection first begins. + * + * @param delay time in seconds before first drift detection + */ + public void setDriftDetectionInitialDelay(long delay) { + configuration.put(DRIFT_DETECTION_INITIAL_DELAY_PROP, delay); + } + + /** + * Returns the length of time, in seconds, between each drift detection scan. In other words, a drift detection scan + * will run every X seconds, where X is this method's return value. If this value was never set via + * {@link #setDriftDetectionPeriod}, the default will be {@link #DRIFT_DETECTION_PERIOD_DEFAULT}. + * + * @return time in seconds between drift detection scans + */ + public long getDriftDetectionPeriod() { + Long period = (Long) configuration.get(DRIFT_DETECTION_PERIOD_PROP); + return (period == null) ? DRIFT_DETECTION_PERIOD_DEFAULT : period.longValue(); + } + + /** + * Sets the length of time, in seconds, between each drift detection scan. In other words, a drift detection + * scan should be run every <code>period</code> seconds. + * + * @param period time in seconds between drift detection scans + */ + public void setDriftDetectionPeriod(long period) { + configuration.put(DRIFT_DETECTION_PERIOD_PROP, period); + } + + /** * Returns the length of time, in seconds, before auto-discovery of content first begins. * * @return initial delay in seconds @@ -790,7 +838,6 @@ public class PluginContainerConfiguration { return configuration.toString(); }
- /** * Returns the default filter for class loading that is used to prevent leaking * of agent / PC classes to plugins. 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 7c8b389..62e1e39 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,6 +19,8 @@
package org.rhq.core.pc.drift;
+import static org.rhq.core.util.ZipUtil.zipFileOrDirectory; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -51,8 +53,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.core.util.ZipUtil.zipFileOrDirectory; - public class DriftManager extends AgentService implements DriftAgentService, DriftClient, ContainerService {
private final Log log = LogFactory.getLog(DriftManager.class); @@ -91,8 +91,15 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri initSchedules(inventoryMgr.getPlatform(), inventoryMgr);
driftThreadPool = new ScheduledThreadPoolExecutor(5); - // TODO Make the drift detection rate configurable - driftThreadPool.scheduleAtFixedRate(driftDetector, 30, 60, TimeUnit.SECONDS); + + long initialDelay = pluginContainerConfiguration.getDriftDetectionInitialDelay(); + long period = pluginContainerConfiguration.getDriftDetectionPeriod(); + if (period > 0) { + // note that drift detection is globally disabled if the detection period is 0 or less + driftThreadPool.scheduleAtFixedRate(driftDetector, initialDelay, period, TimeUnit.SECONDS); + } else { + log.info("Drift detection has been globally disabled as per plugin container configuration"); + } }
private void initSchedules(Resource r, InventoryManager inventoryMgr) { @@ -109,7 +116,7 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri
log.debug("Rescheduling drift detection schedules for " + r); Set<DriftDetectionSchedule> driftSchedules = container.getDriftSchedules(); - if (driftSchedules!=null) + if (driftSchedules != null) for (DriftDetectionSchedule schedule : driftSchedules) { schedulesQueue.addSchedule(schedule); } @@ -184,16 +191,16 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri @Override public void detectDrift(int resourceId, DriftConfiguration driftConfiguration) { if (log.isDebugEnabled()) { - log.debug("Received request to schedule drift detection immediately for [resourceId: " + resourceId + - ", driftConfigurationId: " + driftConfiguration.getId() + ", driftConfigurationName: " + - driftConfiguration.getName() + "]"); + log.debug("Received request to schedule drift detection immediately for [resourceId: " + resourceId + + ", driftConfigurationId: " + driftConfiguration.getId() + ", driftConfigurationName: " + + driftConfiguration.getName() + "]"); }
DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId, driftConfiguration); 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 + ", driftConfigurationId:" + + driftConfiguration.getId() + ", driftConfigurationName: " + driftConfiguration.getName() + "]. No " + + " work will be scheduled."); return; } log.debug("Resetting " + schedule + " for immediate detection."); diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfiguration.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfiguration.java index 3f07f8b..1a4f20e 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfiguration.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfiguration.java @@ -1139,6 +1139,13 @@ public class AgentConfiguration { AgentConfigurationConstants.PLUGINS_MEASUREMENT_COLL_THREADPOOL_SIZE, AgentConfigurationConstants.DEFAULT_PLUGINS_MEASUREMENT_COLL_THREADPOOL_SIZE);
+ // get the drift settings + long drift_period = m_preferences.getLong(AgentConfigurationConstants.PLUGINS_DRIFT_DETECTION_PERIOD, + AgentConfigurationConstants.DEFAULT_PLUGINS_DRIFT_DETECTION_PERIOD); + long drift_initial_delay = m_preferences.getLong( + AgentConfigurationConstants.PLUGINS_DRIFT_DETECTION_INITIAL_DELAY, + AgentConfigurationConstants.DEFAULT_PLUGINS_DRIFT_DETECTION_INITIAL_DELAY); + // determine how many operation invoker threads should be in the threadpool that is used to execute operations int op_threadpool_size = m_preferences.getInt( AgentConfigurationConstants.PLUGINS_OPERATION_INVOKER_THREADPOOL_SIZE, @@ -1217,6 +1224,8 @@ public class AgentConfiguration { config.setAvailabilityScanPeriod(avail_scan_period); config.setMeasurementCollectionThreadPoolSize(meas_threadpool_size); config.setMeasurementCollectionInitialDelay(meas_scan_initial_delay); + config.setDriftDetectionInitialDelay(drift_initial_delay); + config.setDriftDetectionPeriod(drift_period); config.setOperationInvokerThreadPoolSize(op_threadpool_size); config.setOperationInvocationTimeout(op_timeout); config.setContentDiscoveryThreadPoolSize(con_threadpool_size); diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfigurationConstants.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfigurationConstants.java index 6f21139..19d3a03 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfigurationConstants.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentConfigurationConstants.java @@ -625,6 +625,26 @@ public interface AgentConfigurationConstants { long DEFAULT_PLUGINS_MEASUREMENT_COLLECTION_INITIAL_DELAY = PluginContainerConfiguration.MEASUREMENT_COLLECTION_INITIAL_DELAY_DEFAULT;
/** + * Defines, in seconds, the initial delay before the first drift detection scan is run. + */ + String PLUGINS_DRIFT_DETECTION_INITIAL_DELAY = PROPERTY_NAME_PREFIX + "plugins.drift-detection.initial-delay-secs"; + + /** + * The default initial delay of the first drift detection scan, in seconds. + */ + long DEFAULT_PLUGINS_DRIFT_DETECTION_INITIAL_DELAY = PluginContainerConfiguration.DRIFT_DETECTION_INITIAL_DELAY_DEFAULT; + + /** + * Defines, in seconds, how often a drift detection scan is run. + */ + String PLUGINS_DRIFT_DETECTION_PERIOD = PROPERTY_NAME_PREFIX + "plugins.drift-detection.period-secs"; + + /** + * The default time period between each drift detection scan, in seconds. + */ + long DEFAULT_PLUGINS_DRIFT_DETECTION_PERIOD = PluginContainerConfiguration.DRIFT_DETECTION_PERIOD_DEFAULT; + + /** * If defined, this is to be the size of the content discovery thread pool. If not defined, the plugin container * should default to something it considers appropriate. */ diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentSetupInstructions.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentSetupInstructions.java index faf3692..8d27c2a 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentSetupInstructions.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentSetupInstructions.java @@ -865,6 +865,25 @@ public interface AgentSetupInstructions { + "by defining its own timeouts within its plugin descriptor.") }) String SETUP_INSTRUCTION_PCOPINVOCATIONTIMEOUT_HELP = "PromptCommand.setup.instruction.opinvocationtimeout.help";
+ // PLUGINS DRIFT DETECTION PERIOD + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_PREF = AgentConfigurationConstants.PLUGINS_DRIFT_DETECTION_PERIOD; + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_DEFAULT = Long + .toString(AgentConfigurationConstants.DEFAULT_PLUGINS_DRIFT_DETECTION_PERIOD); + @I18NMessages( { @I18NMessage("Drift Detection Period") }) + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_PROMPT = "PromptCommand.setup.instruction.plugins.driftdetection-period.prompt"; + @I18NMessages( { @I18NMessage("The time in seconds that defines how often drift detection scans are run.\n\\n" + + "If 0 or less, drift discovery scans are disabled.") }) + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_HELP = "PromptCommand.setup.instruction.plugins.driftdiscovery-period.help"; + + // PLUGINS DRIFT DETECTION INITIAL DELAY + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_PREF = AgentConfigurationConstants.PLUGINS_DRIFT_DETECTION_INITIAL_DELAY; + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_DEFAULT = Long + .toString(AgentConfigurationConstants.DEFAULT_PLUGINS_DRIFT_DETECTION_INITIAL_DELAY); + @I18NMessages( { @I18NMessage("Drift Detection Initial Delay") }) + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_PROMPT = "PromptCommand.setup.instruction.plugins.driftdetection-initialdelay.prompt"; + @I18NMessages( { @I18NMessage("The time in seconds before the initial drift detection scan is performed.") }) + String SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_HELP = "PromptCommand.setup.instruction.plugins.driftdetection-initialdelay.help"; + // PLUGINS CONTENT DISCOVERY THREADPOOL SIZE String SETUP_INSTRUCTION_PLUGINSCONTENTDISCOVERYTHREADCOUNT_PREF = AgentConfigurationConstants.PLUGINS_CONTENT_DISCOVERY_THREADPOOL_SIZE; String SETUP_INSTRUCTION_PLUGINSCONTENTDISCOVERYTHREADCOUNT_DEFAULT = Integer diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/SetupPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/SetupPromptCommand.java index 7c8152a..5902710 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/SetupPromptCommand.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/SetupPromptCommand.java @@ -593,6 +593,20 @@ public class SetupPromptCommand implements AgentPromptCommand { .getMsg(AgentSetupInstructions.SETUP_INSTRUCTION_PCOPINVOCATIONTIMEOUT_HELP)));
instr.add(new DefaultSetupInstruction( + AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_PREF, + AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_DEFAULT, new LongSetupValidityChecker( + 0L, null), + SETUPMSG.getMsg(AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_PROMPT), SETUPMSG + .getMsg(AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONPERIOD_HELP))); + + instr.add(new DefaultSetupInstruction( + AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_PREF, + AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_DEFAULT, + new LongSetupValidityChecker(1L, null), SETUPMSG + .getMsg(AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_PROMPT), SETUPMSG + .getMsg(AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSDRIFTDETECTIONINITIALDELAY_HELP))); + + instr.add(new DefaultSetupInstruction( AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSCONTENTDISCOVERYPERIOD_PREF, AgentSetupInstructions.SETUP_INSTRUCTION_PLUGINSCONTENTDISCOVERYPERIOD_DEFAULT, new LongSetupValidityChecker(0L, null), SETUPMSG diff --git a/modules/enterprise/agent/src/main/resources/agent-configuration.xml b/modules/enterprise/agent/src/main/resources/agent-configuration.xml index 66e1d59..a4cfa58 100644 --- a/modules/enterprise/agent/src/main/resources/agent-configuration.xml +++ b/modules/enterprise/agent/src/main/resources/agent-configuration.xml @@ -645,6 +645,31 @@ commands named "config", "setconfig" and "setup" and the command line options
<!-- _______________________________________________________________ + rhq.agent.plugins.drift-detection.initial-delay-secs + + Defines the delay before the first drift detection scan is + run. The value is specified in seconds. + --> + <!-- + <entry key="rhq.agent.plugins.drift-detection.initial-delay-secs" value="30"/> + --> + + <!-- + _______________________________________________________________ + rhq.agent.plugins.drift-detection.period-secs + + Defines how often a drift detection scan is run. This type + of scan is used to determine what, if any, file changes (such + as additions, deletions, modifications) occurred within + specific file system locations that are being monitored. + If this value is 0 or less, drift detection will be disabled. + --> + <!-- + <entry key="rhq.agent.plugins.drift-detection.period-secs" value="60"/> + --> + + <!-- + _______________________________________________________________ rhq.agent.plugins.content-discovery.threadpool-size
When plugins are scheduled to discover content, the discovery diff --git a/modules/enterprise/server/sars/agent-sar/src/main/resources/META-INF/embedded-agent-configuration.xml b/modules/enterprise/server/sars/agent-sar/src/main/resources/META-INF/embedded-agent-configuration.xml index 68e8719..52c2c6a 100644 --- a/modules/enterprise/server/sars/agent-sar/src/main/resources/META-INF/embedded-agent-configuration.xml +++ b/modules/enterprise/server/sars/agent-sar/src/main/resources/META-INF/embedded-agent-configuration.xml @@ -637,6 +637,30 @@ Embedded RHQ Agent Configuration
<!-- _______________________________________________________________ + rhq.agent.plugins.drift-detection.initial-delay-secs + + Defines the delay before the first drift detection scan is + run. The value is specified in seconds. + --> + <!-- + <entry key="rhq.agent.plugins.drift-detection.initial-delay-secs" value="30"/> + --> + + <!-- + _______________________________________________________________ + rhq.agent.plugins.drift-detection.period-secs + + Defines how often a drift detection scan is run. This type + of scan is used to determine what, if any, file changes (such + as additions, deletions, modifications) occurred within + specific file system locations that are being monitored. + --> + <!-- + <entry key="rhq.agent.plugins.drift-detection.period-secs" value="60"/> + --> + + <!-- + _______________________________________________________________ rhq.agent.plugins.content-discovery.threadpool-size
When plugins are scheduled to discover content, the discovery diff --git a/modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml index 7d59954..3517bf6 100644 --- a/modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml @@ -357,6 +357,8 @@ <c:simple-property name="rhq.agent.plugins.availability-scan.period-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="300" displayName="Availability Scan Period" description="Time between availability scans (in seconds)" /> <c:simple-property name="rhq.agent.plugins.measurement-collection.initial-delay-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="30" displayName="Measurement Collection Initial Delay" description="Startup delay before the first measurement collection is run (in seconds)" /> <c:simple-property name="rhq.agent.plugins.measurement-collection.threadpool-size" type="integer" activationPolicy="restart" required="false" default="5" displayName="Measurement Collection Threadpool Size" description="Number of concurrent measurement collections that can be run" /> + <c:simple-property name="rhq.agent.plugins.drift-detection.initial-delay-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="30" displayName="Drift Detection Initial Delay" description="Startup delay before the first drift detection scan is run (in seconds)" /> + <c:simple-property name="rhq.agent.plugins.drift-detection.period-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="60" displayName="Drift Detection Period" description="Time between drift detection scans (in seconds)" /> <c:simple-property name="rhq.agent.plugins.operation-invocation-timeout-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="600" displayName="Operation Invocation Timeout" description="Time before an operation invocation is aborted (in seconds)" /> <c:simple-property name="rhq.agent.plugins.operation-invoker.threadpool-size" type="integer" activationPolicy="restart" required="false" default="5" displayName="Operation Invoker Threadpool Size" description="Number of concurrent operation invocations that can be run" /> <c:simple-property name="rhq.agent.plugins.content-discovery.initial-delay-secs" type="integer" units="seconds" activationPolicy="restart" required="false" default="30" displayName="Content Discovery Initial Delay" description="Startup delay before the first content discovery is run (in seconds)" />
commit 48dc8c139982f9d66522c266d993aa11353cc6c1 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 16:57:26 2011 -0400
Add more user filtering capability to the drift histiry views
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 9b1608f..463d222 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 @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.client.drift; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; +import java.util.Iterator; import java.util.Map; import java.util.Set;
@@ -75,6 +76,9 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC public static final String ATTR_PATH = "path";
public static final String FILTER_CATEGORIES = "categories"; + public static final String FILTER_CONFIGURATION = "configuration"; + public static final String FILTER_CHANGE_SET = "changeSet"; + public static final String FILTER_PATH = "path";
private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService();
@@ -191,6 +195,20 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC }
public void onSuccess(PageList<DriftComposite> result) { + // only get the desired config 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_CONFIGURATION, String.class); + if (null != configFilter && !configFilter.isEmpty()) { + configFilter = configFilter.toLowerCase(); + for (Iterator<DriftComposite> i = result.getValues().iterator(); i.hasNext();) { + DriftComposite composite = i.next(); + if (!composite.getDriftConfigName().toLowerCase().contains(configFilter)) { + i.remove(); + } + } + } + dataRetrieved(result, response, request); } }); @@ -269,13 +287,36 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC return null; // user didn't select any priorities - return null to indicate no data should be displayed }
+ String changeSetFilter = getFilter(request, FILTER_CHANGE_SET, 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 + // to the query results. + GenericDriftCriteria criteria = new GenericDriftCriteria(); // grab the change set for the drift criteria.fetchChangeSet(true); // only get the desired drift categories criteria.addFilterCategories(categoriesFilter); - // do not fetch tracking entries from the coverage changeset - criteria.addFilterChangeSetStartVersion(1); + // only get the desired changeset version (substring match) + if (null != changeSetFilter && !changeSetFilter.isEmpty()) { + try { + Integer version = Integer.valueOf(changeSetFilter); + criteria.addFilterChangeSetStartVersion(version); + criteria.addFilterChangeSetEndVersion(version); + } catch (Exception e) { + // ignore the specified filter, it's an invalid integer + // do not fetch tracking entries from the coverage changeset + criteria.addFilterChangeSetStartVersion(1); + } + } else { + // do not fetch tracking entries from the coverage changeset + criteria.addFilterChangeSetStartVersion(1); + } + + // only get the desired paths (substring match) + if (null != pathFilter && !pathFilter.isEmpty()) { + criteria.addFilterPath(pathFilter); + }
switch (entityContext.getType()) { case Resource: 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 01bb14a..998c142 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 @@ -30,6 +30,7 @@ import com.smartgwt.client.data.SortSpecifier; import com.smartgwt.client.types.SortDirection; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; @@ -56,7 +57,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * A view that displays a paginated table of {@link org.rhq.core.domain.drift.JPADrift}s, along with the * ability to filter those drifts, sort those drifts, double-click a row to view full details a drift, and perform * various actions on the the drifts: delete selected, delete all from source, etc. - * This view full respects the user's authorization, and will not allow acttions on the drifts unless the user is + * This view fully 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 drifts being * operated on. * @@ -131,8 +132,13 @@ 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_CONFIGURATION, MSG + .common_title_configuration()); + TextItem changeSetFilter = new TextItem(DriftDataSource.FILTER_CHANGE_SET, MSG.view_drift_table_changeSet()); + TextItem pathFilter = new TextItem(DriftDataSource.FILTER_PATH, MSG.common_title_path()); + if (isShowFilterForm()) { - setFilterFormItems(categoryFilter); + setFilterFormItems(configurationFilter, changeSetFilter, categoryFilter, pathFilter); } }
commit 1638faee4664ce327f9232d4a7ed916ab58f59ca Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 16:56:41 2011 -0400
- Set the built in filter form to 4 columns to make better use of real estate when there are several filters. - removed some compiler warnings
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 b1d0bb1..6e8bbcc 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 @@ -100,7 +100,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Greg Hinkle * @author Ian Springer */ -public class Table<DS extends RPCDataSource> extends LocatableHLayout implements RefreshableView { +public class Table<DS extends RPCDataSource<?, ?>> extends LocatableHLayout implements RefreshableView {
protected static final String FIELD_ID = "id"; protected static final String FIELD_NAME = "name"; @@ -538,6 +538,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements public void setFilterFormItems(FormItem... formItems) { setShowHeader(false); this.filterForm.setItems(formItems); + this.filterForm.setNumCols(4); }
/** @@ -869,7 +870,7 @@ public class Table<DS extends RPCDataSource> extends LocatableHLayout implements this.listGrid.setSelectionType(getDefaultSelectionStyle()); }
- int selectionCount = this.listGrid.getSelection().length; + //int selectionCount = this.listGrid.getSelection().length; for (TableActionInfo tableAction : tableActions) { if (tableAction.actionCanvas != null) { // if null, we haven't initialized our buttons yet, so skip this boolean enabled = (!this.tableActionDisableOverride && tableAction.action.isEnabled(this.listGrid
commit f574b3439995c0398a2e118ca564584d799f2480 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 16:55:24 2011 -0400
Drift - Fix issue returning config name in drift composites
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 a792715..35c3115 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 @@ -50,7 +50,6 @@ import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.clientapi.agent.drift.DriftAgentService; import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; import org.rhq.core.domain.criteria.DriftCriteria; import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; @@ -129,15 +128,19 @@ public class JPADriftServerBean implements JPADriftServerLocal { @Override public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) {
- PageList<JPADrift> drifts = findDriftsByCriteria(subject, criteria); - PageList<DriftComposite> composites = new PageList<DriftComposite>(); + JPADriftCriteria jpaCriteria = (criteria instanceof JPADriftCriteria) ? (JPADriftCriteria) criteria + : new JPADriftCriteria(criteria); + + jpaCriteria.fetchChangeSet(true); + PageList<JPADrift> drifts = findDriftsByCriteria(subject, jpaCriteria); + PageList<DriftComposite> result = new PageList<DriftComposite>(); for (JPADrift drift : drifts) { JPADriftChangeSet changeSet = drift.getChangeSet(); - DriftConfiguration driftConfig = new DriftConfiguration(entityManager.find(Configuration.class, changeSet - .getDriftConfigurationId())); - composites.add(new DriftComposite(drift, changeSet.getResource(), driftConfig.getName())); + DriftConfiguration driftConfig = changeSet.getDriftConfiguration(); + result.add(new DriftComposite(drift, changeSet.getResource(), driftConfig.getName())); } - return composites; + + return result; }
@Override
commit aa638506500a57a845e7033f736da23c61865c2a Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 14:24:30 2011 -0400
Fix drift upgrade script mistake
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index 0b32f50..8dcc549 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3525,7 +3525,7 @@ ALTER TABLE RHQ_DRIFT_CHANGE_SET ADD CONSTRAINT RHQ_DCS_DRIFT_CONFIG_ID_FK FOREIGN KEY (DRIFT_CONFIG_ID) - REFERENCES RHQ_CONFIG (ID) + REFERENCES RHQ_DRIFT_CONFIG (ID) </statement> </schema-directSQL>
commit 0d69b5b012433abdfeb4dbf878e06c85adbbe9dd Merge: 673a387 5fa5b71 Author: John Sanda jsanda@redhat.com Date: Tue Aug 9 12:22:48 2011 -0400
Merge branch 'master' into drift
commit 673a387205ab1af8aaf9caf586936f4c8fa2db0e Author: John Sanda jsanda@redhat.com Date: Tue Aug 9 12:20:34 2011 -0400
Disable test by default until it can be supported on jenkins
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 e2afccf..93fde79 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 @@ -175,7 +175,7 @@ public class ChangeSetDAOTest { expected, actual, ignore); }
- @Test + @Test(enabled = ENABLED) public void findByDriftCriteriaWithCategoryFilter() throws Exception { MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1).add(new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED)); dao.save(c1);
commit 956a4fbd6ee6ded1d967c6ee7803401a67d3e22a Author: John Sanda jsanda@redhat.com Date: Tue Aug 9 11:40:07 2011 -0400
Fixing unit tests
DriftManagerBeanTest started failing as a result of the changes in the change set file format and change set parser.
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 436ac1e..4c84169 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 @@ -19,6 +19,7 @@ package org.rhq.enterprise.server.drift;
import java.io.File; +import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import java.util.Random; @@ -32,6 +33,10 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
+import org.rhq.common.drift.ChangeSetWriter; +import org.rhq.common.drift.ChangeSetWriterImpl; +import org.rhq.common.drift.DirectoryEntry; +import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.clientapi.agent.drift.DriftAgentService; import org.rhq.core.clientapi.server.drift.DriftServerService; @@ -44,21 +49,31 @@ 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.DriftFile; -import org.rhq.core.domain.drift.DriftFileStatus; 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.resource.Agent; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.util.PageOrdering; +import org.rhq.core.util.MessageDigestGenerator; +import org.rhq.core.util.ZipUtil; import org.rhq.enterprise.server.resource.ResourceManagerLocal; 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.apache.commons.io.IOUtils.write; +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. * @@ -78,11 +93,14 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { @SuppressWarnings("unused") private DriftServerService driftServerService;
+ MessageDigestGenerator digestGenerator; + /** * Prepares things for the entire test class. */ @BeforeClass - public void beforeClass() { + public void beforeClass() throws Exception { + digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); jpaDriftServer = LookupUtil.getJPADriftServer(); driftManager = LookupUtil.getDriftManager(); overlord = LookupUtil.getSubjectManager().getOverlord(); @@ -119,9 +137,32 @@ public class DriftManagerBeanTest extends AbstractEJB3Test {
@Test(enabled = ENABLE_TESTS) public void testStoreChangeSet() throws Exception { - File changeset1 = new File("./src/test/resources/org/rhq/enterprise/server/drift/changeset-1.zip"); - assertTrue(changeset1.exists()); - jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeset1); + File rootDir = toFile(getClass().getResource(".")); + deleteDirectory(rootDir); + + File changeSetsDir = new File(rootDir, "changesets"); + changeSetsDir.mkdirs(); + + Headers headers = new Headers(); + headers.setResourceId(newResource.getId()); + headers.setDriftCofigurationId(1); + headers.setDriftConfigurationName("test-1"); + headers.setBasedir(rootDir.getAbsolutePath()); + headers.setType(COVERAGE); + + String file1Hash = sha256("test-1-file-1"); + + File changeSet1 = new File(changeSetsDir, "changeset-1.txt"); + ChangeSetWriter writer = new ChangeSetWriterImpl(changeSet1, headers); + writer.writeDirectoryEntry(new DirectoryEntry("test").add(addedFileEntry("file-1", file1Hash))); + writer.close(); + + File changeSet1Zip = new File(changeSetsDir, "changeset-1.zip"); + ZipUtil.zipFileOrDirectory(changeSet1, changeSet1Zip); + + assertTrue("Expected to find change set zip file: " + changeSet1Zip.getPath(), changeSet1Zip.exists()); + + jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeSet1Zip);
JPADriftChangeSetCriteria c = new JPADriftChangeSetCriteria(); c.addFilterResourceId(newResource.getId()); @@ -132,30 +173,42 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size());
- DriftFile driftFile = jpaDriftServer.getDriftFile(overlord, "aaaaa"); + DriftFile driftFile = jpaDriftServer.getDriftFile(overlord, file1Hash); assertNotNull(driftFile); assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus());
// the second change set should report drift - File changeset2 = new File("./src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip"); - assertTrue(changeset2.exists()); - jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeset2); + String modifiedFile1Hash = sha256("test-2-file-1-modified"); + headers.setType(DRIFT); + File changeSet2 = new File(changeSetsDir, "changeset-2.txt"); + + writer = new ChangeSetWriterImpl(changeSet2, headers); + writer.writeDirectoryEntry(new DirectoryEntry("test").add(changedFileEntry("file-1", file1Hash, modifiedFile1Hash))); + writer.close(); + + File changeSet2Zip = new File(changeSetsDir, "changeset-2.zip"); + ZipUtil.zipFileOrDirectory(changeSet2, changeSet2Zip); + + assertTrue("Expected to find change set file: " + changeSet2Zip.getPath(), changeSet2Zip.exists()); + + jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeSet2Zip); c.addSortVersion(PageOrdering.ASC); + c.addFilterCategory(DRIFT); changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(overlord, c); - assertEquals(2, changeSets.size()); + assertEquals(1, changeSets.size()); changeSet = changeSets.get(0); - assertEquals("The change set version is wrong", 0, changeSet.getVersion()); + assertEquals("The change set version is wrong", 1, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size()); - changeSet = changeSets.get(1); + changeSet = changeSets.get(0); assertEquals(1, changeSet.getVersion()); assertEquals(1, changeSet.getDrifts().size()); Drift<?, ?> drift = changeSet.getDrifts().iterator().next(); - assertEquals("dir/filename.ext", drift.getPath()); - assertEquals("aaaaa", drift.getOldDriftFile().getHashId()); - assertEquals("bbbbb", drift.getNewDriftFile().getHashId()); + assertEquals("test/file-1", drift.getPath()); + assertEquals(file1Hash, drift.getOldDriftFile().getHashId()); + assertEquals(modifiedFile1Hash, drift.getNewDriftFile().getHashId()); assertEquals(DriftCategory.FILE_CHANGED, drift.getCategory());
- driftFile = jpaDriftServer.getDriftFile(overlord, "bbbbb"); + driftFile = jpaDriftServer.getDriftFile(overlord, modifiedFile1Hash); assertNotNull(driftFile); assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus()); } @@ -369,6 +422,10 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { } }
+ String sha256(String s) throws Exception { + return digestGenerator.calcDigestString(s); + } + private class TestConfigService implements DriftAgentService {
@Override diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml index d5d1b61..257bb72 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml @@ -116,6 +116,5 @@ <rhq_bundle/> <rhq_drift_template_map/> <rhq_drift_change_set/> - <rhq_drift_config_map/> <rhq_plugin/> </dataset> 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 e7dd05d..e2afccf 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 @@ -49,7 +49,9 @@ import static org.testng.AssertJUnit.assertEquals;
public class ChangeSetDAOTest {
- static final boolean ENABLED = true; + // Tests need to be disabled when committed/pushed to the remote repo until we get + // mongodb installed on the hudson slave + static final boolean ENABLED = false;
Mongo connection;
@@ -240,6 +242,16 @@ public class ChangeSetDAOTest { assertChangeSetMatches("Failed to find change set by drift criteria with id filter.", c1, actual.get(0)); }
+// @Test +// public void testSlice() throws Exception { +// MongoDBChangeSet c1 = createChangeSet(DRIFT, 2, 1, 1) +// .add(new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED)) +// .add(new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED)); +// dao.save(c1); +// +// dao.createQuery().filter("files $slice", new Integer(1)); +// } + /** * This method first checks that the actual change set is not null. It then performs a * property-wise comparison against the expected change set using
commit 31ba317938dfc30c938872d274b990942c2b21a6 Author: John Mazzitelli mazz@redhat.com Date: Tue Aug 9 11:34:27 2011 -0400
fix the tree IDs so they do not conflict
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 1c09ee9..2cccb4b 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 @@ -324,7 +324,8 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid }
public String getChangeSetId() { - return getAttribute("id"); + String idAttrib = getAttribute("id"); + return idAttrib.substring(idAttrib.indexOf('_') + 1); }
private String buildNodeName(DriftChangeSet<?> changeset) { @@ -346,10 +347,15 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid setIcon(ImageManager.getDriftCategoryIcon(drift.getCategory())); DriftChangeSet<?> changeset = drift.getChangeSet(); setParentID(String.valueOf(changeset.getDriftConfigurationId()) + "_" + changeset.getId()); - setID(drift.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 }
+ public String getDriftId() { + String idAttrib = getAttribute("id"); + return idAttrib.substring(1); // skip the 'D' prefix! + } + @Override public String getTitle() { return super.getName(); 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 527513c..fd61d35 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 @@ -47,8 +47,8 @@ public class ResourceDriftChangeSetsTreeView extends AbstractDriftChangeSetsTree @Override protected String getNodeDetailsLink(TreeNode node) { if (node instanceof DriftTreeNode) { - String driftIdStr = node.getAttribute(AbstractDriftChangeSetsTreeDataSource.ATTR_ID).split("_")[1]; - String path = LinkManager.getDriftHistoryLink(this.context.resourceId, driftIdStr); + String driftId = ((DriftTreeNode) node).getDriftId(); + String path = LinkManager.getDriftHistoryLink(this.context.resourceId, driftId); return path; } return null;
commit 157ae63a812ab703d66bd205a17b8bbc96ebe63c Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 10:55:17 2011 -0400
Add some eager loading (this should probably be reverted and the drift tree build changed such that it is not required, if the tree stays in place moving forward).
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 3d7668b..f739389 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 @@ -31,6 +31,7 @@ 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; @@ -79,7 +80,9 @@ public class JPADriftChangeSet implements Serializable, DriftChangeSet<JPADrift> private DriftChangeSetCategory category;
@JoinColumn(name = "DRIFT_CONFIG_ID", referencedColumnName = "ID", nullable = false) - @ManyToOne(optional = false) + // @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;
@JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID", nullable = false) 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 c40cc8c..7d34297 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 @@ -118,6 +118,8 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc String changesetId = parentId.substring(parentId.indexOf('_') + 1); GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.addFilterChangeSetId(changesetId); + // TODO, this should probably not need to be eager loaded, the drift tree build should not need this + criteria.fetchChangeSet(true);
driftService.findDriftsByCriteria(criteria, new AsyncCallback<PageList<? extends Drift>>() { public void onFailure(Throwable caught) {
commit 403aef65ccf4e5fa52ca658c2c0815576d1f1c93 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 10:54:11 2011 -0400
Add DriftConfiguration as optional change set criteria fetch
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 17b2c62..a7262a2 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 @@ -48,7 +48,8 @@ public class JPADriftChangeSetCriteria extends Criteria implements DriftChangeSe private Long filterCreatedAfter; private Long filterCreatedBefore; private DriftChangeSetCategory filterCategory; - private boolean fetchDrifts; + private Boolean fetchDrifts; + private Boolean fetchDriftConfiguration;
private PageOrdering sortVersion;
@@ -190,6 +191,10 @@ public class JPADriftChangeSetCriteria extends Criteria implements DriftChangeSe return fetchDrifts; }
+ public void fetchDriftConfiguration(boolean fetchDriftConfiguration) { + this.fetchDriftConfiguration = fetchDriftConfiguration; + } + public void addSortVersion(PageOrdering sortVersion) { addSortField("version"); this.sortVersion = sortVersion;
commit 860968a9e384a8623a29662d84b0817f1f5d4d16 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 9 10:53:25 2011 -0400
- increase drift.path from 512 to 1024 precision
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 1706142..a31d6fa 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml @@ -692,7 +692,7 @@ <column name="CTIME" type="LONG" required="true"/> <column name="CATEGORY" type="VARCHAR2" size="20" required="true"/> <column name="DRIFT_CHANGE_SET_ID" type="INTEGER" required="true" references="RHQ_DRIFT_CHANGE_SET"/> - <column name="PATH" type="VARCHAR2" size="512" required="true"/> + <column name="PATH" type="VARCHAR2" size="1024" required="true"/> <column name="OLD_DRIFT_FILE" type="VARCHAR2" size="64" required="false" references="RHQ_DRIFT_FILE"/> <column name="NEW_DRIFT_FILE" type="VARCHAR2" size="64" required="false" references="RHQ_DRIFT_FILE"/> </table> diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index c4abfcb..28813ef 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3540,7 +3540,7 @@ <schema-alterColumn table="RHQ_DRIFT" column="CTIME" nullable="FALSE" /> <schema-addColumn table="RHQ_DRIFT" column="CATEGORY" columnType="VARCHAR2" precision="20" /> <schema-alterColumn table="RHQ_DRIFT" column="CATEGORY" nullable="FALSE" /> - <schema-addColumn table="RHQ_DRIFT" column="PATH" columnType="VARCHAR2" precision="512" /> + <schema-addColumn table="RHQ_DRIFT" column="PATH" columnType="VARCHAR2" precision="1024" /> <schema-alterColumn table="RHQ_DRIFT" column="PATH" nullable="FALSE" /> <schema-addColumn table="RHQ_DRIFT" column="DRIFT_CHANGE_SET_ID" columnType="INTEGER" /> <schema-directSQL>
commit 35f2799ee852fdd4bbc8fcd79a869396336eb842 Merge: 25ce6fc 3268a40 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 9 08:50:51 2011 +0200
Merge remote-tracking branch 'origin/master' into feature/config-sync
commit bf3abc78114a465c9f70affe849b85cc22d6df65 Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 21:52:20 2011 -0400
Disabled wrong test in previous commit
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 ee5ecf8..9e59e61 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 @@ -250,8 +250,9 @@ public class DriftDetectorTest extends DriftTest { .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); }
+ // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") - @Test + @Test(enabled = false) public void includeFiledAddedInNewDirectoryInDriftChangeSet() throws Exception { DriftConfiguration config = driftConfiguration("file-added-in-new-dir", resourceDir.getAbsolutePath());
@@ -276,9 +277,8 @@ public class DriftDetectorTest extends DriftTest { .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); }
- // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") - @Test(enabled = false) + @Test public void includeRemovedFileInDriftChangeSet() throws Exception { DriftConfiguration config = driftConfiguration("file-removed-drift-test", resourceDir.getAbsolutePath());
commit 2d23434891570bb1c81817db4a57cf26da176c61 Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 21:28:20 2011 -0400
disabling a couple tests
These tests were added earlier today to verify that DriftDetector is not properly handling new directories as well as removed directories. The fix is going to take some time as I am going to change the change set file format so that it is flattened out and only stores file entries.
That is going to be a big refactoring and I don't want to have those tests continually failing until the refactoring is done.
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 421798e..ee5ecf8 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 @@ -276,8 +276,9 @@ public class DriftDetectorTest extends DriftTest { .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); }
+ // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") - @Test + @Test(enabled = false) public void includeRemovedFileInDriftChangeSet() throws Exception { DriftConfiguration config = driftConfiguration("file-removed-drift-test", resourceDir.getAbsolutePath());
@@ -317,8 +318,9 @@ public class DriftDetectorTest extends DriftTest { .add(addedFileEntry("server-1.conf", sha256(server1Conf)))); }
+ // TODO enable test once change set file format is changed to only store file entries @SuppressWarnings("unchecked") - @Test + @Test(enabled = false) public void includeFilesInRemovedDirectoryInDriftChangeSet() throws Exception { DriftConfiguration config = driftConfiguration("dir-removed-test", resourceDir.getAbsolutePath());
commit 1422609b565712615048f9149ca2f1e7af22cd4d Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 20:52:10 2011 -0400
Taking DriftManagerRemote out of web services to get past JAXB errors
We weere getting JAXB errors due to our use (at least in part) of interfaces. Remove drift from webservices since there is no requirement to have it included.
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 8088839..bf5be07 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 @@ -19,10 +19,6 @@ package org.rhq.enterprise.server.drift;
import javax.ejb.Remote; -import javax.jws.WebMethod; -import javax.jws.WebParam; -import javax.jws.WebService; -import javax.jws.soap.SOAPBinding;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; @@ -31,17 +27,11 @@ import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.drift.DriftChangeSet; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.server.system.ServerVersion;
-@SOAPBinding(style = SOAPBinding.Style.DOCUMENT) -@WebService(targetNamespace = ServerVersion.namespace) @Remote public interface DriftManagerRemote {
- @WebMethod - DriftSnapshot createSnapshot(// - @WebParam(name = "subject") Subject subject, // - @WebParam(name = "criteria") DriftChangeSetCriteria criteria) throws Exception; + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) throws Exception;
/** * Standard criteria based fetch method @@ -49,10 +39,8 @@ public interface DriftManagerRemote { * @param criteria * @return The DriftChangeSets matching the criteria */ - @WebMethod - PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(// - @WebParam(name = "subject") Subject subject, // - @WebParam(name = "criteria") DriftChangeSetCriteria criteria) throws Exception; + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) throws Exception;
/** * Standard criteria based fetch method @@ -60,8 +48,6 @@ public interface DriftManagerRemote { * @param criteria * @return The Drifts matching the criteria */ - PageList<? extends Drift<?, ?>> findDriftsByCriteria(// - @WebParam(name = "subject") Subject subject, // - @WebParam(name = "criteria") DriftCriteria criteria) throws Exception; + PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) throws Exception;
} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java index c9ee8c6..96aa506 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java @@ -591,27 +591,6 @@ public class WebservicesManagerBean implements WebservicesRemote {
//DISCOVERYBOSS: END ------------------------------------
- // DRIFTMANAGER: BEGIN ---------------------------------- - - @Override - public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) throws Exception { - return driftManager.createSnapshot(subject, criteria); - } - - @Override - public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, - DriftChangeSetCriteria criteria) throws Exception { - return driftManager.findDriftChangeSetsByCriteria(subject, criteria); - } - - @Override - public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) - throws Exception { - return driftManager.findDriftsByCriteria(subject, criteria); - } - - // DRIFTMANAGER: END ------------------------------------ - //EVENTMANAGER: BEGIN ---------------------------------- public PageList<Event> findEventsByCriteria(Subject subject, EventCriteria criteria) { checkParametersPassedIn(subject, criteria); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesRemote.java index 2230a75..cd9b405 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesRemote.java @@ -52,7 +52,6 @@ public interface WebservicesRemote extends // //Removed as it was problematic for WS clients. Not sure if this well be re-enabled. // DataAccessManagerRemote,// DiscoveryBossRemote,// - DriftManagerRemote, // EventManagerRemote,// MeasurementBaselineManagerRemote,// MeasurementDataManagerRemote,//
commit 72c54ac45e2c53a20be06e620fc69a0b8bdba136 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 8 17:59:24 2011 -0400
Drift - Fix issues when adding/updating drift configs.
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 225d519..e7cd21d 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 @@ -358,17 +358,26 @@ public class DriftManagerBean implements DriftManagerLocal { throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); }
- // just completely replace an old version of the config + // Update or add the driftConfig as necessary + boolean isUpdated = false; for (Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { DriftConfiguration dc = i.next(); if (dc.getName().equals(driftConfig.getName())) { - i.remove(); + dc.setConfiguration(driftConfig.getConfiguration()); + isUpdated = true; break; } }
- resource.addDriftConfiguration(driftConfig); - entityManager.merge(resource); + if (!isUpdated) { + resource.addDriftConfiguration(driftConfig); + } + resource = entityManager.merge(resource); + + // Do not pass attached entities to the following Agent call, which is outside Hibernate's control. Flush + // and clear the entities to ensure the work above is captured and we pass out a detached object. + entityManager.flush(); + entityManager.clear();
AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService();
commit 45e733d85d383c3a96e30fadad1f4c190e4f6843 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Aug 8 15:20:12 2011 -0400
Drift Data Model Change - promote DriftConfiguration to entity - Add rhq_drift_config table - promote DriftConfiguration from pojo to entity - Replace unnecessary mapping table rhq_drift_config_map with rhq_drift_configuration.resource_id foreign key. - update db-upgrade - Add DriftConfigurationCriteria for criteria-based fetch of new entity - Update DriftConfigurationDataSource to leverage new criteria (no longer access drift configs indirectly through resource search) - Lots of tests updated
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 527a5f9..4df42fb 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 @@ -639,7 +639,7 @@ public class PluginMetadataParserTest { Configuration config = driftTemplate.getConfiguration(); DriftConfiguration dconfig = new DriftConfiguration(config);
- assertEquals(dconfig.getInterval().longValue(), 11111L); + assertEquals(dconfig.getInterval(), 11111L); assertEquals(dconfig.getBasedir().getValueContext(), BaseDirValueContext.pluginConfiguration); assertEquals(dconfig.getBasedir().getValueName(), "var.lib.test1");
@@ -679,7 +679,7 @@ public class PluginMetadataParserTest { Configuration config = driftTemplate.getConfiguration(); DriftConfiguration dconfig = new DriftConfiguration(config);
- assertEquals(dconfig.getInterval().longValue(), 22222L); + assertEquals(dconfig.getInterval(), 22222L); assertEquals(dconfig.getBasedir().getValueContext(), BaseDirValueContext.resourceConfiguration); assertEquals(dconfig.getBasedir().getValueName(), "var.lib.test2");
@@ -719,7 +719,7 @@ public class PluginMetadataParserTest { Configuration config = driftTemplate.getConfiguration(); DriftConfiguration dconfig = new DriftConfiguration(config);
- assertEquals(dconfig.getInterval().longValue(), 33333L); + assertEquals(dconfig.getInterval(), 33333L); assertEquals(dconfig.getBasedir().getValueContext(), BaseDirValueContext.measurementTrait); assertEquals(dconfig.getBasedir().getValueName(), "var.lib.test3");
@@ -781,7 +781,7 @@ public class PluginMetadataParserTest { Configuration config = driftTemplate.getConfiguration(); DriftConfiguration dconfig = new DriftConfiguration(config);
- assertEquals(dconfig.getInterval().longValue(), 44444L); + assertEquals(dconfig.getInterval(), 44444L); assertEquals(dconfig.getBasedir().getValueContext(), BaseDirValueContext.fileSystem); assertEquals(dconfig.getBasedir().getValueName(), "/wot/gorilla");
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 016c920..1706142 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml @@ -657,6 +657,23 @@ <column name="DATA_SIZE" type="LONG" required="false"/> <column name="STATUS" type="VARCHAR2" size="20" required="true"/> </table> + + <!-- A single drift configuration defining file tracking + Note: A resource or group (todo: group, other?) can have zero or more drift configurations. + Note: The name, interval and is_enabled values are also stored withing the referenced config. + This allows us to use the config editor to manipulate all fields. + Note: Name is read-only + Note: Interval unit is millis + --> + <table name="RHQ_DRIFT_CONFIG"> + <column name="ID" default="sequence-only" initial="10001" primarykey="true" required="true" type="INTEGER"/> + <column name="CTIME" type="LONG" required="true"/> + <column name="NAME" type="VARCHAR2" size="512" required="true"/> + <column name="INTERVAL" type="LONG" required="true"/> + <column name="IS_ENABLED" type="BOOLEAN" required="true"/> + <column name="CONFIG_ID" type="INTEGER" required="true" references="RHQ_CONFIG"/> + <column name="RESOURCE_ID" type="INTEGER" required="false" references="RHQ_RESOURCE"/> + </table>
<!-- A drift change-set report for a resource --> <table name="RHQ_DRIFT_CHANGE_SET"> @@ -666,7 +683,7 @@ <column name="VERSION" type="INTEGER" required="true"/> <column name="CATEGORY" type="VARCHAR2" size="20" required="true"/> <column name="RESOURCE_ID" type="INTEGER" required="true" references="RHQ_RESOURCE"/> - <column name="CONFIG_ID" type="INTEGER" required="true" references="RHQ_CONFIG"/> + <column name="DRIFT_CONFIG_ID" type="INTEGER" required="true" references="RHQ_DRIFT_CONFIG"/> </table>
<!-- A single occurence of drift for a resource --> @@ -679,7 +696,7 @@ <column name="OLD_DRIFT_FILE" type="VARCHAR2" size="64" required="false" references="RHQ_DRIFT_FILE"/> <column name="NEW_DRIFT_FILE" type="VARCHAR2" size="64" required="false" references="RHQ_DRIFT_FILE"/> </table> - + <!-- A resource type can have zero or more drift templates which correspond to <drift> elements declared in the plugin descriptor. A drift template is represented as a @@ -690,14 +707,5 @@ <column name="CONFIG_TEMPLATE_ID" type="INTEGER" required="true" references="RHQ_CONFIG_TEMPLATE"/> </table>
- <!-- - A resource can have zero or more drift configurations used for guiding drift - detection for the resource. - --> - <table name="RHQ_DRIFT_CONFIG_MAP"> - <column name="RESOURCE_ID" type="INTEGER" required="true" references="RHQ_RESOURCE"/> - <column name="CONFIG_ID" type="INTEGER" required="true" references="RHQ_CONFIG"/> - </table> - </dbsetup>
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index 98e7438..c4abfcb 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3459,6 +3459,42 @@ <schema-addColumn table="RHQ_DRIFT_FILE" column="STATUS" columnType="VARCHAR2" precision="20" /> <schema-alterColumn table="RHQ_DRIFT_FILE" column="STATUS" nullable="FALSE" />
+ <!-- RHQ_DRIFT_CONFIG --> + <schema-createSequence name="RHQ_DRIFT_CONFIG_ID_SEQ" initial="10001" /> + <schema-directSQL> + <statement desc="Creating table RHQ_DRIFT_CONFIG"> + CREATE TABLE RHQ_DRIFT_CONFIG (ID INTEGER PRIMARY KEY) + </statement> + </schema-directSQL> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="CTIME" columnType="LONG" /> + <schema-alterColumn table="RHQ_DRIFT_CONFIG" column="CTIME" nullable="FALSE" /> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="NAME" columnType="VARCHAR2" precision="512" /> + <schema-alterColumn table="RHQ_DRIFT_CONFIG" column="NAME" nullable="FALSE" /> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="INTERVAL" columnType="LONG" /> + <schema-alterColumn table="RHQ_DRIFT_CONFIG" column="INTERVAL" nullable="FALSE" /> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="IS_ENABLED" columnType="BOOLEAN" /> + <schema-alterColumn table="RHQ_DRIFT_CONFIG" column="IS_ENABLED" nullable="FALSE" /> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="CONFIG_ID" columnType="INTEGER" /> + <schema-alterColumn table="RHQ_DRIFT_CONFIG" column="CONFIG_ID" nullable="FALSE" /> + <schema-directSQL> + <statement desc="Creating RHQ_DRIFT_CONFIG foreign key relation to RHQ_CONFIG"> + ALTER TABLE RHQ_DRIFT_CONFIG + ADD CONSTRAINT RHQ_DC_CONFIG_ID_FK + FOREIGN KEY (CONFIG_ID) + REFERENCES RHQ_CONFIG (ID) + </statement> + </schema-directSQL> + <schema-addColumn table="RHQ_DRIFT_CONFIG" column="RESOURCE_ID" columnType="INTEGER" /> + <schema-directSQL> + <statement desc="Creating RHQ_DRIFT_CONFIG foreign key relation to RHQ_RESOURCE"> + ALTER TABLE RHQ_DRIFT_CONFIG + ADD CONSTRAINT RHQ_DC_RESOURCE_ID_FK + FOREIGN KEY (RESOURCE_ID) + REFERENCES RHQ_RESOURCE (ID) + </statement> + </schema-directSQL> + + <!-- RHQ_DRIFT_CHANGE_SET --> <schema-createSequence name="RHQ_DRIFT_CHANGE_SET_ID_SEQ" initial="10001" /> <schema-directSQL> @@ -3473,7 +3509,7 @@ <schema-addColumn table="RHQ_DRIFT_CHANGE_SET" column="CATEGORY" columnType="VARCHAR2" precision="20" /> <schema-alterColumn table="RHQ_DRIFT_CHANGE_SET" column="CATEGORY" nullable="FALSE" /> <schema-addColumn table="RHQ_DRIFT_CHANGE_SET" column="RESOURCE_ID" columnType="INTEGER" /> - <schema-addColumn table="RHQ_DRIFT_CHANGE_SET" column="CONFIG_ID" columnType="INTEGER" /> + <schema-alterColumn table="RHQ_DRIFT_CHANGE_SET" column="RESOURCE_ID" nullable="FALSE" /> <schema-directSQL> <statement desc="Creating RHQ_DRIFT_CHANGE_SET foreign key relation to RHQ_RESOURCE"> ALTER TABLE RHQ_DRIFT_CHANGE_SET @@ -3481,17 +3517,17 @@ FOREIGN KEY (RESOURCE_ID) REFERENCES RHQ_RESOURCE (ID) </statement> - </schema-directSQL> + </schema-directSQL> + <schema-addColumn table="RHQ_DRIFT_CHANGE_SET" column="DRIFT_CONFIG_ID" columnType="INTEGER" /> + <schema-alterColumn table="RHQ_DRIFT_CHANGE_SET" column="DRIFT_CONFIG_ID" nullable="FALSE" /> <schema-directSQL> - <statement desc="Creating RHQ_DRIFT_CHANGE_SET foreign key relation to RHQ_CONFIG"> + <statement desc="Creating RHQ_DRIFT_CHANGE_SET foreign key relation to RHQ_DRIFT_CONFIG"> ALTER TABLE RHQ_DRIFT_CHANGE_SET - ADD CONSTRAINT RHQ_DCS_CONFIG_ID_FK - FOREIGN KEY (CONFIG_ID) + ADD CONSTRAINT RHQ_DCS_DRIFT_CONFIG_ID_FK + FOREIGN KEY (DRIFT_CONFIG_ID) REFERENCES RHQ_CONFIG (ID) </statement> </schema-directSQL> - <schema-alterColumn table="RHQ_DRIFT_CHANGE_SET" column="RESOURCE_ID" nullable="FALSE" /> - <schema-alterColumn table="RHQ_DRIFT_CHANGE_SET" column="CONFIG_ID" nullable="FALSE" />
<!-- RHQ_DRIFT --> <schema-createSequence name="RHQ_DRIFT_ID_SEQ" initial="10001" /> @@ -3559,31 +3595,6 @@ REFERENCES RHQ_CONFIG_TEMPLATE (ID) </statement> </schema-directSQL> - - <!-- RHQ_DRIFT_CONFIG_MAP --> - <schema-directSQL> - <statement desc="Creating table RHQ_DRIFT_CONFIG_MAP"> - CREATE TABLE RHQ_DRIFT_CONFIG_MAP ( - RESOURCE_ID INTEGER, - CONFIG_ID INTEGER) - </statement> - </schema-directSQL> - <schema-alterColumn table="RHQ_DRIFT_CONFIG_MAP" column="RESOURCE_ID" nullable="FALSE"/> - <schema-alterColumn table="RHQ_DRIFT_CONFIG_MAP" column="CONFIG_ID" nullable="FALSE"/> - <schema-directSQL> - <statement desc="Creating RHQ_DRIFT_CONFIG_MAP foreign key to RHQ_RESOURCE"> - ALTER TABLE RHQ_DRIFT_CONFIG_MAP - ADD CONSTRAINT RHQ_DCM_RESOURCE_ID_FK - FOREIGN KEY (RESOURCE_ID) - REFERENCES RHQ_RESOURCE (ID) - </statement> - <statement desc="Creating RHQ_DRIFT_CONFIG_MAP foreign key to RHQ_CONFIG"> - ALTER TABLE RHQ_DRIFT_CONFIG_MAP - ADD CONSTRAINT RHQ_DCM_CONFIG_ID_FK - FOREIGN KEY (CONFIG_ID) - REFERENCES RHQ_CONFIG (ID) - </statement> - </schema-directSQL> </schemaSpec>
<schemaSpec version="2.112"> 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 new file mode 100644 index 0000000..e2ed959 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftConfigurationCriteria.java @@ -0,0 +1,87 @@ +/* + * 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 +@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/JPADriftChangeSetCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java index 331400c..17b2c62 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; + private Integer filterDriftConfigurationId; // needs override private Integer filterVersion; private Integer filterStartVersion; private Integer filterEndVersion; @@ -63,6 +63,7 @@ public class JPADriftChangeSetCriteria extends Criteria implements DriftChangeSe filterOverrides.put("endVersion", "version <= ?"); filterOverrides.put("createdAfter", "ctime >= ?"); filterOverrides.put("createdBefore", "ctime <= ?"); + filterOverrides.put("driftConfigurationId", "driftConfiguration.id = ?");
if (null != changeSetCriteria) { this.addFilterCategory(changeSetCriteria.getFilterCategory()); 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 f6144c3..b8be2b2 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 @@ -22,11 +22,20 @@ import static java.util.Collections.emptyList;
import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; import java.util.List; -import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +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; @@ -49,11 +58,134 @@ import org.rhq.core.domain.resource.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; + + // 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 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(); + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + if (this.resource != null) { + this.resource.getDriftConfigurations().add(this); + } + } + public static class BaseDirectory implements Serializable { private static final long serialVersionUID = 1L; private BaseDirValueContext context; @@ -178,35 +310,13 @@ public class DriftConfiguration implements Serializable { } }
- private Configuration configuration; - - // required for jaxb/web services stuff - protected DriftConfiguration() { - } - - public DriftConfiguration(Configuration c) { - this.configuration = c; - } - - public Configuration getConfiguration() { - return configuration; - } - - public int getId() { - return configuration.getId(); - } - - public void setId(int id) { - configuration.setId(id); + private String getNameProperty() { + return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME, null); }
- public String getName() { - return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_NAME, ""); - } - - public void setName(String name) { + private void setNameProperty(String name) { if (name == null) { - throw new NullPointerException("name is null"); + throw new IllegalArgumentException("name is null"); } configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_NAME, name)); } @@ -256,25 +366,21 @@ public class DriftConfiguration implements Serializable { configuration.put(basedirMap); }
- public Long getInterval() { + private Long getIntervalProperty() { return Long.parseLong(configuration.getSimpleValue(DriftConfigurationDefinition.PROP_INTERVAL, String .valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL))); }
- public void setInterval(Long interval) { - if (interval == null) { - configuration.remove(DriftConfigurationDefinition.PROP_INTERVAL); - } else { - configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL, interval.toString())); - } + private void setIntervalProperty(Long interval) { + configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_INTERVAL, interval.toString())); }
- public boolean getEnabled() { + private boolean getIsEnabledProperty() { return configuration.getSimpleValue(DriftConfigurationDefinition.PROP_ENABLED, String.valueOf(DriftConfigurationDefinition.DEFAULT_ENABLED)).equals("true"); }
- public void setEnabled(boolean enabled) { + private void setEnabledProperty(boolean enabled) { configuration.put(new PropertySimple(DriftConfigurationDefinition.PROP_ENABLED, String.valueOf(enabled))); }
@@ -301,38 +407,4 @@ public class DriftConfiguration implements Serializable {
return filters; } - - public static Set<DriftConfiguration> valueOf(Resource resource) { - if (null == resource) { - return new HashSet<DriftConfiguration>(0); - } - - Set<Configuration> configs = resource.getDriftConfigurations(); - if (null == configs) { - return new HashSet<DriftConfiguration>(0); - } - - Set<DriftConfiguration> result = new HashSet<DriftConfiguration>(configs.size()); - - for (Iterator<Configuration> i = configs.iterator(); i.hasNext();) { - result.add(new DriftConfiguration(i.next())); - } - - return result; - } - - public static <T extends Collection<Configuration>> Set<DriftConfiguration> valueOf(T configs) { - if (null == configs) { - return new HashSet<DriftConfiguration>(0); - } - - Set<DriftConfiguration> result = new HashSet<DriftConfiguration>(configs.size()); - - for (Iterator<Configuration> i = configs.iterator(); i.hasNext();) { - result.add(new DriftConfiguration(i.next())); - } - - return result; - } - } 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 975d7d1..3d7668b 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 @@ -78,8 +78,9 @@ public class JPADriftChangeSet implements Serializable, DriftChangeSet<JPADrift> @Enumerated(EnumType.STRING) private DriftChangeSetCategory category;
- @Column(name = "CONFIG_ID", nullable = false) - private int driftConfigurationId; + @JoinColumn(name = "DRIFT_CONFIG_ID", referencedColumnName = "ID", nullable = false) + @ManyToOne(optional = false) + private DriftConfiguration driftConfiguration;
@JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID", nullable = false) @ManyToOne(optional = false) @@ -91,11 +92,12 @@ public class JPADriftChangeSet implements Serializable, DriftChangeSet<JPADrift> protected JPADriftChangeSet() { }
- public JPADriftChangeSet(Resource resource, int version, DriftChangeSetCategory category, int configId) { + public JPADriftChangeSet(Resource resource, int version, DriftChangeSetCategory category, + DriftConfiguration driftConfiguration) { this.resource = resource; this.version = version; this.category = category; - driftConfigurationId = configId; + this.driftConfiguration = driftConfiguration; }
@Override @@ -151,14 +153,22 @@ public class JPADriftChangeSet implements Serializable, DriftChangeSet<JPADrift> this.resource = resource; }
+ public DriftConfiguration getDriftConfiguration() { + return driftConfiguration; + } + + public void setDriftConfiguration(DriftConfiguration driftConfiguration) { + this.driftConfiguration = driftConfiguration; + } + @Override public int getDriftConfigurationId() { - return driftConfigurationId; + return this.driftConfiguration.getId(); }
@Override public void setDriftConfigurationId(int id) { - driftConfigurationId = id; + this.driftConfiguration.setId(id); }
@Override 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 eea5859..40afa2f 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 @@ -39,7 +39,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; @@ -70,6 +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.event.EventSource; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.measurement.MeasurementSchedule; @@ -1074,11 +1074,9 @@ public class Resource implements Comparable<Resource>, Serializable { @OneToMany(mappedBy = "resource", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) private Set<Dashboard> dashboards = null;
- @JoinTable(name = "RHQ_DRIFT_CONFIG_MAP", joinColumns = { @JoinColumn(name = "RESOURCE_ID", nullable = false) }, - inverseJoinColumns = { @JoinColumn(name = "CONFIG_ID", nullable = false)}) - @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) + @OneToMany(mappedBy = "resource", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }) @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) - private Set<Configuration> driftConfigurations = null; + private Set<DriftConfiguration> driftConfigurations = null;
public Resource() { } @@ -1749,14 +1747,23 @@ public class Resource implements Comparable<Resource>, Serializable { this.dashboards = dashboards; }
- public Set<Configuration> getDriftConfigurations() { + public Set<DriftConfiguration> getDriftConfigurations() { + if (this.driftConfigurations == null) { + this.driftConfigurations = new LinkedHashSet<DriftConfiguration>(); + } + return driftConfigurations; }
- public void setDriftConfigurations(Set<Configuration> driftConfigurations) { + public void setDriftConfigurations(Set<DriftConfiguration> driftConfigurations) { this.driftConfigurations = driftConfigurations; }
+ public void addDriftConfiguration(DriftConfiguration driftConfiguration) { + getDriftConfigurations().add(driftConfiguration); + driftConfiguration.setResource(this); + } + public int compareTo(Resource that) { return this.name.compareTo(that.getName()); } 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 1efbe72..1440cf3 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 @@ -1,6 +1,12 @@ package org.rhq.core.domain.drift;
-import java.util.Arrays; +import static java.util.Arrays.asList; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; +import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; +import static org.testng.Assert.assertEquals; + import java.util.List;
import org.testng.annotations.Test; @@ -10,13 +16,6 @@ import org.rhq.core.domain.configuration.PropertyList; import org.rhq.core.domain.configuration.PropertyMap; import org.rhq.core.domain.configuration.PropertySimple;
-import static java.util.Arrays.asList; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUECONTEXT; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.PROP_BASEDIR_VALUENAME; -import static org.testng.Assert.*; - public class DriftConfigurationTest { @Test public void getName() { @@ -31,7 +30,7 @@ public class DriftConfigurationTest {
@Test public void getBasedirForFileSystemContext() { - String basedir = "/opt/drift/test" ; + String basedir = "/opt/drift/test"; Configuration config = new Configuration();
PropertyMap map = new PropertyMap(PROP_BASEDIR); @@ -48,7 +47,7 @@ public class DriftConfigurationTest {
@Test public void getInterval() { - Long interval = 3600L; + long interval = 3600L; Configuration config = new Configuration(); config.put(new PropertySimple("interval", interval));
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 4beaed1..868073e 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,6 +19,10 @@
package org.rhq.core.pc.drift;
+import static java.util.Collections.EMPTY_LIST; +import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; +import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; + import java.io.File; import java.io.IOException; import java.util.Collection; @@ -37,10 +41,6 @@ import org.rhq.core.domain.drift.DriftChangeSetCategory; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.util.MessageDigestGenerator;
-import static java.util.Collections.EMPTY_LIST; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; - public class DriftDetector implements Runnable { private Log log = LogFactory.getLog(DriftDetector.class);
@@ -76,7 +76,7 @@ public class DriftDetector implements Runnable { return; }
- if (!schedule.getDriftConfiguration().getEnabled()) { + if (!schedule.getDriftConfiguration().isEnabled()) { return; }
@@ -109,12 +109,12 @@ public class DriftDetector implements Runnable { private int generateDriftChangeSet(DriftDetectionSchedule schedule) throws IOException { File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration()));
- ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), - createHeaders(schedule, DRIFT)); + ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, + DRIFT)); ChangeSetWriter coverageWriter = changeSetMgr.getChangeSetWriterForUpdate(schedule.getResourceId(), createHeaders(schedule, COVERAGE)); - ChangeSetReader reader = changeSetMgr.getChangeSetReader(schedule.getResourceId(), - schedule.getDriftConfiguration().getName()); + ChangeSetReader reader = changeSetMgr.getChangeSetReader(schedule.getResourceId(), schedule + .getDriftConfiguration().getName());
int changes = 0;
@@ -122,8 +122,8 @@ public class DriftDetector implements Runnable { DirectoryAnalyzer analyzer = new DirectoryAnalyzer(basedir, dirEntry); analyzer.run();
- if (analyzer.getFilesAdded().size() > 0 || analyzer.getFilesRemoved().size() > 0 || - analyzer.getFilesChanged().size() > 0) { + if (analyzer.getFilesAdded().size() > 0 || analyzer.getFilesRemoved().size() > 0 + || analyzer.getFilesChanged().size() > 0) { DirectoryEntry driftDirEntry = new DirectoryEntry(dirEntry.getDirectory()); DirectoryEntry coverageDirEntry = new DirectoryEntry(dirEntry.getDirectory());
@@ -221,11 +221,13 @@ public class DriftDetector implements Runnable { walk(new File(basedir(resourceId, driftConfig)), EMPTY_LIST); }
+ @SuppressWarnings("unchecked") @Override protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException { stack.push(new DirectoryEntry(relativePath(new File(basedir(resourceId, driftConfig)), directory))); }
+ @SuppressWarnings("unchecked") @Override protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException { DirectoryEntry dirEntry = stack.pop(); @@ -234,12 +236,14 @@ public class DriftDetector implements Runnable { } }
+ @SuppressWarnings("unchecked") @Override protected void handleFile(File file, int depth, Collection results) throws IOException { DirectoryEntry dirEntry = stack.peek(); dirEntry.add(FileEntry.addedFileEntry(file.getName(), sha256(file))); }
+ @SuppressWarnings("unchecked") @Override protected void handleEnd(Collection results) throws IOException { writer.close(); 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 497e067..26e2b1a 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 @@ -19,8 +19,8 @@ public class ScheduleQueueImpl implements ScheduleQueue { try { lock.writeLock().lock(); if (activeSchedule != null) { - throw new IllegalStateException("There is already an active schedule that must be deactivated " + - "before getting the next schedule."); + throw new IllegalStateException("There is already an active schedule that must be deactivated " + + "before getting the next schedule."); } activeSchedule = queue.poll(); return activeSchedule == null ? null : activeSchedule.copy(); @@ -32,8 +32,8 @@ public class ScheduleQueueImpl implements ScheduleQueue { private boolean isActiveSchedule(int resourceId, DriftConfiguration config) { try { lock.readLock().lock(); - return activeSchedule != null && activeSchedule.getResourceId() == resourceId && - activeSchedule.getDriftConfiguration().getName().equals(config.getName()); + return activeSchedule != null && activeSchedule.getResourceId() == resourceId + && activeSchedule.getDriftConfiguration().getName().equals(config.getName()); } finally { lock.readLock().unlock(); } @@ -80,8 +80,8 @@ public class ScheduleQueueImpl implements ScheduleQueue { Iterator<DriftDetectionSchedule> iterator = queue.iterator(); while (iterator.hasNext()) { DriftDetectionSchedule schedule = iterator.next(); - if (schedule.getResourceId() == resourceId && - schedule.getDriftConfiguration().getName().equals(config.getName())) { + if (schedule.getResourceId() == resourceId + && schedule.getDriftConfiguration().getName().equals(config.getName())) { iterator.remove(); return schedule; } @@ -114,7 +114,7 @@ public class ScheduleQueueImpl implements ScheduleQueue { }
private void update(DriftDetectionSchedule schedule, DriftConfiguration config) { - schedule.getDriftConfiguration().setEnabled(config.getEnabled()); + schedule.getDriftConfiguration().setEnabled(config.isEnabled()); schedule.getDriftConfiguration().setInterval(config.getInterval()); }
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 2aa8388..1c09ee9 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 @@ -286,7 +286,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid static class DriftConfigurationTreeNode extends TreeNode { public DriftConfigurationTreeNode(DriftConfiguration driftConfig) { setIsFolder(true); - if (driftConfig.getEnabled()) { + if (driftConfig.isEnabled()) { setIcon("subsystems/drift/DriftConfig_Folder_16.png"); } else { setIcon("subsystems/drift/DriftConfig_Disabled_Folder_16.png"); 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 index 1fc9c61..3a5707a 100644 --- 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 @@ -19,9 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.drift;
import java.util.ArrayList; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.Collection;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; @@ -36,20 +34,16 @@ 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.ResourceCriteria; +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.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.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.gwt.ResourceGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.inventory.resource.AncestryUtil; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.TypesLoadedCallback; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
@@ -57,7 +51,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Jay Shaughnessy * @author John Mazzitelli */ -public class DriftConfigurationDataSource extends RPCDataSource<DriftConfiguration, ResourceCriteria> { +public class DriftConfigurationDataSource extends RPCDataSource<DriftConfiguration, DriftConfigurationCriteria> {
public static final String ATTR_ENTITY = "object"; public static final String ATTR_ID = "id"; @@ -66,7 +60,7 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati public static final String ATTR_BASE_DIR_STRING = "baseDirString"; public static final String ATTR_ENABLED = "enabled";
- private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); + private DriftGWTServiceAsync driftService = GWTServiceLookup.getDriftService(); private EntityContext entityContext;
public DriftConfigurationDataSource() { @@ -141,80 +135,43 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati }
@Override - protected void executeFetch(final DSRequest request, final DSResponse response, final ResourceCriteria criteria) { - this.resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_inventory_resources_loadFailed(), caught); - response.setStatus(RPCResponse.STATUS_FAILURE); - processResponse(request.getRequestId(), response); - } - - public void onSuccess(PageList<Resource> result) { - dataRetrieved(result, response, request); - } - }); + 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<Resource> result, final DSResponse response, final DSRequest request) { + 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: - Set<DriftConfiguration> driftConfigs = DriftConfiguration.valueOf(result.get(0)); - response.setData(buildRecords(driftConfigs)); + response.setData(buildRecords(result)); // for paging to work we have to specify size of full result set - response.setTotalRows(getTotalRows(driftConfigs, response, request)); + response.setTotalRows(getTotalRows(result, response, request)); processResponse(request.getRequestId(), response); break;
- // disambiguate as the results could be cross-resource - default: - Set<Integer> typesSet = new HashSet<Integer>(); - Set<String> ancestries = new HashSet<String>(); - for (Resource resource : result) { - typesSet.add(resource.getResourceType().getId()); - ancestries.add(resource.getAncestry()); - } - - // In addition to the types of the result resources, get the types of their ancestry - typesSet.addAll(AncestryUtil.getAncestryTypeIds(ancestries)); - - ResourceTypeRepository typeRepo = ResourceTypeRepository.Cache.getInstance(); - typeRepo.getResourceTypes(typesSet.toArray(new Integer[typesSet.size()]), new TypesLoadedCallback() { - @Override - public void onTypesLoaded(Map<Integer, ResourceType> types) { - // Smartgwt has issues storing a Map as a ListGridRecord attribute. Wrap it in a pojo. - AncestryUtil.MapWrapper typesWrapper = new AncestryUtil.MapWrapper(types); - - Set<DriftConfiguration> driftConfigs = getDriftConfigs(result); - Record[] records = buildRecords(driftConfigs); - for (Record record : records) { - // To avoid a lot of unnecessary String construction, be lazy about building ancestry hover text. - // Store the types map off the records so we can build a detailed hover string as needed. - record.setAttribute(AncestryUtil.RESOURCE_ANCESTRY_TYPES, typesWrapper); - - // Build the decoded ancestry Strings now for display - record - .setAttribute(AncestryUtil.RESOURCE_ANCESTRY_VALUE, AncestryUtil.getAncestryValue(record)); - } - response.setData(records); - // for paging to work we have to specify size of full result set - response.setTotalRows(getTotalRows(driftConfigs, response, request)); - processResponse(request.getRequestId(), response); - } - }); - } - } + case ResourceGroup: + //TODO
- private Set<DriftConfiguration> getDriftConfigs(PageList<Resource> resources) { - Set<DriftConfiguration> result = new HashSet<DriftConfiguration>(); - for (Resource resource : resources) { - result.addAll(DriftConfiguration.valueOf(resource.getDriftConfigurations())); + default: + throw new IllegalArgumentException("Unsupported Context Type: " + entityContext); } - return result; }
/** @@ -227,33 +184,34 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati * * @return should not exceed result.size(). */ - protected int getTotalRows(final Set<DriftConfiguration> result, final DSResponse response, final DSRequest request) { + protected int getTotalRows(final Collection<DriftConfiguration> result, final DSResponse response, + final DSRequest request) { return result.size(); }
@Override - protected ResourceCriteria getFetchCriteria(DSRequest request) { + protected DriftConfigurationCriteria getFetchCriteria(DSRequest request) {
- ResourceCriteria criteria = new ResourceCriteria(); + DriftConfigurationCriteria criteria = new DriftConfigurationCriteria(); switch (entityContext.getType()) { case Resource: - criteria.addFilterId(entityContext.getResourceId()); + criteria.addFilterResourceIds(entityContext.getResourceId()); break;
case ResourceGroup: - criteria.addFilterExplicitGroupIds(entityContext.getGroupId()); - break; + //TODO
default: // no filter }
- criteria.fetchDriftConfigurations(true); + criteria.fetchConfiguration(true); criteria.setPageControl(getPageControl(request));
return criteria; }
+ /* @Override protected String getSortFieldForColumn(String columnName) { if (AncestryUtil.RESOURCE_ANCESTRY.equals(columnName)) { @@ -262,6 +220,7 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati
return super.getSortFieldForColumn(columnName); } + */
@Override public DriftConfiguration copyValues(Record from) { @@ -282,7 +241,7 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati record.setAttribute(ATTR_NAME, from.getName()); record.setAttribute(ATTR_INTERVAL, String.valueOf(from.getInterval())); record.setAttribute(ATTR_BASE_DIR_STRING, getBaseDirString(from.getBasedir())); - record.setAttribute(ATTR_ENABLED, ImageManager.getAvailabilityIcon(from.getEnabled())); + record.setAttribute(ATTR_ENABLED, ImageManager.getAvailabilityIcon(from.isEnabled()));
// // for ancestry handling // Resource resource = ... @@ -298,10 +257,6 @@ public class DriftConfigurationDataSource extends RPCDataSource<DriftConfigurati return basedir.getValueContext() + ":" + basedir.getValueName(); }
- public ResourceGWTServiceAsync getResourceService() { - return resourceService; - } - protected EntityContext getEntityContext() { return entityContext; } 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 index 8d9c726..53a68fd 100644 --- 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 @@ -114,7 +114,7 @@ public class DriftConfigurationEditView extends LocatableVLayout implements Prop removeMember(editor); }
- GWTServiceLookup.getDriftService().getDriftConfiguration(context, driftConfigId, + GWTServiceLookup.getDriftService().getDriftConfiguration(driftConfigId, new AsyncCallback<DriftConfiguration>() { @Override public void onSuccess(final DriftConfiguration result) { 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 519abf5..693998b 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 @@ -60,7 +60,7 @@ public class ResourceDriftChangeSetsTreeDataSource extends AbstractDriftChangeSe criteria.fetchDriftConfigurations(true); this.resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { public void onSuccess(PageList<Resource> result) { - Set<DriftConfiguration> driftConfigs = DriftConfiguration.valueOf(result.get(0)); + Set<DriftConfiguration> driftConfigs = result.get(0).getDriftConfigurations(); 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/gwt/DriftGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/DriftGWTService.java index 3618885..ff195c8 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,6 +22,7 @@ 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.GenericDriftChangeSetCriteria; import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; @@ -36,6 +37,8 @@ import org.rhq.core.domain.util.PageList; */ public interface DriftGWTService extends RemoteService {
+ DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) throws RuntimeException; + /** * Delete the drifts with the specified ids 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). @@ -107,6 +110,18 @@ public interface DriftGWTService extends RemoteService { PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) throws RuntimeException;
+ PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria) throws RuntimeException; + + /** + * Find all drift configurations that match the specified criteria. + * + * @param criteria the criteria + * + * @return all drift configurations that matches the specified criteria + */ + PageList<DriftConfiguration> findDriftConfigurationsByCriteria(DriftConfigurationCriteria criteria) + throws RuntimeException; + /** * Find all drifts that match the specified criteria. * @@ -116,19 +131,14 @@ public interface DriftGWTService extends RemoteService { */ PageList<? extends Drift<?, ?>> findDriftsByCriteria(GenericDriftCriteria criteria) throws RuntimeException;
- PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria); - - DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria); - /** - * Get the specified drift configuration for the specified context. + * Get the specified drift configuration. * - * @param entityContext * @param driftConfigId * @return * @throws RuntimeException */ - DriftConfiguration getDriftConfiguration(EntityContext entityContext, int driftConfigId) throws RuntimeException; + DriftConfiguration getDriftConfiguration(int driftConfigId) throws RuntimeException;
/** * Update the provided driftConfig (identified by name) on the specified EntityContext. If it exists it will be replaced. If not it will 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 e71c602..f1ea5db 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,6 +20,7 @@ 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.GenericDriftChangeSetCriteria; import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; @@ -112,7 +113,8 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria) { + public PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria) + throws RuntimeException { try { PageList<DriftComposite> results = driftManager .findDriftCompositesByCriteria(getSessionSubject(), criteria); @@ -123,6 +125,18 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override + public PageList<DriftConfiguration> findDriftConfigurationsByCriteria(DriftConfigurationCriteria criteria) + throws RuntimeException { + try { + PageList<DriftConfiguration> results = driftManager.findDriftConfigurationsByCriteria(getSessionSubject(), + criteria); + return SerialUtility.prepare(results, "DriftService.findDriftConfigurationsByCriteria"); + } catch (Throwable t) { + throw getExceptionToThrowToClient(t); + } + } + + @Override public DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) { try { return driftManager.createSnapshot(subject, criteria); @@ -132,11 +146,9 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public DriftConfiguration getDriftConfiguration(EntityContext entityContext, int driftConfigId) - throws RuntimeException { + public DriftConfiguration getDriftConfiguration(int driftConfigId) throws RuntimeException { try { - DriftConfiguration driftConfig = driftManager.getDriftConfiguration(getSessionSubject(), entityContext, - driftConfigId); + DriftConfiguration driftConfig = driftManager.getDriftConfiguration(getSessionSubject(), driftConfigId); return SerialUtility.prepare(driftConfig, "DriftService.getDriftConfiguration"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); 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 2289bf6..225d519 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 @@ -47,8 +47,8 @@ import org.jboss.remoting.CannotConnectException; 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.configuration.Configuration; 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.JPADriftCriteria; import org.rhq.core.domain.drift.Drift; @@ -68,6 +68,8 @@ import org.rhq.enterprise.server.plugin.pc.MasterServerPluginContainer; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginContainer; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginManager; +import org.rhq.enterprise.server.util.CriteriaQueryGenerator; +import org.rhq.enterprise.server.util.CriteriaQueryRunner; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -251,8 +253,8 @@ public class DriftManagerBean implements DriftManagerLocal { throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); }
- for (Iterator<Configuration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = new DriftConfiguration(i.next()); + for (Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { + DriftConfiguration dc = i.next(); if (dc.getName().equals(driftConfigName)) { i.remove(); entityManager.merge(resource); @@ -292,6 +294,18 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override + public PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject subject, + DriftConfigurationCriteria criteria) { + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); + CriteriaQueryRunner<DriftConfiguration> queryRunner = new CriteriaQueryRunner<DriftConfiguration>(criteria, + generator, entityManager); + PageList<DriftConfiguration> result = queryRunner.execute(); + + return result; + } + + @Override @TransactionAttribute(NOT_SUPPORTED) public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { DriftServerPluginFacet driftServerPlugin = getServerPlugin(); @@ -299,34 +313,17 @@ public class DriftManagerBean implements DriftManagerLocal { }
@Override - public DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId) { - DriftConfiguration result = null; - - switch (entityContext.getType()) { - case Resource: - Resource resource = entityManager.find(Resource.class, entityContext.getResourceId()); - if (null == resource) { - throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); - } - - for (Configuration config : resource.getDriftConfigurations()) { - if (config.getId() == driftConfigId) { - result = new DriftConfiguration(config); - break; - } - } - - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); - } + public DriftConfiguration getDriftConfiguration(Subject subject, int driftConfigId) { + DriftConfiguration result = entityManager.find(DriftConfiguration.class, driftConfigId);
if (null == result) { - throw new IllegalArgumentException("Drift Configuration Id [" + driftConfigId - + "] not found for entityContext [" + entityContext + "]"); + throw new IllegalArgumentException("Drift Configuration Id [" + driftConfigId + "] not found."); }
+ // force lazy loads + result.getConfiguration().getProperties(); + result.getResource(); + return result; }
@@ -361,15 +358,16 @@ public class DriftManagerBean implements DriftManagerLocal { throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); }
- for (Iterator<Configuration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = new DriftConfiguration(i.next()); + // just completely replace an old version of the config + for (Iterator<DriftConfiguration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { + DriftConfiguration dc = i.next(); if (dc.getName().equals(driftConfig.getName())) { i.remove(); break; } }
- resource.getDriftConfigurations().add(driftConfig.getConfiguration()); + resource.addDriftConfiguration(driftConfig); entityManager.merge(resource);
AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); 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 ca98149..3ac01b2 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 @@ -25,7 +25,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.drift.DriftConfiguration; +import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
@Local @@ -108,15 +110,16 @@ public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerR */ void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig);
+ PageList<DriftConfiguration> findDriftConfigurationsByCriteria(Subject subject, DriftConfigurationCriteria criteria); + /** - * Get the specified drift configuration for the specified context. + * Get the specified drift configuration. Note, the full Configuration is fetched. * - * @param entityContext * @param driftConfigId * @return The drift configuration * @throws RuntimeException, IllegalArgumentException if entity or driftConfig not found. */ - DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId); + DriftConfiguration getDriftConfiguration(Subject subject, int driftConfigId);
/** * Update the provided driftConfig (identified by name) on the specified EntityContext. If it exists it will be replaced. If not it will 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 c66b900..a792715 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 @@ -210,7 +210,7 @@ public class JPADriftServerBean implements JPADriftServerLocal { }
DriftChangeSetCategory category = reader.getHeaders().getType(); - driftChangeSet = new JPADriftChangeSet(resource, version, category, config.getId()); + driftChangeSet = new JPADriftChangeSet(resource, version, category, config); entityManager.persist(driftChangeSet);
for (DirectoryEntry dir = reader.readDirectoryEntry(); null != dir; dir = reader @@ -314,8 +314,7 @@ public class JPADriftServerBean implements JPADriftServerLocal { }
private DriftConfiguration findDriftConfiguration(Resource resource, Headers headers) { - for (Configuration config : resource.getDriftConfigurations()) { - DriftConfiguration driftConfig = new DriftConfiguration(config); + for (DriftConfiguration driftConfig : resource.getDriftConfigurations()) { if (driftConfig.getName().equals(headers.getDriftConfigurationName())) { return driftConfig; } 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 69f0984..436ac1e 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 @@ -19,7 +19,6 @@ package org.rhq.enterprise.server.drift;
import java.io.File; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; @@ -39,8 +38,6 @@ import org.rhq.core.clientapi.server.drift.DriftServerService; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertyMap; -import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.drift.Drift; @@ -49,6 +46,7 @@ import org.rhq.core.domain.drift.DriftChangeSet; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus; +import org.rhq.core.domain.drift.DriftConfiguration.BaseDirectory; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.InventoryStatus; @@ -165,13 +163,10 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { @Test(enabled = ENABLE_TESTS) public void testDriftConfig() throws Exception { Configuration config = new Configuration(); - config.put(new PropertySimple("name", "testDriftConfig")); - config.put(new PropertySimple("interval", "60")); - PropertyMap basedirMap = new PropertyMap("basedir"); - basedirMap.put(new PropertySimple("valueContext", BaseDirValueContext.fileSystem)); - basedirMap.put(new PropertySimple("valueName", "foo/bar")); - config.put(basedirMap); DriftConfiguration driftConfigPojo = new DriftConfiguration(config); + driftConfigPojo.setName("testDriftConfig"); + driftConfigPojo.setInterval(60L); + driftConfigPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/bar"));
driftManager .updateDriftConfiguration(overlord, EntityContext.forResource(newResource.getId()), driftConfigPojo); @@ -182,16 +177,21 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { c.fetchDriftConfigurations(true); List<Resource> resources = resourceManager.findResourcesByCriteria(overlord, c); assertEquals(1, resources.size()); - Set<Configuration> driftConfigs = resources.get(0).getDriftConfigurations(); + Set<DriftConfiguration> driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); assertEquals(3, driftConfigs.size()); - DriftConfiguration driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); + DriftConfiguration driftConfig = null; + for (Iterator<DriftConfiguration> i = driftConfigs.iterator(); i.hasNext();) { + driftConfig = i.next(); + if (driftConfigPojo.getName().equals(driftConfig.getName())) + break; + } assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getName(), driftConfig.getName()); assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir()); assertEquals(driftConfigPojo.getInterval(), driftConfig.getInterval());
- driftConfigPojo.getConfiguration().put(new PropertySimple("interval", "120")); + driftConfigPojo.setInterval(120L); driftManager .updateDriftConfiguration(overlord, EntityContext.forResource(newResource.getId()), driftConfigPojo);
@@ -200,19 +200,20 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); assertEquals(3, driftConfigs.size()); - driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); - assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted + driftConfig = null; + for (Iterator<DriftConfiguration> i = driftConfigs.iterator(); i.hasNext();) { + driftConfig = i.next(); + if (driftConfigPojo.getName().equals(driftConfig.getName())) + break; + } assertEquals(driftConfigPojo.getName(), driftConfig.getName()); + assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir()); - assertEquals(new Long(120), driftConfig.getInterval()); + assertEquals(120L, driftConfig.getInterval());
- config = driftConfigPojo.getConfiguration(); - config.put(new PropertySimple("name", "testDriftConfig-2")); - config.put(new PropertySimple("interval", "30")); - basedirMap = new PropertyMap("basedir"); - basedirMap.put(new PropertySimple("valueContext", BaseDirValueContext.fileSystem)); - basedirMap.put(new PropertySimple("valueName", "foo/baz")); - config.put(basedirMap); + driftConfigPojo.setName("testDriftConfig-2"); + driftConfigPojo.setInterval(30L); + driftConfigPojo.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "foo/baz"));
driftManager .updateDriftConfiguration(overlord, EntityContext.forResource(newResource.getId()), driftConfigPojo); @@ -222,13 +223,13 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); assertEquals(4, driftConfigs.size()); - for (Iterator<Configuration> i = driftConfigs.iterator(); i.hasNext();) { - driftConfig = new DriftConfiguration(i.next()); + 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(new Long(120), driftConfig.getInterval()); + assertEquals(120L, driftConfig.getInterval()); } else if ("testDriftConfig-2".equals(driftConfig.getName())) { assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir()); @@ -245,7 +246,11 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); assertEquals(3, driftConfigs.size()); - driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); + for (Iterator<DriftConfiguration> i = driftConfigs.iterator(); i.hasNext();) { + driftConfig = i.next(); + if (driftConfigPojo.getName().equals(driftConfig.getName())) + break; + } assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getName(), driftConfig.getName()); assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir()); @@ -299,15 +304,12 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { DriftConfiguration test2Config = new DriftConfiguration(new Configuration()); test2Config.setName("test-2");
- Set<Configuration> driftConfigs = new HashSet<Configuration>(); - driftConfigs.add(test1Config.getConfiguration()); - driftConfigs.add(test2Config.getConfiguration()); - resource = new Resource("reskey" + System.currentTimeMillis(), "resname", resourceType); resource.setUuid("" + new Random().nextInt()); resource.setAgent(agent); resource.setInventoryStatus(InventoryStatus.COMMITTED); - resource.setDriftConfigurations(driftConfigs); + resource.addDriftConfiguration(test1Config); + resource.addDriftConfiguration(test2Config); em.persist(resource);
} catch (Exception e) { 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 b5cfd34..403fc25 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 @@ -18,10 +18,8 @@ */ package org.rhq.enterprise.server.inventory;
-import java.util.HashSet; import java.util.List; import java.util.Random; -import java.util.Set;
import javax.persistence.EntityManager; import javax.persistence.Query; @@ -77,9 +75,7 @@ public class UninventoryTest extends AbstractEJB3Test { DriftConfiguration driftConfig = new DriftConfiguration(config); driftConfig.setBasedir(new BaseDirectory(BaseDirValueContext.fileSystem, "/boo")); driftConfig.setName("drift-config-name"); - Set<Configuration> driftConfigSet = new HashSet<Configuration>(1); - driftConfigSet.add(driftConfig.getConfiguration()); - resource.setDriftConfigurations(driftConfigSet); + resource.addDriftConfiguration(driftConfig); } };
@@ -92,7 +88,7 @@ public class UninventoryTest extends AbstractEJB3Test { Query qTemplate; Query qConfig; String qTemplateString = "select ct from ConfigurationTemplate ct where ct.id = :id"; - String qConfigString = "select c from Configuration c where c.id = :id"; + String qConfigString = "select dc from DriftConfiguration dc where dc.id = :id";
getTransactionManager().begin(); try { 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 c4268df..066bd8c 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 @@ -1,5 +1,7 @@ package org.rhq.enterprise.server.resource.metadata;
+import static java.util.Arrays.asList; + import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -23,8 +25,8 @@ import org.rhq.core.domain.bundle.ResourceTypeBundleConfiguration.BundleDestinat import org.rhq.core.domain.bundle.ResourceTypeBundleConfiguration.BundleDestinationBaseDirectory.Context; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; -import org.rhq.core.domain.content.PackageType; import org.rhq.core.domain.content.Package; +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; @@ -41,7 +43,6 @@ import org.rhq.core.domain.shared.ResourceBuilder; import org.rhq.enterprise.server.alert.AlertTemplateManagerLocal; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.bundle.BundleManagerLocal; -import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal; import org.rhq.enterprise.server.content.ContentManagerLocal; import org.rhq.enterprise.server.operation.OperationManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; @@ -49,21 +50,16 @@ import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
-import static java.util.Arrays.asList; - public class ResourceMetadataManagerBeanTest extends MetadataBeanTest {
@Test(groups = { "plugin.metadata", "NewPlugin" }) public void testRemovalOfObsoleteBundleAndDriftConfig() throws Exception { // create the initial type that has bundle and drift configs createPlugin("test-plugin.jar", "1.0", "remove_bundle_drift_config_v1.xml"); - + // make sure the drift config was persisted, and remember the type - ResourceType type1 = assertResourceTypeAssociationEquals( - "ServerWithBundleAndDriftConfig", - "TestPlugin", - "driftConfigurationTemplates", - asList("drift1")); + ResourceType type1 = assertResourceTypeAssociationEquals("ServerWithBundleAndDriftConfig", "TestPlugin", + "driftConfigurationTemplates", asList("drift1"));
// sanity check, make sure our queries work and that we did persist these things Query qTemplate; @@ -90,10 +86,10 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { // make sure the bundle config was also persisted // NOTE: WHY DOES THIS WORK? I DIDN'T ASK TO FETCH IT AND IT IS MARKED AS LAZY LOAD assertNotNull(type1.getResourceTypeBundleConfiguration()); - assertEquals("destdir1", - type1.getResourceTypeBundleConfiguration().getBundleDestinationBaseDirectories().iterator().next().getName()); + assertEquals("destdir1", type1.getResourceTypeBundleConfiguration().getBundleDestinationBaseDirectories() + .iterator().next().getName());
- // upgrade the type which removes the bundle config and drift config + // upgrade the type which removes the bundle config and drift config createPlugin("test-plugin.jar", "2.0", "remove_bundle_drift_config_v2.xml");
getTransactionManager().begin(); @@ -110,7 +106,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } }
- @Test(groups = {"plugin.metadata", "NewPlugin"}) + @Test(groups = { "plugin.metadata", "NewPlugin" }) public void registerPluginWithDuplicateDriftConfigurations() { try { createPlugin("test-plugin.jar", "1.0", "dup_drift.xml"); @@ -120,85 +116,62 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } }
- @Test(groups = {"plugin.metadata", "NewPlugin"}) + @Test(groups = { "plugin.metadata", "NewPlugin" }) public void registerPlugin() throws Exception { createPlugin("test-plugin.jar", "1.0", "plugin_v1.xml"); } - - @Test(dependsOnMethods = {"registerPlugin"}, groups = {"plugin.metadata", "NewPlugin"}) + + @Test(dependsOnMethods = { "registerPlugin" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistNewTypes() { List<String> newTypes = asList("ServerA", "ServerB"); assertTypesPersisted("Failed to persist new types", newTypes, "TestPlugin"); }
-// @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) -// public void persistSubcategories() throws Exception { -// assertResourceTypeAssociationEquals( -// "ServerA", -// "TestPlugin", -// "childSubCategories", -// asList("Resources", "Applications") -// ); -// } + // @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + // public void persistSubcategories() throws Exception { + // assertResourceTypeAssociationEquals( + // "ServerA", + // "TestPlugin", + // "childSubCategories", + // asList("Resources", "Applications") + // ); + // }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistMeasurementDefinitions() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "metricDefinitions", - asList("metric1", "metric2") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "metricDefinitions", asList("metric1", "metric2")); }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistEventDefinitions() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "eventDefinitions", - asList("logAEntry", "logBEntry") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "eventDefinitions", asList("logAEntry", + "logBEntry")); }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistOperationDefinitions() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "operationDefinitions", - asList("start", "stop") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "operationDefinitions", asList("start", "stop")); }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistProcessScans() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "processScans", - asList("serverA") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "processScans", asList("serverA")); }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistDriftConfigurationTemplates() throws Exception { - ResourceType type = assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "driftConfigurationTemplates", - asList("drift-pc", "drift-fs") - ); + ResourceType type = assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "driftConfigurationTemplates", + asList("drift-pc", "drift-fs"));
DriftConfiguration driftConfig = null; Set<ConfigurationTemplate> drifts = type.getDriftConfigurationTemplates(); for (ConfigurationTemplate drift : drifts) { if (drift.getName().equals("drift-pc")) { driftConfig = new DriftConfiguration(drift.getConfiguration()); - assertFalse(driftConfig.getEnabled()); + assertFalse(driftConfig.isEnabled()); assertEquals(BaseDirValueContext.pluginConfiguration, driftConfig.getBasedir().getValueContext()); assertEquals("connectionPropertyX", driftConfig.getBasedir().getValueName()); - assertEquals(Long.valueOf(123456L), driftConfig.getInterval()); + assertEquals(123456L, driftConfig.getInterval()); assertEquals(1, driftConfig.getIncludes().size()); assertEquals(2, driftConfig.getExcludes().size()); Filter filter = driftConfig.getIncludes().get(0); @@ -212,10 +185,10 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { assertEquals("", filter.getPattern()); } else if (drift.getName().equals("drift-fs")) { driftConfig = new DriftConfiguration(drift.getConfiguration()); - assertFalse(driftConfig.getEnabled()); + assertFalse(driftConfig.isEnabled()); assertEquals(BaseDirValueContext.fileSystem, driftConfig.getBasedir().getValueContext()); assertEquals("/", driftConfig.getBasedir().getValueName()); - assertEquals(Long.valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL), driftConfig.getInterval()); + assertEquals(DriftConfigurationDefinition.DEFAULT_INTERVAL, driftConfig.getInterval()); assertEquals(0, driftConfig.getIncludes().size()); assertEquals(0, driftConfig.getExcludes().size()); } else { @@ -224,9 +197,9 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistBundleTargetConfigurations() throws Exception { - String resourceTypeName="ServerA"; + String resourceTypeName = "ServerA"; String plugin = "TestPlugin";
SubjectManagerLocal subjectMgr = LookupUtil.getSubjectManager(); @@ -239,7 +212,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { List<ResourceType> resourceTypes = resourceTypeMgr.findResourceTypesByCriteria(subjectMgr.getOverlord(), criteria); ResourceType resourceType = resourceTypes.get(0); - + ResourceTypeBundleConfiguration rtbc = resourceType.getResourceTypeBundleConfiguration(); assertNotNull("missing bundle configuration", rtbc); Set<BundleDestinationBaseDirectory> dirs = rtbc.getBundleDestinationBaseDirectories(); @@ -252,121 +225,83 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } else if (dir.getName().equals("bundleTarget-fs")) { assertEquals(Context.fileSystem, dir.getValueContext()); assertEquals("/wot/gorilla", dir.getValueName()); - assertNull(dir.getDescription()); + assertNull(dir.getDescription()); } else { fail("got an unexpected bundle target dest dir: " + dir); } } } - - @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistChildTypes() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "childResourceTypes", - asList("Child1", "Child2") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "childResourceTypes", asList("Child1", "Child2")); }
- - @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistPluginConfigurationDefinition() throws Exception { assertAssociationExists("ServerA", "pluginConfigurationDefinition"); }
- @Test(dependsOnMethods = {"persistNewTypes"}, groups = {"plugin.metadata", "NewPlugin"}) + @Test(dependsOnMethods = { "persistNewTypes" }, groups = { "plugin.metadata", "NewPlugin" }) public void persistPackageTypes() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "packageTypes", - asList("ServerA.Content.1", "ServerA.Content.2") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "packageTypes", asList("ServerA.Content.1", + "ServerA.Content.2")); }
- @Test(groups = {"plugin.metadata", "UpgradePlugin"}, dependsOnGroups = {"NewPlugin"}) + @Test(groups = { "plugin.metadata", "UpgradePlugin" }, dependsOnGroups = { "NewPlugin" }) public void upgradePlugin() throws Exception { createPlugin("test-plugin.jar", "2.0", "plugin_v2.xml"); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeOperationDefinitions() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "operationDefinitions", - asList("start", "shutdown", "restart") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "operationDefinitions", asList("start", + "shutdown", "restart")); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeChildResources() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "childResourceTypes", - asList("Child1", "Child3") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "childResourceTypes", asList("Child1", "Child3")); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeParentTypeOfChild() throws Exception { - assertResourceTypeAssociationEquals( - "ServerB", - "TestPlugin", - "childResourceTypes", - asList("Child2") - ); + assertResourceTypeAssociationEquals("ServerB", "TestPlugin", "childResourceTypes", asList("Child2")); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeEventDefinitions() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "eventDefinitions", - asList("logAEntry", "logCEntry") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "eventDefinitions", asList("logAEntry", + "logCEntry")); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeProcessScans() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "processScans", - asList("processA", "processB") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "processScans", asList("processA", "processB")); }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeDriftConfigurationTemplates() throws Exception { - ResourceType type = assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "driftConfigurationTemplates", - asList("drift-rc", "drift-mt") - ); - + ResourceType type = assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "driftConfigurationTemplates", + asList("drift-rc", "drift-mt"));
DriftConfiguration driftConfig = null; Set<ConfigurationTemplate> drifts = type.getDriftConfigurationTemplates(); for (ConfigurationTemplate drift : drifts) { if (drift.getName().equals("drift-rc")) { driftConfig = new DriftConfiguration(drift.getConfiguration()); - assertFalse(driftConfig.getEnabled()); + assertFalse(driftConfig.isEnabled()); assertEquals(BaseDirValueContext.resourceConfiguration, driftConfig.getBasedir().getValueContext()); assertEquals("resourceConfig1", driftConfig.getBasedir().getValueName()); - assertEquals(Long.valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL), driftConfig.getInterval()); + assertEquals(DriftConfigurationDefinition.DEFAULT_INTERVAL, driftConfig.getInterval()); assertEquals(0, driftConfig.getIncludes().size()); assertEquals(0, driftConfig.getExcludes().size()); } else if (drift.getName().equals("drift-mt")) { driftConfig = new DriftConfiguration(drift.getConfiguration()); - assertFalse(driftConfig.getEnabled()); + assertFalse(driftConfig.isEnabled()); assertEquals(BaseDirValueContext.measurementTrait, driftConfig.getBasedir().getValueContext()); assertEquals("trait1", driftConfig.getBasedir().getValueName()); - assertEquals(Long.valueOf(DriftConfigurationDefinition.DEFAULT_INTERVAL), driftConfig.getInterval()); + assertEquals(DriftConfigurationDefinition.DEFAULT_INTERVAL, driftConfig.getInterval()); assertEquals(0, driftConfig.getIncludes().size()); assertEquals(0, driftConfig.getExcludes().size()); } else { @@ -375,9 +310,9 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradeBundleTargetConfigurations() throws Exception { - String resourceTypeName="ServerA"; + String resourceTypeName = "ServerA"; String plugin = "TestPlugin";
SubjectManagerLocal subjectMgr = LookupUtil.getSubjectManager(); @@ -390,7 +325,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { List<ResourceType> resourceTypes = resourceTypeMgr.findResourceTypesByCriteria(subjectMgr.getOverlord(), criteria); ResourceType resourceType = resourceTypes.get(0); - + ResourceTypeBundleConfiguration rtbc = resourceType.getResourceTypeBundleConfiguration(); assertNotNull("missing bundle configuration", rtbc); Set<BundleDestinationBaseDirectory> dirs = rtbc.getBundleDestinationBaseDirectories(); @@ -410,17 +345,13 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { } }
- @Test(dependsOnMethods = {"upgradePlugin"}, groups = {"plugin.metadata", "UpgradePlugin"}) + @Test(dependsOnMethods = { "upgradePlugin" }, groups = { "plugin.metadata", "UpgradePlugin" }) public void upgradePackageTypes() throws Exception { - assertResourceTypeAssociationEquals( - "ServerA", - "TestPlugin", - "packageTypes", - asList("ServerA.Content.1", "ServerA.Content.3") - ); + assertResourceTypeAssociationEquals("ServerA", "TestPlugin", "packageTypes", asList("ServerA.Content.1", + "ServerA.Content.3")); }
- @Test(groups = {"RemoveTypes"}, dependsOnGroups = {"UpgradePlugin"}) + @Test(groups = { "RemoveTypes" }, dependsOnGroups = { "UpgradePlugin" }) public void upgradePluginWithTypesRemoved() throws Exception { createPlugin("remove-types-plugin", "1.0", "remove_types_v1.xml");
@@ -433,7 +364,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { createPlugin("remove-types-plugin", "2.0", "remove_types_v2.xml"); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteOperationDefsForRemovedType() throws Exception { OperationManagerLocal operationMgr = LookupUtil.getOperationManager(); SubjectManagerLocal subjectMgr = LookupUtil.getSubjectManager(); @@ -442,31 +373,29 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { criteria.addFilterResourceTypeName("ServerC"); criteria.addFilterName("run");
- List<OperationDefinition> operationDefs = operationMgr.findOperationDefinitionsByCriteria( - subjectMgr.getOverlord(), criteria); + List<OperationDefinition> operationDefs = operationMgr.findOperationDefinitionsByCriteria(subjectMgr + .getOverlord(), criteria);
assertEquals("The operation definition should have been deleted", 0, operationDefs.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteEventDefsForRemovedType() throws Exception { - List results = getEntityManager().createQuery( - "from EventDefinition e where e.name = :ename and e.resourceType.name = :rname") - .setParameter("ename", "serverCEvent") - .setParameter("rname", "ServerC") - .getResultList(); + List<?> results = getEntityManager().createQuery( + "from EventDefinition e where e.name = :ename and e.resourceType.name = :rname").setParameter("ename", + "serverCEvent").setParameter("rname", "ServerC").getResultList();
assertEquals("The event definition(s) should have been deleted", 0, results.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteParent() throws Exception { SubjectManagerLocal subjectMgr = LookupUtil.getSubjectManager(); ResourceTypeManagerLocal resourceTypeMgr = LookupUtil.getResourceTypeManager();
ResourceTypeCriteria criteria = new ResourceTypeCriteria(); criteria.addFilterName("ServerD.GrandChild1"); - criteria.addFilterPluginName ("RemoveTypesPlugin"); + criteria.addFilterPluginName("RemoveTypesPlugin"); criteria.fetchParentResourceTypes(true);
List<ResourceType> types = resourceTypeMgr.findResourceTypesByCriteria(subjectMgr.getOverlord(), criteria); @@ -481,7 +410,7 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest {
assertNotNull("Expected to find 'ServerD' as the parent, but found, " + type.getParentResourceTypes(), parentType); - } + }
private ResourceType findByName(Collection<ResourceType> types, String name) { for (ResourceType type : types) { @@ -492,40 +421,35 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { return null; }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteTypeAndAllItsDescedantTypes() throws Exception { - List typesNotRemoved = getEntityManager().createQuery( - "from ResourceType t where t.plugin = :plugin and t.name in (:resourceTypes)") - .setParameter("plugin", "RemoveTypesPlugin") - .setParameter("resourceTypes", asList("ServerE", "ServerE1", "ServerE2", "ServerE3", "ServerE4")) - .getResultList(); + List<?> typesNotRemoved = getEntityManager().createQuery( + "from ResourceType t where t.plugin = :plugin and t.name in (:resourceTypes)").setParameter("plugin", + "RemoveTypesPlugin").setParameter("resourceTypes", + asList("ServerE", "ServerE1", "ServerE2", "ServerE3", "ServerE4")).getResultList();
assertEquals("Failed to delete resource type or one or more of its descendant types", 0, typesNotRemoved.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteProcessScans() { - List processScans = getEntityManager().createQuery( - "from ProcessScan p where p.name = :name1 or p.name = :name2") - .setParameter("name1", "scan1") - .setParameter("name2", "scan2") - .getResultList(); + List<?> processScans = getEntityManager().createQuery( + "from ProcessScan p where p.name = :name1 or p.name = :name2").setParameter("name1", "scan1").setParameter( + "name2", "scan2").getResultList();
assertEquals("The process scans should have been deleted", 0, processScans.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteSubcategories() { - List subcategories = getEntityManager().createQuery( - "from ResourceSubCategory r where r.name = :name1 or r.name = :name2 or r.name = :name3") - .setParameter("name1", "ServerC.Category1") - .setParameter("name2", "ServerC.Category2") - .setParameter("name3", "ServerC.NestedCategory1") - .getResultList(); + List<?> subcategories = getEntityManager().createQuery( + "from ResourceSubCategory r where r.name = :name1 or r.name = :name2 or r.name = :name3").setParameter( + "name1", "ServerC.Category1").setParameter("name2", "ServerC.Category2").setParameter("name3", + "ServerC.NestedCategory1").getResultList(); assertEquals("The subcategories should have been deleted", 0, subcategories.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteResources() { ResourceManagerLocal resourceMgr = LookupUtil.getResourceManager(); SubjectManagerLocal subjectMgr = LookupUtil.getSubjectManager(); @@ -536,10 +460,8 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest {
List<Resource> resources = resourceMgr.findResourcesByCriteria(subjectMgr.getOverlord(), criteria);
- assertTrue( - "Did not expect to find any more that three resources. Database might need to be reset", - resources.size() < 4 - ); + assertTrue("Did not expect to find any more that three resources. Database might need to be reset", resources + .size() < 4);
// We won't do anything more rigorous that making sure the resources were marked uninventoried. // Resource deletion is an expensive, time-consuming process; consequently, it is carried out @@ -547,76 +469,65 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { // quickly as it is basically just updates the the inventory status to UNINVENTORIED for the // resources to be deleted. for (Resource resource : resources) { - assertEquals( - "The resource should have been marked for deletion", - InventoryStatus.UNINVENTORIED == resource.getInventoryStatus() - ); + assertEquals("The resource should have been marked for deletion", InventoryStatus.UNINVENTORIED == resource + .getInventoryStatus()); } }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteBundles() { - List bundles = getEntityManager().createQuery("from Bundle b where b.bundleType.name = :name") - .setParameter("name", "Test Bundle") - .getResultList(); + List<?> bundles = getEntityManager().createQuery("from Bundle b where b.bundleType.name = :name").setParameter( + "name", "Test Bundle").getResultList();
assertEquals("Failed to delete the bundles", 0, bundles.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteBundleTypes() { - List bundleTypes = getEntityManager().createQuery("from BundleType b where b.name = :name") - .setParameter("name", "Test Bundle") - .getResultList(); + List<?> bundleTypes = getEntityManager().createQuery("from BundleType b where b.name = :name").setParameter( + "name", "Test Bundle").getResultList();
assertEquals("The bundle type should have been deleted", 0, bundleTypes.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deletePackages() { - List packages = getEntityManager().createQuery("from Package p where p.name = :name") - .setParameter("name", "ServerC::test-package") - .getResultList(); + List<?> packages = getEntityManager().createQuery("from Package p where p.name = :name").setParameter("name", + "ServerC::test-package").getResultList();
assertEquals("All packages should have been deleted", 0, packages.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deletePackageTypes() { - List packageTypes = getEntityManager().createQuery("from PackageType p where p.name = :name") - .setParameter("name", "ServerC.Content") - .getResultList(); + List<?> packageTypes = getEntityManager().createQuery("from PackageType p where p.name = :name").setParameter( + "name", "ServerC.Content").getResultList();
assertEquals("All package types should have been deleted", 0, packageTypes.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteResourceGroups() { - List groups = getEntityManager().createQuery( - "from ResourceGroup g where g.name = :name and g.resourceType.name = :typeName") - .setParameter("name", "ServerC Group") - .setParameter("typeName", "ServerC") - .getResultList(); + List<?> groups = getEntityManager().createQuery( + "from ResourceGroup g where g.name = :name and g.resourceType.name = :typeName").setParameter("name", + "ServerC Group").setParameter("typeName", "ServerC").getResultList();
assertEquals("All resource groups should have been deleted", 0, groups.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteAlertTemplates() { - List templates = getEntityManager().createQuery( - "from AlertDefinition a where a.name = :name and a.resourceType.name = :typeName") - .setParameter("name", "ServerC Alert Template") - .setParameter("typeName", "ServerC") - .getResultList(); + List<?> templates = getEntityManager().createQuery( + "from AlertDefinition a where a.name = :name and a.resourceType.name = :typeName").setParameter("name", + "ServerC Alert Template").setParameter("typeName", "ServerC").getResultList();
assertEquals("Alert templates should have been deleted.", 0, templates.size()); }
- @Test(dependsOnMethods = {"upgradePluginWithTypesRemoved"}, groups = {"plugin.metadata", "RemoveTypes"}) + @Test(dependsOnMethods = { "upgradePluginWithTypesRemoved" }, groups = { "plugin.metadata", "RemoveTypes" }) public void deleteMeasurementDefinitions() { - List measurementDefs = getEntityManager().createQuery("from MeasurementDefinition m where m.name = :name") - .setParameter("name", "ServerC::metric1") - .getResultList(); + List<?> measurementDefs = getEntityManager().createQuery("from MeasurementDefinition m where m.name = :name") + .setParameter("name", "ServerC::metric1").getResultList();
assertEquals("Measurement definitions should have been deleted", 0, measurementDefs.size()); } @@ -658,18 +569,14 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { ResourceTypeManagerLocal resourceTypeMgr = LookupUtil.getResourceTypeManager(); ResourceType resourceType = resourceTypeMgr.getResourceTypeByNameAndPlugin(resourceTypeName, pluginName);
- assertNotNull("Cannot create resources. Unable to find resource type for [name: " + resourceTypeName + - ", plugin: " + pluginName + "]", resourceType); + assertNotNull("Cannot create resources. Unable to find resource type for [name: " + resourceTypeName + + ", plugin: " + pluginName + "]", resourceType);
List<Resource> resources = new ArrayList<Resource>(); for (int i = 0; i < count; ++i) { - resources.add(new ResourceBuilder() - .createServer() - .withResourceType(resourceType) - .withName(resourceType.getName() + "--" + i) - .withUuid(resourceType.getName()) - .withRandomResourceKey(resourceType.getName() + "--" + i) - .build()); + resources.add(new ResourceBuilder().createServer().withResourceType(resourceType).withName( + resourceType.getName() + "--" + i).withUuid(resourceType.getName()).withRandomResourceKey( + resourceType.getName() + "--" + i).build()); }
getTransactionManager().begin(); @@ -686,8 +593,8 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { ResourceTypeManagerLocal resourceTypeMgr = LookupUtil.getResourceTypeManager(); ResourceType resourceType = resourceTypeMgr.getResourceTypeByNameAndPlugin(resourceTypeName, pluginName);
- assertNotNull("Cannot create bundle. Unable to find resource type for [name: " + resourceTypeName + - ", plugin: " + pluginName + "]", resourceType); + assertNotNull("Cannot create bundle. Unable to find resource type for [name: " + resourceTypeName + + ", plugin: " + pluginName + "]", resourceType);
BundleType bundleType = bundleMgr.getBundleType(subjectMgr.getOverlord(), bundleTypeName); assertNotNull("Cannot create bundle. Unable to find bundle type for [name: " + bundleTypeName + "]", bundleType); @@ -715,8 +622,8 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest {
ResourceType resourceType = resourceTypeMgr.getResourceTypeByNameAndPlugin(resourceTypeName, pluginName);
- assertNotNull("Cannot create resource group. Unable to find resource type for [name: " + resourceTypeName + - ", plugin: " + pluginName + "]", resourceType); + assertNotNull("Cannot create resource group. Unable to find resource type for [name: " + resourceTypeName + + ", plugin: " + pluginName + "]", resourceType);
ResourceGroup resourceGroup = new ResourceGroup(groupName, resourceType); resourceGroupMgr.createResourceGroup(subjectMgr.getOverlord(), resourceGroup); @@ -728,8 +635,8 @@ public class ResourceMetadataManagerBeanTest extends MetadataBeanTest { AlertTemplateManagerLocal alertTemplateMgr = LookupUtil.getAlertTemplateManager();
ResourceType resourceType = resourceTypeMgr.getResourceTypeByNameAndPlugin(resourceTypeName, pluginName); - assertNotNull("Cannot create alert template. Unable to find resource type for [name: " + resourceTypeName + - ", plugin: " + pluginName + "]", resourceType); + assertNotNull("Cannot create alert template. Unable to find resource type for [name: " + resourceTypeName + + ", plugin: " + pluginName + "]", resourceType);
AlertDefinition alertDef = new AlertDefinition(); alertDef.setName(name); diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/resource/metadata/MetadataTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/resource/metadata/MetadataTest.xml index fa25510..e0dc90a 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/resource/metadata/MetadataTest.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/resource/metadata/MetadataTest.xml @@ -319,7 +319,7 @@ <rhq_create_res_hist/> <rhq_delete_res_hist/> <rhq_drift_template_map/> - <rhq_drift_config_map/> + <rhq_drift_config/> <rhq_drift_change_set/> <jms_messages/> <jms_transactions/>
commit 066d4f19152e624aa589257908526e58620182a2 Author: John Mazzitelli mazz@redhat.com Date: Mon Aug 8 16:46:05 2011 -0400
[BZ 718315] support properties name/value pairs with spaces around the equals sign
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..60ae7cb 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 @@ -1,25 +1,25 @@ - /* - * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ package org.rhq.core.util;
import java.io.BufferedReader; @@ -133,6 +133,7 @@ public class PropertiesFileUpdate { out.println(line); } else { String existingKey = line.substring(0, equalsSign); + existingKey = trimString(existingKey, false, true); if (!propsToUpdate.containsKey(existingKey)) { out.println(line); // property that is not being updated; leave it alone and write it out as-is } else { @@ -180,4 +181,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; + } } \ No newline at end of file diff --git a/modules/core/util/src/test/java/org/rhq/core/util/PropertiesFileUpdateTest.java b/modules/core/util/src/test/java/org/rhq/core/util/PropertiesFileUpdateTest.java index 11b8572..7512e86 100644 --- a/modules/core/util/src/test/java/org/rhq/core/util/PropertiesFileUpdateTest.java +++ b/modules/core/util/src/test/java/org/rhq/core/util/PropertiesFileUpdateTest.java @@ -1,37 +1,42 @@ - /* - * RHQ Management Platform - * Copyright (C) 2005-2008 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ +/* + * RHQ Management Platform + * Copyright (C) 2005-2008 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ package org.rhq.core.util;
+import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.Properties; + import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
+import org.rhq.core.util.stream.StreamUtil; + @Test public class PropertiesFileUpdateTest { private File existingPropertiesFile; @@ -41,13 +46,13 @@ public class PropertiesFileUpdateTest { existingPropertiesFile = File.createTempFile("properties-file-update-test", ".properties"); PrintStream ps = new PrintStream(new FileOutputStream(existingPropertiesFile), true, "8859_1"); ps.println("# first comment"); - ps.println("one=1"); + ps.println("one=1"); // no spaces around the equals ps.println(); ps.println("# second comment"); - ps.println("two=12"); + ps.println("two = 12"); // a single space on either side of the equals ps.println(); ps.println("# third comment"); - ps.println("three=123"); + ps.println("three = 123"); // multiple spaces around the equals ps.flush(); ps.close(); } @@ -59,6 +64,65 @@ public class PropertiesFileUpdateTest { } }
+ public void testSpacesAroundEquals() throws Exception { + Properties props = loadPropertiesFile(); + + // sanity check - validate our original test properties file is as we expect + assert props.getProperty("one").equals("1"); + assert props.getProperty("two").equals("12"); + assert props.getProperty("three").equals("123"); + assert props.size() == 3; + + PropertiesFileUpdate update = new PropertiesFileUpdate(existingPropertiesFile.getAbsolutePath()); + + // we want to change the values, but reuse the lines that originally set them + Properties newProps = new Properties(); + newProps.setProperty("one", "new1"); + newProps.setProperty("two", "new2"); + newProps.setProperty("three", "new3"); + + update.update(newProps); + props = loadPropertiesFile(); + assert props.getProperty("one").equals("new1"); + assert props.getProperty("two").equals("new2"); + assert props.getProperty("three").equals("new3"); + assert props.size() == 3; + + // now make sure we didn't add extra lines, we should have reused the original lines in the file + // we should only ever have a single instance of one=, two=, three= lines. + int oneCount = 0; + int twoCount = 0; + int threeCount = 0; + BufferedReader reader = new BufferedReader(new FileReader(existingPropertiesFile)); + try { + while (true) { + String line = reader.readLine(); + if (line == null) { + break; + } + if (line.startsWith("one")) { + oneCount++; + } + if (line.startsWith("two")) { + twoCount++; + } + if (line.startsWith("three")) { + threeCount++; + } + } + } finally { + reader.close(); + } + + assert oneCount == 1 : "we added extraneous one= properties:\n" + slurpPropertiesFile(); + assert twoCount == 1 : "we added extraneous two= properties:\n" + slurpPropertiesFile(); + assert threeCount == 1 : "we added extraneous three= properties:\n" + slurpPropertiesFile(); + } + + private String slurpPropertiesFile() throws Exception { + return new String(StreamUtil.slurp(new FileInputStream(existingPropertiesFile))); // slurp will close our stream for us + } + public void testEmptyValue() throws Exception { Properties props = loadPropertiesFile();
commit e4e3383f5eefa0fc134bd6cf3dcfdb5b14aca417 Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 16:08:12 2011 -0400
Changing logic and semantics around 'detect drift now'
When DriftAgentService.detectDrift is invoked, the corresponding schedule has its next scan time reset which effectively moves it to the front of the queue to be processed.
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 6137400..c8bcdb6 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 @@ -35,16 +35,33 @@ import org.rhq.core.domain.drift.DriftFile; public interface DriftAgentService {
/** - * Ask the agent to send down the requested drift file content as a zip of all requested files. + * Ask the agent to send the requested drift file content as a zip of all requested files. * * @param driftFiles + * @param headers Used to identify the change set to which the requested files belong * @return the results of the immediate scheduling */ boolean requestDriftFiles(int resourceId, Headers headers, List<? extends DriftFile> driftFiles);
/** - * Execute drift detection immediately. If any drift is found, the agent will send the - * change set back to the server in a separate request from agent to server. + * Schedule drift detection to occur immediately. If any changes are foind, the agent + * will report thenm back to the server in a separate request from agent to server. + * This method returns quickly and can be considered a non-blocking operation since + * the drift detection happens asynchronously. + * <p/> + * 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 + * 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 + * factors. First there could be other schedules already at the front of the queue that + * would first be processed if their next scan times have also been reset. Secondly, + * drift detection occurs at regularly scheduled intervals in its own thread. If this + * method is called immediately after drift detection has just started, the earliest + * that the detection would occur is the time it takes for the current detection to + * 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 @@ -57,8 +74,9 @@ public interface DriftAgentService { * specified drift configuration. The interval at which the drift detection occurs is * specified by the drift configuration. * <p/> - * Note that this method only schedules the drift detection and that it may return - * before drift detection actually starts executing. + * 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 + * 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 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 147fa86..65e4b72 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 @@ -36,6 +36,10 @@ public class DriftDetectionSchedule implements Comparable<DriftDetectionSchedule nextScan = System.currentTimeMillis() + (driftConfig.getInterval() * 1000); }
+ public void resetSchedule() { + nextScan = -1; + } + public DriftDetectionSchedule copy() { DriftDetectionSchedule copy = new DriftDetectionSchedule(resourceId, new DriftConfiguration(driftConfig.getConfiguration().deepCopyWithoutProxies())); @@ -78,4 +82,10 @@ public class DriftDetectionSchedule implements Comparable<DriftDetectionSchedule public int hashCode() { return Long.valueOf(nextScan).hashCode(); } + + @Override + public String toString() { + return getClass().getSimpleName() + "[resourceId: " + resourceId + ", driftConfigurationId: " + + driftConfig.getId() + ", driftConfigurationName: " + driftConfig.getName() + "]"; + } } 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 4f36939..d97ad3b 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 @@ -180,50 +180,22 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri
@Override public void detectDrift(int resourceId, DriftConfiguration driftConfiguration) { - ScheduleQueue queue = new ScheduleQueue() { - DriftDetectionSchedule schedule; - - @Override - public DriftDetectionSchedule getNextSchedule() { - DriftDetectionSchedule removedSchedule = schedule; - schedule = null; - return removedSchedule; - } - - @Override - public boolean addSchedule(DriftDetectionSchedule schedule) { - this.schedule = schedule; - return true; - } - - @Override - public void clear() { - schedule = null; - } - - @Override - public void deactivateSchedule() { - schedule = null; - } - - @Override - public DriftDetectionSchedule update(int resourceId, DriftConfiguration config) { - return schedule; - } - - @Override - public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) { - return null; - } - }; - queue.addSchedule(new DriftDetectionSchedule(resourceId, driftConfiguration)); - - DriftDetector driftDetector = new DriftDetector(); - driftDetector.setChangeSetManager(changeSetMgr); - driftDetector.setScheduleQueue(queue); - driftDetector.setDriftClient(this); + if (log.isDebugEnabled()) { + log.debug("Received request to schedule drift detection immediately for [resourceId: " + resourceId + + ", driftConfigurationId: " + driftConfiguration.getId() + ", driftConfigurationName: " + + driftConfiguration.getName() + "]"); + }
- driftThreadPool.execute(driftDetector); + DriftDetectionSchedule schedule = schedulesQueue.remove(resourceId, driftConfiguration); + 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."); + return; + } + log.debug("Resetting " + schedule + " for immediate detection."); + schedule.resetSchedule(); + schedulesQueue.addSchedule(schedule); }
@Override 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 b4a2f00..497e067 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 @@ -1,5 +1,6 @@ package org.rhq.core.pc.drift;
+import java.util.Iterator; import java.util.PriorityQueue; import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -29,8 +30,13 @@ public class ScheduleQueueImpl implements ScheduleQueue { }
private boolean isActiveSchedule(int resourceId, DriftConfiguration config) { - return activeSchedule != null && activeSchedule.getResourceId() == resourceId && - activeSchedule.getDriftConfiguration().getName().equals(config.getName()); + try { + lock.readLock().lock(); + return activeSchedule != null && activeSchedule.getResourceId() == resourceId && + activeSchedule.getDriftConfiguration().getName().equals(config.getName()); + } finally { + lock.readLock().unlock(); + }
}
@@ -63,74 +69,44 @@ public class ScheduleQueueImpl implements ScheduleQueue {
@Override public DriftDetectionSchedule remove(int resourceId, DriftConfiguration config) { - DriftDetectionSchedule scheduleToRemove = null; try { - lock.readLock().lock(); + lock.writeLock().lock(); if (isActiveSchedule(resourceId, config)) { - // The schedule to be removed is the currently active schedule so "upgrade" - // to the write lock and return the schedule while removing it from the queue - // at the same time. - try { - lock.writeLock().lock(); - DriftDetectionSchedule removedSchedule = activeSchedule; - activeSchedule = null; - return removedSchedule; - } finally { - lock.writeLock().unlock(); - } + DriftDetectionSchedule removedSchedule = activeSchedule; + activeSchedule = null; + return removedSchedule; }
- for (DriftDetectionSchedule s : queue) { - if (s.getResourceId() == resourceId && - s.getDriftConfiguration().getName().equals(config.getName())) { - scheduleToRemove = s; - break; + Iterator<DriftDetectionSchedule> iterator = queue.iterator(); + while (iterator.hasNext()) { + DriftDetectionSchedule schedule = iterator.next(); + if (schedule.getResourceId() == resourceId && + schedule.getDriftConfiguration().getName().equals(config.getName())) { + iterator.remove(); + return schedule; } }
- // The schedule was not found in the queue so we can simply return null without - // any additional processing. - if (scheduleToRemove == null) { - return null; - } - - boolean removed = false; - // At this point, we found the target schedule in the queue. We "upgrade" to - // the write lock and remove it from the queue. If the schedule was successfully - // removed we return it; otherwise, return null. - try { - lock.writeLock().lock(); - removed = queue.remove(scheduleToRemove); - } finally { - lock.writeLock().unlock(); - } - - return removed ? scheduleToRemove : null; + return null; } finally { - lock.readLock().unlock(); + lock.writeLock().unlock(); } }
@Override public DriftDetectionSchedule update(int resourceId, DriftConfiguration config) { - try { - lock.writeLock().lock(); - if (isActiveSchedule(resourceId, config)) { - update(activeSchedule, config); - return activeSchedule.copy(); - } - - DriftDetectionSchedule schedule = remove(resourceId, config); - if (schedule == null) { - return null; - } + DriftDetectionSchedule schedule = remove(resourceId, config); + if (schedule == null) { + return null; + }
- update(schedule, config); + update(schedule, config);
+ try { + lock.writeLock().lock(); if (queue.offer(schedule)) { - return schedule.copy(); + return schedule.copy(); } - return null; } finally { lock.writeLock().unlock(); 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 1b44518..421798e 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 @@ -252,6 +252,32 @@ public class DriftDetectorTest extends DriftTest {
@SuppressWarnings("unchecked") @Test + public void includeFiledAddedInNewDirectoryInDriftChangeSet() throws Exception { + DriftConfiguration config = driftConfiguration("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)); + writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); + writer.close(); + + // create some drift + File subconfDir = mkdir(confDir, "subconf"); + File server2Conf = createRandomFile(subconfDir, "server-2.conf"); + + scheduleQueue.addSchedule(new DriftDetectionSchedule(resourceId(), config)); + detector.run(); + + File driftChangeSet = changeSet(config.getName(), DRIFT); + assertTrue(driftChangeSet.exists(), "Expected to find drift change set " + driftChangeSet.getPath()); + + assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("subconf") + .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); + } + + @SuppressWarnings("unchecked") + @Test public void includeRemovedFileInDriftChangeSet() throws Exception { DriftConfiguration config = driftConfiguration("file-removed-drift-test", resourceDir.getAbsolutePath());
@@ -291,6 +317,32 @@ public class DriftDetectorTest extends DriftTest { .add(addedFileEntry("server-1.conf", sha256(server1Conf)))); }
+ @SuppressWarnings("unchecked") + @Test + public void includeFilesInRemovedDirectoryInDriftChangeSet() throws Exception { + DriftConfiguration config = driftConfiguration("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)); + writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", server1Hash))); + writer.close(); + + // create some drift + server1Conf.delete(); + confDir.delete(); + + File driftChangeSet = changeSet(config.getName(), DRIFT); + + // verify that the drift change set was generated + assertTrue(driftChangeSet.exists(), "Expected to find drift change set " + driftChangeSet.getPath()); + + assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") + .add(removedFileEntry("server-1.conf", server1Hash))); + } + void assertHeaderEquals(File changeSet, Headers expected) throws Exception { ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new FileReader(changeSet))); Headers actual = reader.getHeaders();
commit b6ef0f1f21f3d32772c54e14f646246ee776916e Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 12:30:01 2011 -0400
Don't use the interval as an initial delay for drift schedules
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 ab5bac3..147fa86 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 @@ -17,7 +17,7 @@ public class DriftDetectionSchedule implements Comparable<DriftDetectionSchedule public DriftDetectionSchedule(int resourceId, DriftConfiguration configuration) { this.resourceId = resourceId; driftConfig = configuration; - nextScan = System.currentTimeMillis(); + nextScan = -1; }
public int getResourceId() {
commit b9b5fa71f6a4044705b577d0be2f49bf816680ff Author: John Sanda jsanda@redhat.com Date: Mon Aug 8 11:28:24 2011 -0400
Updating change set parser to handle files with spaces in their names
The format of the file entry has been altered to make parsing simpler and more robust. A file entry has the following fields in the order specified:
* drift category code * new sha 256 * old sha 256 * path
There are now five headers included in each change set file and they are:
* resource id * drift configuration id * drift configuration name * base directory * change set category code
diff --git a/modules/common/drift/pom.xml b/modules/common/drift/pom.xml index 35bf0da..d7404e0 100644 --- a/modules/common/drift/pom.xml +++ b/modules/common/drift/pom.xml @@ -27,6 +27,12 @@
<dependencies> <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>test-utils</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.4</version> diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java index a39867a..68b7163 100644 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReader.java @@ -1,13 +1,30 @@ -package org.rhq.common.drift; +/* + * 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. + */
-import java.io.IOException; +package org.rhq.common.drift;
public interface ChangeSetReader extends Iterable<DirectoryEntry> {
- Headers getHeaders() throws IOException; + Headers getHeaders() throws ChangeSetReaderException;
- DirectoryEntry readDirectoryEntry() throws IOException; + DirectoryEntry readDirectoryEntry() throws ChangeSetReaderException;
- void close() throws IOException; + void close() throws ChangeSetReaderException;
} diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderException.java b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderException.java new file mode 100644 index 0000000..efdc6e0 --- /dev/null +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetReaderException.java @@ -0,0 +1,46 @@ +/* + * 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.common.drift; + +import java.io.IOException; + +/** + * An exception thrown by {@link ChangeSetReader} when an error occurs while parsing a + * change set file. + */ +public class ChangeSetReaderException extends IOException { + + public ChangeSetReaderException() { + super(); + } + + public ChangeSetReaderException(String message) { + super(message); + } + + public ChangeSetReaderException(String message, Throwable cause) { + super(message, cause); + } + + public ChangeSetReaderException(Throwable cause) { + super(cause); + } + +} 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 0d1e07e..417f512 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 @@ -1,6 +1,23 @@ -package org.rhq.common.drift; +/* + * 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. + */
-import static java.lang.Integer.parseInt; +package org.rhq.common.drift;
import java.io.BufferedReader; import java.io.File; @@ -8,26 +25,49 @@ import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern;
+import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
+import static java.lang.Integer.parseInt; +import static org.rhq.common.drift.FileEntry.addedFileEntry; +import static org.rhq.common.drift.FileEntry.changedFileEntry; +import static org.rhq.common.drift.FileEntry.removedFileEntry; + +/** + * Note that this implementation does not do any validation for the most part. It assumes + * that entries in the change set file contain valid, 64 character SHA-256 hashes. It + * assumes that all headers are present in the file and in the correct order. It assume + * that all paths are non-null. + * <p/> + * The one thing that the read does check is the drift category code for each file entry. + * If the code is not valid, an error message is logged and a {@link ChangeSetReaderException} + * is thrown. + */ public class ChangeSetReaderImpl implements ChangeSetReader {
- private Pattern DIRECTORY_PATTERN = Pattern.compile("^\s*(.*?)\s+(\d+)\s*$"); + private Log log = LogFactory.getLog(ChangeSetReaderImpl.class); + private BufferedReader reader;
private File metaDataFile;
private Headers headers;
- public ChangeSetReaderImpl(File metaDataFile) throws IOException { - this.metaDataFile = metaDataFile; - reader = new BufferedReader(new FileReader(this.metaDataFile)); - readHeaders(); + public ChangeSetReaderImpl(File metaDataFile) throws ChangeSetReaderException { + try { + this.metaDataFile = metaDataFile; + reader = new BufferedReader(new FileReader(this.metaDataFile)); + readHeaders(); + } catch (IOException e) { + log.error("Unable to read headers from " + metaDataFile.getAbsolutePath() + ": " + e.getMessage()); + throw new ChangeSetReaderException("Unable to read headers from " + metaDataFile.getAbsolutePath(), e); + } catch (IllegalArgumentException e) { + log.error("Unable to read headers from " + metaDataFile.getAbsolutePath() + ": " + e.getMessage()); + throw new ChangeSetReaderException("Unable to read headers from " + metaDataFile.getAbsolutePath(), e); + } }
public ChangeSetReaderImpl(Reader metaDataFile) throws Exception { @@ -36,48 +76,74 @@ public class ChangeSetReaderImpl implements ChangeSetReader { }
private void readHeaders() throws IOException { - String name = reader.readLine(); - String basedir = reader.readLine(); - DriftChangeSetCategory type = DriftChangeSetCategory.fromCode(reader.readLine()); - - headers = new Headers(name, basedir, type); + headers = new Headers(); + headers.setResourceId(Integer.parseInt(reader.readLine())); + headers.setDriftCofigurationId(Integer.parseInt(reader.readLine())); + headers.setDriftConfigurationName(reader.readLine()); + headers.setBasedir(reader.readLine()); + headers.setType(DriftChangeSetCategory.fromCode(reader.readLine())); }
@Override - public Headers getHeaders() throws IOException { + public Headers getHeaders() throws ChangeSetReaderException { return headers; }
@Override - public DirectoryEntry readDirectoryEntry() throws IOException { - String line = reader.readLine(); - if (null == line) { - return null; - } - - Matcher m = DIRECTORY_PATTERN.matcher(line); - if (!m.matches() || 2 != m.groupCount()) { - LogFactory.getLog(ChangeSetReaderImpl.class).error("Unexpected directory line, returning null on: " + line); - return null; - } + public DirectoryEntry readDirectoryEntry() throws ChangeSetReaderException { + try { + String dirLine = reader.readLine(); + if (null == dirLine) { + return null; + }
- DirectoryEntry dirEntry = new DirectoryEntry(m.group(1)); - int numFiles = parseInt(m.group(2)); + int index = dirLine.indexOf(" "); + // TODO should we throw a parse exception if index is < 1 + int numFiles = parseInt(dirLine.substring(0, index)); + DirectoryEntry dirEntry = new DirectoryEntry(dirLine.substring(index + 1)); + + for (int i = 0; i < numFiles; ++i) { + String line = reader.readLine(); + if (line.charAt(0) == 'A') { // file added + String sha = line.substring(2, 66); + String fileName = line.substring(69); + + dirEntry.add(addedFileEntry(fileName, sha)); + } else if (line.charAt(0) == 'C') { // file changed + String newSha = line.substring(2, 66); + String oldSha = line.substring(67, 131); + String fileName = line.substring(132); + + dirEntry.add(changedFileEntry(fileName, oldSha, newSha)); + } else if (line.charAt(0) == 'R') { + String sha = line.substring(4, 68); + String fileName = line.substring(69); + + dirEntry.add(removedFileEntry(fileName, sha)); + } else { + log.error("An error occurred while parsing " + metaDataFile.getAbsolutePath() + ": " + + line.charAt(0) + " is not a recognized drift change set category code."); + throw new ChangeSetReaderException(line.charAt(0) + " is not a recognized drift change set " + + "category code."); + } + }
- for (int i = 0; i < numFiles; ++i) { - String[] cols = reader.readLine().split(" "); - dirEntry.add(new FileEntry(cols[0], cols[1], cols[2], cols[3])); + return dirEntry; + } catch (IOException e) { + log.error("An error ocurred while parsing " + metaDataFile.getAbsolutePath() + ": " + e.getMessage()); + throw new ChangeSetReaderException("An error ocurred while parsing " + metaDataFile.getAbsolutePath(), e); } - // Reader the blank line that follows. Not sure if the blank line is needed since - // the directory entry header specifies the number of lines in entry - reader.readLine(); - - return dirEntry; }
@Override - public void close() throws IOException { - reader.close(); + public void close() throws ChangeSetReaderException { + try { + reader.close(); + } catch (IOException e) { + log.warn("An error ocurred while trying to close " + metaDataFile.getAbsolutePath() + ": " + e.getMessage()); + throw new ChangeSetReaderException("An error ocurred while trying to close " + + metaDataFile.getAbsolutePath(), e); + } }
@Override diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java index 25a973a8..4ea79c9 100644 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/ChangeSetWriter.java @@ -1,3 +1,22 @@ +/* + * 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.common.drift;
import java.io.IOException; @@ -8,7 +27,7 @@ import java.io.IOException; * The meta data includes the SHA-256 hash, the old SHA-256 hash (if one exists), the * file name, and a single character code indicating whether the file has been added, * changed, or removed in this change set. The codes are taken from - * {@link org.rhq.core.domain.drift.DriftCategory}. + * {@link org.rhq.core.domain.drift.DriftCategory DriftCategory}. * <br/> * <br/> * The current format of the change set file is: @@ -16,29 +35,33 @@ import java.io.IOException; * HEADER * DRIFT_ENTRY * FILE_ENTRY (1..N) - * EMPTY_LINE * </pre> - * where HEADER has three fields that are terminated by newline characters. Those fields are: + * where HEADER corresponds to {@link Headers} and the header fields are written out in the + * following order: * <ul> + * <li>resource id</li> + * <li>drift configuration id</li> * <li>drift configuration name</li> * <li>drift configuration base directory</li> * <li>change set type flag indicating whether this is a coverage or drift changeset</li> * </ul> * <br/> - * and where DRIFT_ENTRY has two field that are space delimited. The first is the directory path - * and the second is the number of files included in DRIFT_ENTRY. Note that the last FILE_ENTRY - * in DRIFT_ENTRY is followed by a new line. + * DRIFT_ENTRY has two field that are space delimited. The first is the number of files + * included in DRIFT_ENTRY. The second is the relative path of the directory, that is * <br/> - * FILE_ENTRY has four, space-delimited fields - new_sha, old_sha, file_name, type.<br/> + * FILE_ENTRY has four, space-delimited fields - type, new_sha, old_sha, file_name.<br/> * Here is an example change set: * * <pre> - * /var/lib/myserver/lib 2 - * 2c4edd 5bd37a foo.jar C - * d72c54 0 bar.jar A - * - * /var/lib/myserver/conf 1 - * 0 c31d46 foo.conf R + * 1001 + * 2345 + * Core Server JARs + * /var/lib/myserver + * 2 lib + * C 1706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c 1536b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013c foo.jar + * A 2706b5c18e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a 0 bar.jar + * 1 conf + * R 0 2206b5af8e4358041b463995efc30f8f721766fab0e018d50d85978b46df013a foo.conf * </pre> * * For the first directory entry, notice that the old_sha field has a value of 0 for bar.jar. 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 4244fac..d822d40 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 @@ -1,3 +1,22 @@ +/* + * 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.common.drift;
import java.io.BufferedWriter; @@ -6,9 +25,11 @@ import java.io.FileWriter; import java.io.IOException; import java.io.Writer;
-import org.rhq.core.domain.drift.DriftChangeSetCategory; -import org.rhq.core.domain.drift.DriftConfiguration; - +/** + * Note that this implementation does not do any validation. It assumes that each file entry + * contains valid, 64 character SHA-256 hashes. it also assumes paths are not null and that + * directory entry paths are in relative paths. + */ public class ChangeSetWriterImpl implements ChangeSetWriter {
private Writer writer; @@ -25,30 +46,29 @@ 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.getBasedir() + "\n"); writer.write(headers.getType().code() + "\n"); }
public void writeDirectoryEntry(DirectoryEntry dirEntry) throws IOException { - writer.write(dirEntry.getDirectory() + " " + dirEntry.getNumberOfFiles() + "\n"); + writer.write(dirEntry.getNumberOfFiles() + " " + dirEntry.getDirectory() + "\n"); for (FileEntry entry : dirEntry) { switch (entry.getType()) { case FILE_ADDED: - writer.write(entry.getNewSHA() + " 0 " + entry.getFile() + " " + entry.getType().code() + - "\n"); + writer.write(entry.getType().code() + " " + entry.getNewSHA() + " 0 " + entry.getFile() + "\n"); break; case FILE_CHANGED: - writer.write(entry.getNewSHA() + " " + entry.getOldSHA() + " " + entry.getFile() + " " + - entry.getType().code() + "\n"); + writer.write(entry.getType().code() + " " + entry.getNewSHA() + " " + entry.getOldSHA() + " " + + entry.getFile() + "\n"); break; case FILE_REMOVED: - writer.write("0 " + entry.getOldSHA() + " " + entry.getFile() + " " + - entry.getType().code() + "\n"); + writer.write(entry.getType().code() + " 0 " + entry.getOldSHA() + " " + entry.getFile() + "\n"); break; } } - writer.write("\n"); }
File getChangeSetFile() { diff --git a/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java b/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java index c5c5e7a..fabcc7e 100644 --- a/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java +++ b/modules/common/drift/src/main/java/org/rhq/common/drift/DirectoryEntry.java @@ -1,3 +1,22 @@ +/* + * 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.common.drift;
import java.io.Serializable; 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 5387e12..65bfec3 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 @@ -1,3 +1,22 @@ +/* + * 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.common.drift;
import java.io.Serializable; 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 39fe8d9..2799a3c 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 @@ -1,35 +1,115 @@ +/* + * 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.common.drift;
import java.io.Serializable;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
+/** + * A change set meta data file produced with a {@link ChangeSetWriter} includes a set of + * headers which are represented by this class. The headers can be obtained through + * {@link org.rhq.common.drift.ChangeSetReader#getHeaders()}. + */ public class Headers implements Serializable {
private static final long serialVersionUID = 1L;
+ private int driftCofigurationId; + private String driftConfigurationName;
private String basedir;
private DriftChangeSetCategory type;
- public Headers(String driftConfigurationName, String basedir, DriftChangeSetCategory type) { - this.driftConfigurationName = driftConfigurationName; - this.basedir = basedir; - this.type = type; + private int resourceId; + + /** + * This is the id of the resource to which the change set belongs + * + * @return The owning resource id + */ + public int getResourceId() { + return resourceId; }
+ /** @param resourceId The id of the resource to which the change set belongs */ + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } + + /** + * @return The id of the drift configuration to which the change set belongs. + */ + public int getDriftCofigurationId() { + return driftCofigurationId; + } + + /** + * @param driftCofigurationId The id of the drift configuration to which the change set belongs + */ + public void setDriftCofigurationId(int driftCofigurationId) { + this.driftCofigurationId = driftCofigurationId; + } + + /** + * @return The name of the drift configuration to which the change set belongs + */ public String getDriftConfigurationName() { return driftConfigurationName; }
+ /** + * @param name The name of the drift configuration to which the change set belongs + */ + public void setDriftConfigurationName(String name) { + driftConfigurationName = name; + } + + /** + * @return The full path of the top-level directory from which drift detection is performed + */ public String getBasedir() { return basedir; }
+ /** + * @param basedir The full path of the top-level directory from which drift detection is performed + */ + public void setBasedir(String basedir) { + this.basedir = basedir; + } + + /** + * @return The type of change set + */ public DriftChangeSetCategory getType() { return type; }
+ /** + * @param type The type of change set + */ + public void setType(DriftChangeSetCategory type) { + this.type = type; + } + } 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 a953414..db4955c 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 @@ -1,30 +1,41 @@ package org.rhq.common.drift;
import java.io.StringReader; -import java.util.ArrayList; -import java.util.List;
import org.testng.annotations.Test;
-import org.rhq.core.domain.drift.DriftChangeSetCategory; +import org.rhq.core.util.MessageDigestGenerator;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -import static org.testng.Assert.*; +import static org.rhq.test.AssertUtils.assertPropertiesMatch; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull;
public class ChangeSetReaderImplTest { + + MessageDigestGenerator digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); + @Test @SuppressWarnings("unchecked") public void readDirectoryEntryWithFileAdded() throws Exception { - String changeset = "file-added-test\n" + + String sha = sha256("myconf.conf"); + String changeset = "1\n" + + "1\n" + + "file-added-test\n" + "myresource\n" + "C\n" + - "myresource/conf 1\n" + - "a34ef6 0 myconf.conf A"; + "1 myresource/conf\n" + + "A " + sha + " 0 myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
Headers actualHeaders = reader.getHeaders(); - Headers expectedHeaders = new Headers("file-added-test", "myresource", COVERAGE); + Headers expectedHeaders = new Headers(); + expectedHeaders.setResourceId(1); + expectedHeaders.setDriftCofigurationId(1); + expectedHeaders.setDriftConfigurationName("file-added-test"); + expectedHeaders.setBasedir("myresource"); + expectedHeaders.setType(COVERAGE);
assertHeadersEquals(actualHeaders, expectedHeaders);
@@ -34,7 +45,7 @@ public class ChangeSetReaderImplTest { assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1);
FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry("a34ef6", "0", "myconf.conf", "A"); + FileEntry expectedFileEntry = new FileEntry(sha, "0", "myconf.conf", "A");
assertFileEntryEquals(actualFileEntry, expectedFileEntry); } @@ -42,16 +53,24 @@ public class ChangeSetReaderImplTest { @Test @SuppressWarnings("unchecked") public void readDirectoryEntryWithFileRemoved() throws Exception { - String changeset = "file-removed-test\n" + + String sha = sha256("myconf.conf"); + String changeset = "1\n" + + "1\n" + + "file-removed-test\n" + "myresource\n" + "C\n" + - "myresource/conf 1\n" + - "0 a34ef6 myconf.conf R"; + "1 myresource/conf\n" + + "R 0 " + sha + " myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
Headers actualHeaders = reader.getHeaders(); - Headers expectedHeaders = new Headers("file-removed-test", "myresource", COVERAGE); + Headers expectedHeaders = new Headers(); + expectedHeaders.setResourceId(1); + expectedHeaders.setDriftCofigurationId(1); + expectedHeaders.setDriftConfigurationName("file-removed-test"); + expectedHeaders.setBasedir("myresource"); + expectedHeaders.setType(COVERAGE);
assertHeadersEquals(actualHeaders, expectedHeaders);
@@ -61,7 +80,7 @@ public class ChangeSetReaderImplTest { assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1);
FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry("0", "a34ef6", "myconf.conf", "R"); + FileEntry expectedFileEntry = new FileEntry("0", sha, "myconf.conf", "R");
assertFileEntryEquals(actualFileEntry, expectedFileEntry); } @@ -69,16 +88,25 @@ public class ChangeSetReaderImplTest { @Test @SuppressWarnings("unchecked") public void readDirectoryEntryWithFileChanged() throws Exception { - String changeset = "file-changed-test\n" + + String oldSha = sha256("myconf.conf.old"); + String newSha = sha256("myconf.conf.new"); + String changeset = "1\n" + + "1\n" + + "file-changed-test\n" + "myresource\n" + "C\n" + - "myresource/conf 1\n" + - "a34ef6 c41b8 myconf.conf C"; + "1 myresource/conf\n" + + "C " + newSha + " " + oldSha + " myconf.conf";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset));
Headers actualHeaders = reader.getHeaders(); - Headers expectedHeaders = new Headers("file-changed-test", "myresource", COVERAGE); + Headers expectedHeaders = new Headers(); + expectedHeaders.setResourceId(1); + expectedHeaders.setDriftCofigurationId(1); + expectedHeaders.setDriftConfigurationName("file-changed-test"); + expectedHeaders.setBasedir("myresource"); + expectedHeaders.setType(COVERAGE);
assertHeadersEquals(actualHeaders, expectedHeaders);
@@ -88,7 +116,42 @@ public class ChangeSetReaderImplTest { assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1);
FileEntry actualFileEntry = dirEntry.iterator().next(); - FileEntry expectedFileEntry = new FileEntry("a34ef6", "c41b8", "myconf.conf", "C"); + FileEntry expectedFileEntry = new FileEntry(newSha, oldSha, "myconf.conf", "C"); + + assertFileEntryEquals(actualFileEntry, expectedFileEntry); + } + + @Test + @SuppressWarnings("unchecked") + public void readEntryWithAddedFileThatHasSpaces() throws Exception { + String sha = sha256("file with spaces.conf"); + String changeset = "1\n" + + "1\n" + + "file-name-test\n" + + "myresource\n" + + "C\n" + + "1 myresource/conf\n" + + "A " + sha + " 0 file with spaces.conf"; + + ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); + + Headers actualHeaders = reader.getHeaders(); + Headers expectedHeaders = new Headers(); + expectedHeaders.setResourceId(1); + expectedHeaders.setDriftCofigurationId(1); + expectedHeaders.setDriftConfigurationName("file-name-test"); + expectedHeaders.setBasedir("myresource"); + expectedHeaders.setType(COVERAGE); + + assertHeadersEquals(actualHeaders, expectedHeaders); + + DirectoryEntry dirEntry = reader.readDirectoryEntry(); + reader.close(); + + assertDirectoryEntryEquals(dirEntry, "myresource/conf", 1); + + FileEntry actualFileEntry = dirEntry.iterator().next(); + FileEntry expectedFileEntry = new FileEntry(sha, "0", "file with spaces.conf", "A");
assertFileEntryEquals(actualFileEntry, expectedFileEntry); } @@ -106,14 +169,15 @@ public class ChangeSetReaderImplTest { @Test @SuppressWarnings("unchecked") public void iterateOverChangeSetWithMultipledDirectoryEntries() throws Exception { - String changeset = "multiple-dir-entries-test\n" + + String changeset = "1\n" + + "1\n" + + "multiple-dir-entries-test\n" + "myresource\n" + "C\n" + - "conf 1\n" + - "abcd 0 resource.conf A\n" + - "\n" + - "lib 1\n" + - "1234 0 resource.jar A"; + "1 conf\n" + + "A " + sha256("resource.conf") + " 0 resource.conf\n" + + "1 lib\n" + + "A " + sha256("resource.jar") + " 0 resource.jar";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); int numDirEntries = 0; @@ -128,12 +192,14 @@ public class ChangeSetReaderImplTest { @Test @SuppressWarnings("unchecked") public void iterateOverChangeSetOneDirectoryEntry() throws Exception { - String changeset = "single-dir-entry-test\n" + + String sha = sha256("resource.conf"); + String changeset = "1\n" + + "1\n" + + "single-dir-entry-test\n" + "myresource\n" + "C\n" + - "conf 1\n" + - "abcd 0 resource.conf A\n" + - "\n"; + "1 conf\n" + + "A " + sha + " 0 resource.conf\n";
ChangeSetReaderImpl reader = new ChangeSetReaderImpl(new StringReader(changeset)); int numDirEntries = 0; @@ -152,7 +218,9 @@ public class ChangeSetReaderImplTest { // header) but this test is here to make sure ChangeReaderImpl is robust in handling // edge cases.
- String changeset = "empty-changeset-test\n" + + String changeset = "1\n" + + "1\n" + + "empty-changeset-test\n" + "myresouce\n" + "C\n";
@@ -167,12 +235,7 @@ public class ChangeSetReaderImplTest { }
void assertHeadersEquals(Headers actual, Headers expected) { - assertEquals(actual.getDriftConfigurationName(), expected.getDriftConfigurationName(), - "The drift configuration name, which should be the first header, is wrong."); - assertEquals(actual.getBasedir(), expected.getBasedir(), "The drift configuration base directory, which " + - "should be the second header, is wrong."); - assertEquals(actual.getType(), expected.getType(), "The change set type flag, " + - "which should be the third header, is wrong."); + assertPropertiesMatch(expected, actual, "Failed to parse change set headers"); }
/** @@ -191,10 +254,14 @@ public class ChangeSetReaderImplTest { }
void assertFileEntryEquals(FileEntry actual, FileEntry expected) { - assertEquals(actual.getNewSHA(), expected.getNewSHA(), "The first column, the new SHA-256, is wrong"); - assertEquals(actual.getOldSHA(), expected.getOldSHA(), "The second column, the old SHA-256, is wrong"); - assertEquals(actual.getFile(), expected.getFile(), "The third column, the file name, is wrong"); - assertEquals(actual.getType(), expected.getType(), "The fourth column, the entry type, is wrong"); + assertEquals(actual.getType(), expected.getType(), "The first column, the entry type, is wrong"); + assertEquals(actual.getNewSHA(), expected.getNewSHA(), "The second column, the new SHA-256, is wrong"); + assertEquals(actual.getOldSHA(), expected.getOldSHA(), "The third column, the old SHA-256, is wrong"); + assertEquals(actual.getFile(), expected.getFile(), "The fourth column, the file name, is wrong"); + } + + String sha256(String s) throws Exception { + return digestGenerator.calcDigestString(s); }
} 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 0109619..433634b 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 @@ -1,3 +1,22 @@ +/* + * 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.common.drift;
import java.io.File; @@ -7,20 +26,13 @@ import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
-import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.drift.DriftChangeSetCategory; -import org.rhq.core.domain.drift.DriftConfiguration; - import static org.apache.commons.io.FileUtils.deleteDirectory; -import static org.apache.commons.io.IOUtils.lineIterator; import static org.apache.commons.io.IOUtils.readLines; 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.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue;
public class ChangeSetWriterImplTest {
@@ -48,7 +60,13 @@ public class ChangeSetWriterImplTest { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "added-file-test"); - Headers headers = new Headers("added-file-test", resourceDir.getAbsolutePath(), COVERAGE); + + Headers headers = new Headers(); + headers.setResourceId(1); + headers.setDriftCofigurationId(2); + headers.setDriftConfigurationName("add-file-test"); + headers.setBasedir(resourceDir.getAbsolutePath()); + headers.setType(COVERAGE);
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
@@ -59,15 +77,15 @@ public class ChangeSetWriterImplTest { File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 6, "Expected to find six lines in " + metaDataFile.getPath() + - " - three for the header followed by three for a directory entry."); + assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + + " - five for the header followed by two for a directory entry.");
- assertHeaderEquals(lines, "added-file-test", resourceDir.getAbsolutePath(), "C"); + assertHeadersEquals(lines, headers);
- assertEquals(lines.get(3), "conf 1", "The first line for a directory entry should specify the " + - "directory path followed by the number of lines in the entry."); + assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + + "the number of lines in the entry followed by the directory path.");
- assertFileEntryEquals(lines.get(4), "a34ef6 0 myconf.conf A"); + assertFileEntryEquals(lines.get(6), "A a34ef6 0 myconf.conf"); }
@Test @@ -76,7 +94,12 @@ public class ChangeSetWriterImplTest { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "removed-file-test"); - Headers headers = new Headers("removed-file-test", resourceDir.getAbsolutePath(), COVERAGE); + Headers headers = new Headers(); + headers.setResourceId(1); + headers.setDriftCofigurationId(2); + headers.setDriftConfigurationName("removed-file-test"); + headers.setBasedir(resourceDir.getAbsolutePath()); + headers.setType(COVERAGE);
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
@@ -87,15 +110,15 @@ public class ChangeSetWriterImplTest { File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 6, "Expected to find six lines in " + metaDataFile.getPath() + - " - three for the header followed by three for a directory entry."); + assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + + " - five for the header followed by two for a directory entry.");
- assertHeaderEquals(lines, "removed-file-test", resourceDir.getAbsolutePath(), "C"); + assertHeadersEquals(lines, headers);
- assertEquals(lines.get(3), "conf 1", "The first line for a directory entry should specify the " + - "directory path followed by the number of lines in the entry."); + assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + + "the number of lines in the entry followed by the directory path.");
- assertFileEntryEquals(lines.get(4), "0 a34ef6 myconf.conf R"); + assertFileEntryEquals(lines.get(6), "R 0 a34ef6 myconf.conf"); }
@Test @@ -104,7 +127,12 @@ public class ChangeSetWriterImplTest { File resourceDir = new File(resourcesDir, "myresource");
File changeSetFile = new File(changeSetsDir, "changed-file-test"); - Headers headers = new Headers("changed-file-test", resourceDir.getAbsolutePath(), COVERAGE); + Headers headers = new Headers(); + headers.setResourceId(1); + headers.setDriftCofigurationId(2); + headers.setDriftConfigurationName("changed-file-test"); + headers.setBasedir(resourceDir.getAbsolutePath()); + headers.setType(COVERAGE);
ChangeSetWriterImpl writer = new ChangeSetWriterImpl(changeSetFile, headers);
@@ -115,43 +143,41 @@ public class ChangeSetWriterImplTest { File metaDataFile = writer.getChangeSetFile(); List<String> lines = readLines(new FileInputStream(metaDataFile));
- assertEquals(lines.size(), 6, "Expected to find six lines in " + metaDataFile.getPath() + - " - three for the header followed by three for a directory entry."); + assertEquals(lines.size(), 7, "Expected to find seven lines in " + metaDataFile.getPath() + + " - five for the header followed by two for a directory entry.");
- assertHeaderEquals(lines, "changed-file-test", resourceDir.getAbsolutePath(), "C"); + assertHeadersEquals(lines, headers);
- assertEquals(lines.get(3), "conf 1", "The first line for a directory entry should specify the " + - "directory path followed by the number of lines in the entry."); + assertEquals(lines.get(5), "1 conf", "The first line for a directory entry should specify the " + + "the number of lines in the entry followed by the directory path.");
- assertFileEntryEquals(lines.get(4), "c2d55f a34ef6 myconf.conf C"); + assertFileEntryEquals(lines.get(6), "C c2d55f a34ef6 myconf.conf"); }
/** - * Verifies that <code>lines</code>, which is assumed to represent the entire changeset - * file, contains the expected header. The header contains three entries which are - * written out one entry per line. The header is the first three lines of the changeset - * file and contains the following entries: + * Verifies that <code>lines</code> which is assumed to represent the entire cange set + * file contains the expected headers * - * <ul> - * <li>drift configuration name</li> - * <li>drift configuration base directory</li> - * <li>Flag indicating whether or not this is an initial changeset. The flag is a - * single letter code code from {@link DriftChangeSetCategory}</li> - * </ul> - * @param lines - * @param expected + * @param lines The change set where each string in the list represents a line + * @param headers The expected headers */ - void assertHeaderEquals(List<String> lines, String... expected) { - assertEquals(lines.get(0), expected[0], "The first header entry should be the drift configuration name."); - assertEquals(lines.get(1), expected[1], "The second header entry should be the base directory."); - assertEquals(lines.get(2), expected[2], "The third header entry should be a flag indicating the change set " + - "type."); + 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 " + + "should be the drift configuration id."); + assertEquals(lines.get(2), headers.getDriftConfigurationName(), "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."); + assertEquals(lines.get(4), headers.getType().code(), "The fifth header entry should be the change set " + + "category code"); }
/** * Verifies that a file entry matches an expected value. A file entry consists of * four, space-delimited fields and is terminated by a newline character. Those fields - * are new_sha, old_sha, file_name, type. + * are type_code, new_sha, old_sha, file_name. * * @param actual * @param expected @@ -169,12 +195,4 @@ public class ChangeSetWriterImplTest { assertEquals(actualFields[3], expectedFields[3], "The fourth column, the type, is wrong"); }
- DriftConfiguration driftConfiguration(String name, String basedir) { - Configuration config = new Configuration(); - config.put(new PropertySimple("name", name)); - config.put(new PropertySimple("basedir", basedir)); - - return new DriftConfiguration(config); - } - } 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 4ef7821..e2b1c80 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.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 dbb1cfb..e83f84d 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.BufferedInputStream; 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 153e5a9..4beaed1 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.File; @@ -67,8 +86,7 @@ public class DriftDetector implements Runnable { int changes = 0;
try { - if (changeSetMgr.changeSetExists(schedule.getResourceId(), new Headers(driftConfig.getName(), - basedir(resourceId, driftConfig), COVERAGE))) { + if (changeSetMgr.changeSetExists(schedule.getResourceId(), createHeaders(schedule, COVERAGE))) { changeSetType = DRIFT; changes = generateDriftChangeSet(schedule); } else { @@ -92,9 +110,9 @@ public class DriftDetector implements Runnable { File basedir = new File(basedir(schedule.getResourceId(), schedule.getDriftConfiguration()));
ChangeSetWriter driftWriter = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), - new Headers(schedule.getDriftConfiguration().getName(), basedir.getAbsolutePath(), DRIFT)); + createHeaders(schedule, DRIFT)); ChangeSetWriter coverageWriter = changeSetMgr.getChangeSetWriterForUpdate(schedule.getResourceId(), - new Headers(schedule.getDriftConfiguration().getName(), basedir.getAbsolutePath(), COVERAGE)); + createHeaders(schedule, COVERAGE)); ChangeSetReader reader = changeSetMgr.getChangeSetReader(schedule.getResourceId(), schedule.getDriftConfiguration().getName());
@@ -144,16 +162,14 @@ public class DriftDetector implements Runnable { } driftWriter.close(); coverageWriter.close(); - changeSetMgr.updateChangeSet(schedule.getResourceId(), new Headers(schedule.getDriftConfiguration().getName(), - basedir.getAbsolutePath(), COVERAGE)); + changeSetMgr.updateChangeSet(schedule.getResourceId(), createHeaders(schedule, COVERAGE));
return changes; }
private void generateCoverageChangeSet(DriftDetectionSchedule schedule) throws IOException { - ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), - new Headers(schedule.getDriftConfiguration().getName(), - basedir(schedule.getResourceId(), schedule.getDriftConfiguration()), COVERAGE)); + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(schedule.getResourceId(), createHeaders(schedule, + COVERAGE));
DirectoryScanner scanner = new DirectoryScanner(schedule.getResourceId(), schedule.getDriftConfiguration(), writer); @@ -175,6 +191,17 @@ public class DriftDetector implements Runnable { return driftClient.getAbsoluteBaseDirectory(resourceId, driftConfig).getAbsolutePath(); }
+ private Headers createHeaders(DriftDetectionSchedule schedule, DriftChangeSetCategory type) { + 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.setType(type); + + return headers; + } + // TODO Do not use DirectoryWalker // Want to do the file scan iteratively to keep memory overhead as low as possible. private class DirectoryScanner extends DirectoryWalker { 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 d22563c..4f36939 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 @@ -1,6 +1,23 @@ -package org.rhq.core.pc.drift; +/* + * 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. + */
-import static org.rhq.core.util.ZipUtil.zipFileOrDirectory; +package org.rhq.core.pc.drift;
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -33,6 +50,8 @@ 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.core.util.ZipUtil.zipFileOrDirectory; + public class DriftManager extends AgentService implements DriftAgentService, DriftClient, ContainerService {
private final Log log = LogFactory.getLog(DriftManager.class); 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 e4ab114..a914bfe 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.File; @@ -6,10 +25,14 @@ import java.util.List; import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetReader; +import org.rhq.common.drift.ChangeSetWriter; import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.Headers; +import org.rhq.core.domain.drift.DriftChangeSetCategory;
import static java.util.Arrays.asList; +import static org.rhq.common.drift.FileEntry.addedFileEntry; +import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; @@ -28,44 +51,42 @@ public class ChangeSetManagerImplTest extends DriftTest { @Test public void returnReaderForRequestedChangeSet() throws Exception { String config = "return-reader-for-existing-changeset-test"; - File changeSetDir = changeSetDir(config);
- writeChangeSet(changeSetDir, - config, - "server", - "D", - "server/conf 1", - "8f26ac3d 0 myconf.conf A" - ); + File confDir = mkdir(resourceDir, "conf"); + File serverConf = createRandomFile(confDir, "server.conf"); + String serverConfHash = sha256(serverConf); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); + writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server.conf", serverConfHash))); + writer.close();
ChangeSetReader reader = changeSetMgr.getChangeSetReader(resourceId(), config);
assertNotNull(reader, "Expected to get a change set reader when change set exists"); - assertReaderOpenedOnChangeSet(reader, asList("server/conf", "1")); + assertReaderOpenedOnChangeSet(reader, asList("conf", "1")); }
@Test public void verifyChangeSetExists() throws Exception { String config = "changeset-exists-test"; - File changeSetDir = changeSetDir(config); - - writeChangeSet(changeSetDir, - config, - "server", - "D", - "server/conf 1", - "8f26ac3d 0 myconf.conf A" - ); - - assertTrue(changeSetMgr.changeSetExists(resourceId(), new Headers(config, resourceDir.getAbsolutePath(), - DRIFT)), "Expected to find change set file."); + + File confDir = mkdir(resourceDir, "conf"); + File serverConf = createRandomFile(confDir, "server.conf"); + + Headers headers = createHeaders(config, COVERAGE); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); + writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server.conf", sha256(serverConf)))); + writer.close(); + + assertTrue(changeSetMgr.changeSetExists(resourceId(), headers), "Expected to find change set file."); }
@Test public void verifyChangeSetDoesNotExist() throws Exception { String config = "changeset-does-not-exist"; - assertFalse(changeSetMgr.changeSetExists(resourceId(), new Headers(config, resourceDir.getAbsolutePath(), - DRIFT)), "Did not expect to find change set file."); + assertFalse(changeSetMgr.changeSetExists(resourceId(), createHeaders(config, DRIFT)), + "Did not expect to find change set file."); }
/** @@ -94,4 +115,15 @@ public class ChangeSetManagerImplTest extends DriftTest { "The number of files for the directory entry is wrong"); }
+ Headers createHeaders(String driftConfigName, DriftChangeSetCategory type) { + Headers headers = new Headers(); + headers.setResourceId(resourceId()); + headers.setDriftCofigurationId(1); + headers.setDriftConfigurationName(driftConfigName); + headers.setBasedir(resourceDir.getPath()); + headers.setType(type); + + return headers; + } + } 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 49dab54..1b44518 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.BufferedReader; @@ -13,6 +32,7 @@ import org.testng.annotations.Test;
import org.rhq.common.drift.ChangeSetReader; import org.rhq.common.drift.ChangeSetReaderImpl; +import org.rhq.common.drift.ChangeSetWriter; import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; @@ -63,7 +83,7 @@ public class DriftDetectorTest extends DriftTest {
File changeSet = changeSet(driftConfig.getName(), COVERAGE);
- assertHeaderEquals(changeSet, new Headers(driftConfig.getName(), resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(changeSet, createHeaders(driftConfig, COVERAGE)); assertThatChangeSetDoesNotContainEmptyDirs(changeSet); }
@@ -107,7 +127,7 @@ public class DriftDetectorTest extends DriftTest {
File changeSet = changeSet(config.getName(), COVERAGE);
- assertHeaderEquals(changeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(changeSet, createHeaders(config, COVERAGE)); assertChangeSetContainsDirEntry(changeSet, new DirectoryEntry("conf") .add(addedFileEntry("server-1.conf", sha256(server1Conf))) @@ -132,7 +152,7 @@ public class DriftDetectorTest extends DriftTest {
File changeSet = changeSet(config.getName(), COVERAGE);
- assertHeaderEquals(changeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
assertChangeSetContainsDirEntry(changeSet, new DirectoryEntry("conf").add(addedFileEntry("server.conf", sha256(serverConf)))); @@ -158,7 +178,7 @@ public class DriftDetectorTest extends DriftTest {
File changeSet = changeSet(config.getName(), COVERAGE);
- assertHeaderEquals(changeSet, new Headers("nested-dirs-test", resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(changeSet, createHeaders(config, COVERAGE));
assertChangeSetContainsDirEntry(changeSet, new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); @@ -201,17 +221,9 @@ public class DriftDetectorTest extends DriftTest { File server1Conf = new File(confDir, "server-1.conf"); touch(server1Conf);
- File changeSetDir = changeSetDir(config.getName()); - - // Generate the initial, coverage change set - writeChangeSet(changeSetDir, - config.getName(), - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 1", - sha256(server1Conf) + " 0 server-1.conf A", - "" - ); + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); + writer.writeDirectoryEntry(new DirectoryEntry("conf").add(addedFileEntry("server-1.conf", sha256(server1Conf)))); + writer.close();
// Create some drift File server2Conf = new File(confDir, "server-2.conf"); @@ -225,14 +237,14 @@ public class DriftDetectorTest extends DriftTest { assertTrue(driftChangeSet.exists(), "Expected to find drift change set " + driftChangeSet.getPath());
// verify that the drift change set was generated - assertHeaderEquals(driftChangeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), DRIFT)); + assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT)); assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") .add(addedFileEntry("server-2.conf", sha256(server2Conf))));
File coverageChangeSet = changeSet(config.getName(), COVERAGE);
// verify that the coverage change set was updated - assertHeaderEquals(coverageChangeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); assertChangeSetContainsDirEntry(coverageChangeSet, new DirectoryEntry("conf") .add(addedFileEntry("server-1.conf", sha256(server1Conf))) .add(addedFileEntry("server-2.conf", sha256(server2Conf)))); @@ -250,18 +262,12 @@ public class DriftDetectorTest extends DriftTest { touch(server2Conf);
String server2ConfHash = sha256(server2Conf); - File changeSetDir = changeSetDir(config.getName()); - - // generate the initial, coverage change set - writeChangeSet(changeSetDir, - config.getName(), - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - sha256(server1Conf) + " 0 server-1.conf A", - server2ConfHash + " 0 server-2.conf A", - "" - ); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), createHeaders(config, COVERAGE)); + writer.writeDirectoryEntry(new DirectoryEntry("conf") + .add(addedFileEntry("server-1.conf", sha256(server1Conf))) + .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.close();
// create some drift server2Conf.delete(); @@ -273,14 +279,14 @@ public class DriftDetectorTest extends DriftTest {
// verify that the drift change set was generated assertTrue(driftChangeSet.exists(), "Expected to find drift change set " + driftChangeSet.getPath()); - assertHeaderEquals(driftChangeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), DRIFT)); + assertHeaderEquals(driftChangeSet, createHeaders(config, DRIFT)); assertChangeSetContainsDirEntry(driftChangeSet, new DirectoryEntry("conf") .add(removedFileEntry("server-2.conf", server2ConfHash)));
// verify that the coverage change set was updated File coverageChangeSet = changeSet(config.getName(), COVERAGE);
- assertHeaderEquals(coverageChangeSet, new Headers(config.getName(), resourceDir.getAbsolutePath(), COVERAGE)); + assertHeaderEquals(coverageChangeSet, createHeaders(config, COVERAGE)); assertChangeSetContainsDirEntry(coverageChangeSet, new DirectoryEntry("conf") .add(addedFileEntry("server-1.conf", sha256(server1Conf)))); } @@ -319,6 +325,17 @@ public class DriftDetectorTest extends DriftTest { expected + " in change set " + changeSet.getPath() + " do not match"); }
+ Headers createHeaders(DriftConfiguration driftConfig, DriftChangeSetCategory type) { + Headers headers = new Headers(); + headers.setResourceId(resourceId()); + headers.setDriftCofigurationId(driftConfig.getId()); + headers.setDriftConfigurationName(driftConfig.getName()); + headers.setBasedir(resourceDir.getAbsolutePath()); + headers.setType(type); + + return headers; + } + Collection<FileEntry> fileEntries(DirectoryEntry dirEntry) { List<FileEntry> list = new ArrayList<FileEntry>(); for (FileEntry entry : dirEntry) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java.orig b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java.orig deleted file mode 100644 index 3dfb057..0000000 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftDetectorTest.java.orig +++ /dev/null @@ -1,172 +0,0 @@ -package org.rhq.core.pc.drift; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.util.List; - -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import org.rhq.common.drift.ChangeSetReader; -import org.rhq.common.drift.ChangeSetReaderImpl; -import org.rhq.common.drift.DirectoryEntry; -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.drift.DriftConfiguration; - -import static org.apache.commons.io.IOUtils.readLines; -import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -import static org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext.fileSystem; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.unitils.thirdparty.org.apache.commons.io.FileUtils.touch; - -public class DriftDetectorTest extends DriftTest { - - ScheduleQueue scheduleQueue; - - DriftClientTestStub driftClient; - - DriftDetector detector; - - @BeforeMethod - public void initDetector() { - driftClient = new DriftClientTestStub(); - driftClient.setBaseDir(resourceDir); - - scheduleQueue = new ScheduleQueueImpl(); - - detector = new DriftDetector(); - detector.setDriftClient(driftClient); - detector.setChangeSetManager(changeSetMgr); - detector.setScheduleQueue(scheduleQueue); - } - - @SuppressWarnings("unchecked") - @Test - public void excludeEmptyDirsFromCoverageChangeSet() throws Exception { - File confDir = mkdir(resourceDir, "conf"); - touch(new File(confDir, "server.conf")); - - DriftConfiguration driftConfig = driftConfiguration("coverage-test", resourceDir.getAbsolutePath()); - - scheduleQueue.enqueue(new DriftDetectionSchedule(resourceId(), driftConfig)); - detector.run(); - - File changeSetDir = changeSetDir(driftConfig.getName()); - File changeSet = new File(changeSetDir, "changeset.txt"); - List<String> lines = readLines(new BufferedInputStream(new FileInputStream(changeSet))); - - assertHeaderEquals(lines, driftConfig.getName(), driftConfig.getBasedir().getValueName(), COVERAGE.code()); - assertThatChangeSetDoesNotContainEmptyDirs(changeSet); - } - - @SuppressWarnings("unchecked") - @Test - public void usePeriodAsNameOfBasedirDirectoryEntry() throws Exception { - touch(new File(resourceDir, "data-1.txt")); - touch(new File(resourceDir, "data-2.txt")); - - DriftConfiguration driftConfig = driftConfiguration("basedir-entry-test", resourceDir.getAbsolutePath()); - - scheduleQueue.enqueue(new DriftDetectionSchedule(resourceId(), driftConfig)); - detector.run(); - - File changeSetDir = changeSetDir(driftConfig.getName()); - DriftDetectionSchedule schedule = new DriftDetectionSchedule(resourceId(), driftConfig); - - scheduleQueue.enqueue(schedule); - detector.run(); - - File changeSetDir = new File(new File(changeSetsDir, Integer.toString(resourceId())), "coverage-test"); - File changeSet = new File(changeSetDir, "changeset.txt"); - List<String> lines = readLines(new BufferedInputStream(new FileInputStream(changeSet))); - - assertEquals(lines.size(), 7, "Expected " + changeSet.getPath() + " to have seven lines."); - assertEquals(". 2", lines.get(3), "The directory header name is wrong for change set " + - changeSet.getAbsolutePath()); - } - - @SuppressWarnings("unchecked") - @Test - public void includeNestedDirsInCoverageChangeSet() throws Exception { - File confDir = mkdir(resourceDir, "conf"); - File server1Conf = new File(confDir, "server-1.conf"); - touch(server1Conf); - - File subConfDir = mkdir(confDir, "subconf"); - File server2Conf = new File(subConfDir, "server-2.conf"); - touch(server2Conf); - - DriftConfiguration config = driftConfiguration("nested-dirs-test", resourceDir.getAbsolutePath()); - - scheduleQueue.enqueue(new DriftDetectionSchedule(resourceId(), config)); - detector.run(); - - File changesetDir = changeSetDir(config.getName()); - File changeSet = new File(changesetDir, "changeset.txt"); - List<String> lines = readLines(new BufferedInputStream(new FileInputStream(changeSet))); - - assertEquals(lines.size(), 9, "Expected " + changeSet.getPath() + " to have 9 lines"); - - assertHeaderEquals(lines, "nested-dirs-test", resourceDir.getAbsolutePath(), "C"); -// assertChangeSetContainsDirEntry(lines, -// "conf 1", -// sha256(server1Conf) + " 0 " + server1Conf.getName() + " " + FILE_ADDED -// ); - } - - void assertHeaderEquals(List<String> lines, String... expected) { - assertEquals(lines.get(0), expected[0], "The first header entry should be the drift configuration name."); - assertEquals(lines.get(1), expected[1], "The second header entry should be the base directory."); - assertEquals(lines.get(2), expected[2], "The third header entry should be a flag indicating the change set " - + "type."); - } - - void assertThatChangeSetDoesNotContainEmptyDirs(File changeSet) throws Exception { - ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new FileReader(changeSet))); - DirectoryEntry dirEntry = reader.readDirectoryEntry(); - - while (dirEntry != null) { - Assert.assertTrue(dirEntry.getNumberOfFiles() > 0, "The change set file should not include empty " - + "directories"); - dirEntry = reader.readDirectoryEntry(); - } - } - -// void assertChangeSetContainsDirEntry(List<String> changeSet, String... dirEntry) { -// String dirEntryHeader = dirEntry[0]; -// int i = -1; -// boolean found = false; -// -// for (String line : changeSet) { -// if (line.equals(dirEntryHeader)) { -// found = true; -// } -// ++i; -// if (found) { -// break; -// } -// } -// } -// -// void assertChangeSetContainsDirEntry(File changeSet, String... dirEntry) throws Exception { -// ChangeSetReader reader = new ChangeSetReaderImpl(changeSet); -// DirectoryEntry actualDirEntry = reader.readDirectoryEntry(); -// -// while (dir) -// } - - DriftConfiguration driftConfiguration(String name, String basedir) { - DriftConfiguration config = new DriftConfiguration(new Configuration()); - config.setName(name); - config.setBasedir(new DriftConfiguration.BaseDirectory(fileSystem, basedir)); - - return config; - } -} 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 c1f4559..30ebe6a 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.File; @@ -7,12 +26,14 @@ import java.util.List; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
+import org.rhq.common.drift.ChangeSetWriter; +import org.rhq.common.drift.DirectoryEntry; import org.rhq.common.drift.Headers; +import org.rhq.core.domain.drift.DriftChangeSetCategory; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.JPADriftFile;
-import static org.apache.commons.io.FileUtils.touch; -import static org.apache.commons.io.IOUtils.writeLines; +import static org.rhq.common.drift.FileEntry.addedFileEntry; import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; @@ -38,32 +59,31 @@ public class DriftFilesSenderTest extends DriftTest { String driftConfigName = "single-directory-test";
File confDir = mkdir(resourceDir, "conf"); - touch(new File(confDir, "server-1.conf")); - touch(new File(confDir, "server-2.conf")); + File server1Conf = createRandomFile(confDir, "server-1.conf"); + File server2Conf = createRandomFile(confDir, "server-2.conf"); + + String server1ConfHash = sha256(server1Conf); + String server2ConfHash = sha256(server2Conf);
File changeSetDir = changeSetDir(driftConfigName);
- // Each item in changeSet is listed by the line it will appear in the actual file - // in an attemp to make it more self-documenting. - writeChangeSet(changeSetDir, - driftConfigName, - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - "2e345df 0 server-1.conf A", - "a5d8c3e 0 server-2.conf A", - "" - ); - - sender.setDriftFiles(driftFiles("2e345df", "a5d8c3e")); - sender.setHeaders(new Headers(driftConfigName, resourceDir.getAbsolutePath(), COVERAGE)); + Headers headers = createHeaders(driftConfigName, COVERAGE); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); + writer.writeDirectoryEntry(new DirectoryEntry("conf") + .add(addedFileEntry("server-1.conf", server1ConfHash)) + .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.close(); + + sender.setDriftFiles(driftFiles(server1ConfHash, server2ConfHash)); + sender.setHeaders(createHeaders(driftConfigName, COVERAGE)); sender.run();
File contentDir = mkdir(changeSetDir, "content");
assertEquals(contentDir.list().length, 2, "Expected to find two files in " + contentDir.getAbsolutePath()); - assertFileCopiedToContentDir(contentDir, "2e345df"); - assertFileCopiedToContentDir(contentDir, "a5d8c3e"); + assertFileCopiedToContentDir(contentDir, server1ConfHash); + assertFileCopiedToContentDir(contentDir, server2ConfHash); }
@Test @@ -72,74 +92,78 @@ public class DriftFilesSenderTest extends DriftTest {
File confDir = mkdir(resourceDir, "conf"); File libDir = mkdir(resourceDir, "lib"); - touch(new File(confDir, "server-1.conf")); - touch(new File(confDir, "server-2.conf")); - touch(new File(libDir, "server-1.jar")); - touch(new File(libDir, "server-2.jar")); + File server1Conf = createRandomFile(confDir, "server-1.conf"); + File server2Conf = createRandomFile(confDir, "server-2.conf"); + File server1Jar = createRandomFile(libDir, "server-1.jar"); + File server2Jar = createRandomFile(libDir, "server-2.jar"); + + String server1ConfHash = sha256(server1Conf); + String server2ConfHash = sha256(server2Conf); + String server1JarHash = sha256(server1Jar); + String server2JarHash = sha256(server2Jar);
File changeSetDir = changeSetDir(driftConfigName);
- // Each item in changeSet is listed by the line it will appear in the actual file - // in an attemp to make it more self-documenting. - writeChangeSet(changeSetDir, - driftConfigName, - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - "2e345df 0 server-1.conf A", - "a5d8c3e 0 server-2.conf A", - "", - "lib 2", - "91d4abb 0 server-1.jar A", - "92c4abb 0 server-2.jar A", - "" - ); + Headers headers = createHeaders(driftConfigName, COVERAGE); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); + writer.writeDirectoryEntry(new DirectoryEntry("conf") + .add(addedFileEntry("server-1.conf", server1ConfHash)) + .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.writeDirectoryEntry(new DirectoryEntry("lib") + .add(addedFileEntry("server-1.jar", server1JarHash)) + .add(addedFileEntry("server-2.jar", server2JarHash))); + writer.close();
// Note that the order of the drift files is random. When the server sends a request // for files we cannot assume that the files will be in any particular order. - sender.setDriftFiles(driftFiles("2e345df", "91d4abb", "a5d8c3e", "92c4abb")); - sender.setHeaders(new Headers(driftConfigName, resourceDir.getAbsolutePath(), COVERAGE)); + sender.setDriftFiles(driftFiles(server1JarHash, server2ConfHash, server2JarHash, server1ConfHash)); + sender.setHeaders(createHeaders(driftConfigName, COVERAGE)); sender.run();
File contentDir = mkdir(changeSetDir, "content");
assertEquals(contentDir.list().length, 4, "Expected to find four files in " + contentDir.getAbsolutePath()); - assertFileCopiedToContentDir(contentDir, "2e345df"); - assertFileCopiedToContentDir(contentDir, "a5d8c3e"); - assertFileCopiedToContentDir(contentDir, "91d4abb"); - assertFileCopiedToContentDir(contentDir, "92c4abb"); + assertFileCopiedToContentDir(contentDir, server1ConfHash); + assertFileCopiedToContentDir(contentDir, server2ConfHash); + assertFileCopiedToContentDir(contentDir, server1JarHash); + assertFileCopiedToContentDir(contentDir, server2JarHash); }
@Test public void checkForFilesThatHaveBeenRemoved() throws Exception { - // It is possible that the server can request a file that has been deleted since it - // it was initially detected during drift detection. - String driftConfigName = "file-exists-test";
File confDir = mkdir(resourceDir, "conf"); - touch(new File(confDir, "server-2.conf")); + File server1Conf = createRandomFile(confDir, "server-1.conf"); + File server2Conf = createRandomFile(confDir, "server-2.conf"); + + String server1ConfHash = sha256(server1Conf); + String server2ConfHash = sha256(server2Conf);
File changeSetDir = changeSetDir(driftConfigName);
- writeChangeSet(changeSetDir, - driftConfigName, - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - "a34fcc 0 server-1.conf A", // The file is listed but does not exist - "f319d5 0 server-2.conf A", - "" - ); - - sender.setDriftFiles(driftFiles("a34fcc", "f319d5")); - sender.setHeaders(new Headers(driftConfigName, resourceDir.getAbsolutePath(), COVERAGE)); + Headers headers = createHeaders(driftConfigName, COVERAGE); + + ChangeSetWriter writer = changeSetMgr.getChangeSetWriter(resourceId(), headers); + writer.writeDirectoryEntry(new DirectoryEntry("conf") + .add(addedFileEntry("server-1.conf", server1ConfHash)) + .add(addedFileEntry("server-2.conf", server2ConfHash))); + writer.close(); + + // It is possible that the server can request a file that has been deleted since it + // it was initially detected during drift detection. + server1Conf.delete(); + + + sender.setDriftFiles(driftFiles(server1ConfHash, server2ConfHash)); + sender.setHeaders(headers); sender.run();
File contentDir = mkdir(changeSetDir, "content");
assertEquals(contentDir.list().length, 1, "Expected to find one file in " + contentDir.getAbsolutePath()); - assertFileCopiedToContentDir(contentDir, "f319d5"); + assertFileCopiedToContentDir(contentDir, server2ConfHash); }
/** @@ -157,6 +181,17 @@ public class DriftFilesSenderTest extends DriftTest { contentDir.getPath() + ". The SHA-256 hash should be used as the file name."); }
+ Headers createHeaders(String configName, DriftChangeSetCategory type) { + Headers headers = new Headers(); + headers.setResourceId(resourceId()); + headers.setDriftCofigurationId(0); + headers.setDriftConfigurationName(configName); + headers.setBasedir(resourceDir.getAbsolutePath()); + headers.setType(type); + + return headers; + } + List<DriftFile> driftFiles(String... hashes) { List<DriftFile> files = new ArrayList<DriftFile>(); for (String hash : hashes) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java.orig b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java.orig deleted file mode 100644 index f4d42e5..0000000 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftFilesSenderTest.java.orig +++ /dev/null @@ -1,144 +0,0 @@ -package org.rhq.core.pc.drift; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import org.rhq.common.drift.Headers; -import org.rhq.core.domain.drift.DriftFile; - -import static java.util.Arrays.asList; -import static org.apache.commons.io.FileUtils.touch; -import static org.apache.commons.io.IOUtils.writeLines; -import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -public class DriftFilesSenderTest extends DriftTest { - - DriftClient driftClient; - - DriftFilesSender sender; - - @BeforeMethod - public void initSender() { - driftClient = new DriftClientTestStub(); - - sender = new DriftFilesSender(); - sender.setDriftClient(driftClient); - sender.setChangeSetManager(changeSetMgr); - sender.setResourceId(resourceId()); - } - - @Test - public void sendFilesInOneDirectory() throws Exception { - String driftConfigName = "single-directory-test"; - - File confDir = mkdir(resourceDir, "conf"); - touch(new File(confDir, "server-1.conf")); - touch(new File(confDir, "server-2.conf")); - - File changeSetDir = changeSetDir(driftConfigName); - - // Each item in changeSet is listed by the line it will appear in the actual file - // in an attemp to make it more self-documenting. - writeChangeSet(changeSetDir, asList( - driftConfigName, - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - "2e345df 0 server-1.conf A", - "a5d8c3e 0 server-2.conf A", - "" - )); - - sender.setDriftFiles(driftFiles("2e345df", "a5d8c3e")); - sender.setHeaders(new Headers(driftConfigName, resourceDir.getAbsolutePath(), COVERAGE)); - sender.run(); - - File contentDir = mkdir(changeSetDir, "content"); - - assertEquals(contentDir.list().length, 2, "Expected to find two files in " + contentDir.getAbsolutePath()); - assertFileCopiedToContentDir(contentDir, "2e345df"); - assertFileCopiedToContentDir(contentDir, "a5d8c3e"); - } - - @Test - public void sendFilesInMultipleDirectories() throws Exception { - String driftConfigName = "multiple-directories-test"; - - File confDir = mkdir(resourceDir, "conf"); - File libDir = mkdir(resourceDir, "lib"); - touch(new File(confDir, "server-1.conf")); - touch(new File(confDir, "server-2.conf")); - touch(new File(libDir, "server-1.jar")); - touch(new File(libDir, "server-2.jar")); - - File changeSetDir = changeSetDir(driftConfigName); - - // Each item in changeSet is listed by the line it will appear in the actual file - // in an attemp to make it more self-documenting. - writeChangeSet(changeSetDir, asList( - driftConfigName, - resourceDir.getAbsolutePath(), - COVERAGE.code(), - "conf 2", - "2e345df 0 server-1.conf A", - "a5d8c3e 0 server-2.conf A", - "", - "lib 2", - "91d4abb 0 server-1.jar A", - "92c4abb 0 server-2.jar A", - "" - )); - - // Note that the order of the drift files is random. When the server sends a request - // for files we cannot assume that the files will be in any particular order. - sender.setDriftFiles(driftFiles("2e345df", "91d4abb", "a5d8c3e", "92c4abb")); - sender.setHeaders(new Headers(driftConfigName, resourceDir.getAbsolutePath(), COVERAGE)); - sender.run(); - - File contentDir = mkdir(changeSetDir, "content"); - - assertEquals(contentDir.list().length, 4, "Expected to find four files in " + contentDir.getAbsolutePath()); - assertFileCopiedToContentDir(contentDir, "2e345df"); - assertFileCopiedToContentDir(contentDir, "a5d8c3e"); - assertFileCopiedToContentDir(contentDir, "91d4abb"); - assertFileCopiedToContentDir(contentDir, "92c4abb"); - } - - /** - * This method only verifies that a file having a particular hash or SHA-256 has been - * copied to the specified content directory. - * - * @param contentDir The directory to which the file should have been copied - * - * @param fileHash The file hash which is expected to be the name of the file in the - * content directory. - */ - void assertFileCopiedToContentDir(File contentDir, String fileHash) { - File file = new File(contentDir, fileHash); - assertTrue(file.exists(), "Expected to find file named " + file.getName() + " in content directory " + - contentDir.getPath() + ". The SHA-256 hash should be used as the file name."); - } - - void writeChangeSet(File changeSetDir, List<String> changeSet) throws Exception { - BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(changeSetDir, - "changeset.txt"))); - writeLines(changeSet, "\n", stream); - stream.close(); - } - - List<DriftFile> driftFiles(String... hashes) { - List<DriftFile> files = new ArrayList<DriftFile>(); - for (String hash : hashes) { - files.add(new DriftFile(hash)); - } - return files; - } -} 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 98c421e..1c02b3f 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 @@ -1,3 +1,22 @@ +/* + * 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.pc.drift;
import java.io.BufferedOutputStream; @@ -5,6 +24,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; +import java.util.Random;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -16,6 +36,7 @@ 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.DriftConfigurationDefinition.BaseDirValueContext.fileSystem;
@@ -90,6 +111,11 @@ public class DriftTest { private MessageDigestGenerator digestGenerator;
/** + * Used for creating random files in {@link #createRandomFile(java.io.File, String)} + */ + private Random random = new Random(); + + /** * Deletes the base output directory (which is the name of the test class), removing * output from a previous run. The output directories (i.e., change sets and resources) * are then recreated. @@ -176,6 +202,17 @@ public class DriftTest { return digestGenerator.calcDigestString(file); }
+ protected File createRandomFile(File dir, String fileName) throws Exception { + File file = new File(dir, fileName); + FileOutputStream stream = new FileOutputStream(file); + byte[] bytes = new byte[32]; + random.nextBytes(bytes); + write(bytes, stream); + stream.close(); + + return file; + } + protected void writeChangeSet(File changeSetDir, String... changeSet) throws Exception { File changeSetFile = new File(changeSetDir, "changeset.txt"); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(changeSetFile)); @@ -201,4 +238,5 @@ public class DriftTest {
return config; } + } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java.orig b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java.orig deleted file mode 100644 index c65c7dc..0000000 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/drift/DriftTest.java.orig +++ /dev/null @@ -1,71 +0,0 @@ -package org.rhq.core.pc.drift; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FileUtils; -import org.apache.poi.util.IOUtils; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; - -import org.rhq.core.domain.drift.DriftConfiguration; -import org.rhq.core.util.MessageDigestGenerator; - -import static org.apache.commons.io.FileUtils.deleteDirectory; - -public class DriftTest { - - protected File changeSetsDir; - - protected File resourcesDir; - - protected ChangeSetManager changeSetMgr; - - private int resourceId; - - protected File resourceDir; - - private MessageDigestGenerator digestGenerator; - - @BeforeClass - public void initResourcesAndChangeSetsDirs() throws Exception { - File basedir = new File("target", getClass().getSimpleName()); - deleteDirectory(basedir); - basedir.mkdir(); - - changeSetsDir = mkdir(basedir, "changesets"); - resourcesDir = mkdir(basedir, "resources"); - - digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); - } - - @BeforeMethod - public void setUp() { - resourceDir = mkdir(resourcesDir, "resource-" + nextResourceId()); - changeSetMgr = new ChangeSetManagerImpl(changeSetsDir); - } - - protected int resourceId() { - return resourceId; - } - - protected int nextResourceId() { - return ++resourceId; - } - - protected File mkdir(File parent, String name) { - File dir = new File(parent, name); - dir.mkdirs(); - return dir; - } - - protected File changeSetDir(String driftConfigName) { - File dir = new File(new File(changeSetsDir, Integer.toString(resourceId)), driftConfigName); - dir.mkdirs(); - return dir; - } - - protected String sha256(File file) throws IOException { - return digestGenerator.calcDigestString(file); - } -} 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 816055e..989211f 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 @@ -16,6 +16,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + package org.rhq.enterprise.server.plugins.drift.mongodb;
import java.io.BufferedReader;
commit 25ce6fc4cc33141ba0473e029ab3f79969a745b2 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Aug 8 17:20:10 2011 +0200
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.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/SystemSettings.java b/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/SystemSettings.java index 172e15c..3b69c02 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/SystemSettings.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/sync/entity/SystemSettings.java @@ -19,13 +19,19 @@
package org.rhq.core.domain.sync.entity;
+import java.io.Serializable; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; import java.util.Properties; +import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlValue;
/** * A domain class representing the system settings of an RHQ installation. @@ -36,80 +42,95 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) public class SystemSettings extends AbstractExportedEntity {
- private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2L;
- // The below are copied from RHQConstants (residing in the server jar) but kept here - // so that we can provide an easy to use conversions to and from a map of values - private static final String JAASProvider = "CAM_JAAS_PROVIDER"; - private static final String JDBCJAASProvider = "JDBC"; - private static final String LDAPJAASProvider = "LDAP"; - private static final String LDAPFactory = "CAM_LDAP_NAMING_FACTORY_INITIAL"; - private static final String LDAPUrl = "CAM_LDAP_NAMING_PROVIDER_URL"; - private static final String LDAPProtocol = "CAM_LDAP_PROTOCOL"; - private static final String LDAPLoginProperty = "CAM_LDAP_LOGIN_PROPERTY"; - private static final String LDAPFilter = "CAM_LDAP_FILTER"; - private static final String LDAPGroupFilter = "CAM_LDAP_GROUP_FILTER"; - private static final String LDAPGroupMember = "CAM_LDAP_GROUP_MEMBER"; - private static final String LDAPBaseDN = "CAM_LDAP_BASE_DN"; - private static final String LDAPBindDN = "CAM_LDAP_BIND_DN"; - private static final String LDAPBindPW = "CAM_LDAP_BIND_PW"; - private static final String BaseURL = "CAM_BASE_URL"; - private static final String AgentMaxQuietTimeAllowed = "AGENT_MAX_QUIET_TIME_ALLOWED"; - private static final String EnableAgentAutoUpdate = "ENABLE_AGENT_AUTO_UPDATE"; - private static final String EnableDebugMode = "ENABLE_DEBUG_MODE"; - private static final String EnableExperimentalFeatures = "ENABLE_EXPERIMENTAL_FEATURES"; - private static final String DataPurge1Hour = "CAM_DATA_PURGE_1H"; - private static final String DataPurge6Hour = "CAM_DATA_PURGE_6H"; - private static final String DataPurge1Day = "CAM_DATA_PURGE_1D"; - private static final String DataMaintenance = "CAM_DATA_MAINTENANCE"; - private static final String DataReindex = "DATA_REINDEX_NIGHTLY"; - private static final String RtDataPurge = "RT_DATA_PURGE"; - private static final String AlertPurge = "ALERT_PURGE"; - private static final String EventPurge = "EVENT_PURGE"; - private static final String TraitPurge = "TRAIT_PURGE"; - private static final String AvailabilityPurge = "AVAILABILITY_PURGE"; - private static final String BaselineFrequency = "CAM_BASELINE_FREQUENCY"; - private static final String BaselineDataSet = "CAM_BASELINE_DATASET"; + @XmlAccessorType(XmlAccessType.FIELD) + public static class Entry implements Serializable {
- //this is left out from the export, because we have no way of editing this in the UI - //private static final String AllowResourceGenericPropertiesUpgrade = "RESOURCE_GENERIC_PROPERTIES_UPGRADE"; - - private String jAASProvider = ""; - private String jDBCJAASProvider = ""; - private String lDAPJAASProvider = ""; - private String lDAPFactory = ""; - private String lDAPUrl = ""; - private String lDAPProtocol = ""; - private String lDAPLoginProperty = ""; - private String lDAPFilter = ""; - private String lDAPGroupFilter = ""; - private String lDAPGroupMember = ""; - private String lDAPBaseDN = ""; - private String lDAPBindDN = ""; - private String lDAPBindPW = ""; - private String baseURL = ""; - private String agentMaxQuietTimeAllowed = ""; - private String enableAgentAutoUpdate = ""; - private String enableDebugMode = ""; - private String enableExperimentalFeatures = ""; - private String dataPurge1Hour = ""; - private String dataPurge6Hour = ""; - private String dataPurge1Day = ""; - private String dataMaintenance = ""; - private String dataReindex = ""; - private String rtDataPurge = ""; - private String alertPurge = ""; - private String eventPurge = ""; - private String traitPurge = ""; - private String availabilityPurge = ""; - private String baselineFrequency = ""; - private String baselineDataSet = ""; + private static final long serialVersionUID = 1L;
- //this is left out from the export, because we have no way of editing this in the UI - //private String allowresourceGenericPropertiesUpgrade; + @XmlAttribute + private String key; + + @XmlValue + private String value; + + public Entry() { + + } + + public Entry(String key, String value) { + this.key = key; + this.value = value; + } + + /** + * @return the key + */ + public String getKey() { + return key; + } + + /** + * @param key the key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (obj == null) { + return false; + } + + if (getClass() != obj.getClass()) { + return false; + } + + Entry other = (Entry) obj; + + return key.equals(other.getKey()); + } + + @Override + public String toString() { + return key + " = '" + value + "'"; + } + } + + @XmlElement(name = "entry") + private Set<Entry> entries;
public SystemSettings() { setReferencedEntityId(0); + entries = new HashSet<Entry>(); }
public SystemSettings(Map<String, String> settings) { @@ -120,49 +141,21 @@ public class SystemSettings extends AbstractExportedEntity { public SystemSettings(Properties settings) { this(); HashMap<String, String> map = new HashMap<String, String>(); - for(Map.Entry<Object, Object> entry : settings.entrySet()) { + for (Map.Entry<Object, Object> entry : settings.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); map.put(key, value); } - + initFrom(map); } - + public Map<String, String> toMap() { - HashMap<String, String> settings = new HashMap<String, String>(); - - settings.put(AgentMaxQuietTimeAllowed, agentMaxQuietTimeAllowed); - settings.put(AlertPurge, alertPurge); - settings.put(AvailabilityPurge, availabilityPurge); - settings.put(BaselineDataSet, baselineDataSet); - settings.put(BaselineFrequency, baselineFrequency); - settings.put(BaseURL, baseURL); - settings.put(DataMaintenance, dataMaintenance); - settings.put(DataPurge1Day, dataPurge1Day); - settings.put(DataPurge1Hour, dataPurge1Hour); - settings.put(DataPurge6Hour, dataPurge6Hour); - settings.put(DataReindex, dataReindex); - settings.put(EnableAgentAutoUpdate, enableAgentAutoUpdate); - settings.put(EnableDebugMode, enableDebugMode); - settings.put(EnableExperimentalFeatures, enableExperimentalFeatures); - settings.put(EventPurge, eventPurge); - settings.put(JAASProvider, jAASProvider); - settings.put(JDBCJAASProvider, jDBCJAASProvider); - settings.put(LDAPBaseDN, lDAPBaseDN); - settings.put(LDAPBindDN, lDAPBindDN); - settings.put(LDAPBindPW, lDAPBindPW); - settings.put(LDAPFactory, lDAPFactory); - settings.put(LDAPFilter, lDAPFilter); - settings.put(LDAPGroupFilter, lDAPGroupFilter); - settings.put(LDAPGroupMember, lDAPGroupMember); - settings.put(LDAPJAASProvider, lDAPJAASProvider); - settings.put(LDAPLoginProperty, lDAPLoginProperty); - settings.put(LDAPProtocol, lDAPProtocol); - settings.put(LDAPUrl, lDAPUrl); - settings.put(RtDataPurge, rtDataPurge); - settings.put(TraitPurge, traitPurge); - //settings.put(AllowResourceGenericPropertiesUpgrade, allowResourceGenericPropertiesUpgrade); + HashMap<String, String> settings = new HashMap<String, String>(); + + for(Entry e : entries) { + settings.put(e.getKey(), e.getValue()); + }
return settings; } @@ -172,498 +165,16 @@ public class SystemSettings extends AbstractExportedEntity { ret.putAll(toMap()); return ret; } - - public void initFrom(Map<String, String> settings) { - agentMaxQuietTimeAllowed = settings.get(AgentMaxQuietTimeAllowed); - alertPurge = settings.get(AlertPurge); - availabilityPurge = settings.get(AvailabilityPurge); - baselineDataSet = settings.get(BaselineDataSet); - baselineFrequency = settings.get(BaselineFrequency); - baseURL = settings.get(BaseURL); - dataMaintenance = settings.get(DataMaintenance); - dataPurge1Day = settings.get(DataPurge1Day); - dataPurge1Hour = settings.get(DataPurge1Hour); - dataPurge6Hour = settings.get(DataPurge6Hour); - dataReindex = settings.get(DataReindex); - enableAgentAutoUpdate = settings.get(EnableAgentAutoUpdate); - enableDebugMode = settings.get(EnableDebugMode); - enableExperimentalFeatures = settings.get(EnableExperimentalFeatures); - eventPurge = settings.get(EventPurge); - jAASProvider = settings.get(JAASProvider); - jDBCJAASProvider = settings.get(JDBCJAASProvider); - lDAPBaseDN = settings.get(LDAPBaseDN); - lDAPBindDN = settings.get(LDAPBindDN); - lDAPBindPW = settings.get(LDAPBindPW); - lDAPFactory = settings.get(LDAPFactory); - lDAPFilter = settings.get(LDAPFilter); - lDAPGroupFilter = settings.get(LDAPGroupFilter); - lDAPGroupMember = settings.get(LDAPGroupMember); - lDAPJAASProvider = settings.get(LDAPJAASProvider); - lDAPLoginProperty = settings.get(LDAPLoginProperty); - lDAPProtocol = settings.get(LDAPProtocol); - lDAPUrl = settings.get(LDAPUrl); - rtDataPurge = settings.get(RtDataPurge); - traitPurge = settings.get(TraitPurge); - //allowresourceGenericPropertiesUpgrade = settings.get(AllowResourceGenericPropertiesUpgrade); - } - - /** - * @return the jAASProvider - */ - public String getJAASProvider() { - return jAASProvider; - } - - /** - * @param jAASProvider the jAASProvider to set - */ - public void setJAASProvider(String jAASProvider) { - this.jAASProvider = jAASProvider; - } - - /** - * @return the jDBCJAASProvider - */ - public String getJDBCJAASProvider() { - return jDBCJAASProvider; - } - - /** - * @param jDBCJAASProvider the jDBCJAASProvider to set - */ - public void setJDBCJAASProvider(String jDBCJAASProvider) { - this.jDBCJAASProvider = jDBCJAASProvider; - } - - /** - * @return the lDAPJAASProvider - */ - public String getLDAPJAASProvider() { - return lDAPJAASProvider; - } - - /** - * @param lDAPJAASProvider the lDAPJAASProvider to set - */ - public void setLDAPJAASProvider(String lDAPJAASProvider) { - this.lDAPJAASProvider = lDAPJAASProvider; - } - - /** - * @return the lDAPFactory - */ - public String getLDAPFactory() { - return lDAPFactory; - } - - /** - * @param lDAPFactory the lDAPFactory to set - */ - public void setLDAPFactory(String lDAPFactory) { - this.lDAPFactory = lDAPFactory; - } - - /** - * @return the lDAPUrl - */ - public String getLDAPUrl() { - return lDAPUrl; - } - - /** - * @param lDAPUrl the lDAPUrl to set - */ - public void setLDAPUrl(String lDAPUrl) { - this.lDAPUrl = lDAPUrl; - } - - /** - * @return the lDAPProtocol - */ - public String getLDAPProtocol() { - return lDAPProtocol; - } - - /** - * @param lDAPProtocol the lDAPProtocol to set - */ - public void setLDAPProtocol(String lDAPProtocol) { - this.lDAPProtocol = lDAPProtocol; - } - - /** - * @return the lDAPLoginProperty - */ - public String getLDAPLoginProperty() { - return lDAPLoginProperty; - } - - /** - * @param lDAPLoginProperty the lDAPLoginProperty to set - */ - public void setLDAPLoginProperty(String lDAPLoginProperty) { - this.lDAPLoginProperty = lDAPLoginProperty; - } - - /** - * @return the lDAPFilter - */ - public String getLDAPFilter() { - return lDAPFilter; - } - - /** - * @param lDAPFilter the lDAPFilter to set - */ - public void setLDAPFilter(String lDAPFilter) { - this.lDAPFilter = lDAPFilter; - } - - /** - * @return the lDAPGroupFilter - */ - public String getLDAPGroupFilter() { - return lDAPGroupFilter; - } - - /** - * @param lDAPGroupFilter the lDAPGroupFilter to set - */ - public void setLDAPGroupFilter(String lDAPGroupFilter) { - this.lDAPGroupFilter = lDAPGroupFilter; - } - - /** - * @return the lDAPGroupMember - */ - public String getLDAPGroupMember() { - return lDAPGroupMember; - } - - /** - * @param lDAPGroupMember the lDAPGroupMember to set - */ - public void setLDAPGroupMember(String lDAPGroupMember) { - this.lDAPGroupMember = lDAPGroupMember; - } - - /** - * @return the lDAPBaseDN - */ - public String getLDAPBaseDN() { - return lDAPBaseDN; - } - - /** - * @param lDAPBaseDN the lDAPBaseDN to set - */ - public void setLDAPBaseDN(String lDAPBaseDN) { - this.lDAPBaseDN = lDAPBaseDN; - } - - /** - * @return the lDAPBindDN - */ - public String getLDAPBindDN() { - return lDAPBindDN; - } - - /** - * @param lDAPBindDN the lDAPBindDN to set - */ - public void setLDAPBindDN(String lDAPBindDN) { - this.lDAPBindDN = lDAPBindDN; - } - - /** - * @return the lDAPBindPW - */ - public String getLDAPBindPW() { - return lDAPBindPW; - } - - /** - * @param lDAPBindPW the lDAPBindPW to set - */ - public void setLDAPBindPW(String lDAPBindPW) { - this.lDAPBindPW = lDAPBindPW; - } - - /** - * @return the baseURL - */ - public String getBaseURL() { - return baseURL; - } - - /** - * @param baseURL the baseURL to set - */ - public void setBaseURL(String baseURL) { - this.baseURL = baseURL; - } - - /** - * @return the agentMaxQuietTimeAllowed - */ - public String getAgentMaxQuietTimeAllowed() { - return agentMaxQuietTimeAllowed; - } - - /** - * @param agentMaxQuietTimeAllowed the agentMaxQuietTimeAllowed to set - */ - public void setAgentMaxQuietTimeAllowed(String agentMaxQuietTimeAllowed) { - this.agentMaxQuietTimeAllowed = agentMaxQuietTimeAllowed; - } - - /** - * @return the enableAgentAutoUpdate - */ - public String getEnableAgentAutoUpdate() { - return enableAgentAutoUpdate; - } - - /** - * @param enableAgentAutoUpdate the enableAgentAutoUpdate to set - */ - public void setEnableAgentAutoUpdate(String enableAgentAutoUpdate) { - this.enableAgentAutoUpdate = enableAgentAutoUpdate; - } - - /** - * @return the enableDebugMode - */ - public String getEnableDebugMode() { - return enableDebugMode; - }
- /** - * @param enableDebugMode the enableDebugMode to set - */ - public void setEnableDebugMode(String enableDebugMode) { - this.enableDebugMode = enableDebugMode; - } - - /** - * @return the enableExperimentalFeatures - */ - public String getEnableExperimentalFeatures() { - return enableExperimentalFeatures; - } - - /** - * @param enableExperimentalFeatures the enableExperimentalFeatures to set - */ - public void setEnableExperimentalFeatures(String enableExperimentalFeatures) { - this.enableExperimentalFeatures = enableExperimentalFeatures; - } - - /** - * @return the dataPurge1Hour - */ - public String getDataPurge1Hour() { - return dataPurge1Hour; - } - - /** - * @param dataPurge1Hour the dataPurge1Hour to set - */ - public void setDataPurge1Hour(String dataPurge1Hour) { - this.dataPurge1Hour = dataPurge1Hour; - } - - /** - * @return the dataPurge6Hour - */ - public String getDataPurge6Hour() { - return dataPurge6Hour; - } - - /** - * @param dataPurge6Hour the dataPurge6Hour to set - */ - public void setDataPurge6Hour(String dataPurge6Hour) { - this.dataPurge6Hour = dataPurge6Hour; - } - - /** - * @return the dataPurge1Day - */ - public String getDataPurge1Day() { - return dataPurge1Day; - } - - /** - * @param dataPurge1Day the dataPurge1Day to set - */ - public void setDataPurge1Day(String dataPurge1Day) { - this.dataPurge1Day = dataPurge1Day; - } - - /** - * @return the dataMaintenance - */ - public String getDataMaintenance() { - return dataMaintenance; - } - - /** - * @param dataMaintenance the dataMaintenance to set - */ - public void setDataMaintenance(String dataMaintenance) { - this.dataMaintenance = dataMaintenance; - } - - /** - * @return the dataReindex - */ - public String getDataReindex() { - return dataReindex; - } - - /** - * @param dataReindex the dataReindex to set - */ - public void setDataReindex(String dataReindex) { - this.dataReindex = dataReindex; - } - - /** - * @return the rtDataPurge - */ - public String getRtDataPurge() { - return rtDataPurge; - } - - /** - * @param rtDataPurge the rtDataPurge to set - */ - public void setRtDataPurge(String rtDataPurge) { - this.rtDataPurge = rtDataPurge; - } - - /** - * @return the alertPurge - */ - public String getAlertPurge() { - return alertPurge; - } - - /** - * @param alertPurge the alertPurge to set - */ - public void setAlertPurge(String alertPurge) { - this.alertPurge = alertPurge; - } - - /** - * @return the eventPurge - */ - public String getEventPurge() { - return eventPurge; - } - - /** - * @param eventPurge the eventPurge to set - */ - public void setEventPurge(String eventPurge) { - this.eventPurge = eventPurge; - } - - /** - * @return the traitPurge - */ - public String getTraitPurge() { - return traitPurge; - } - - /** - * @param traitPurge the traitPurge to set - */ - public void setTraitPurge(String traitPurge) { - this.traitPurge = traitPurge; - } - - /** - * @return the availabilityPurge - */ - public String getAvailabilityPurge() { - return availabilityPurge; - } - - /** - * @param availabilityPurge the availabilityPurge to set - */ - public void setAvailabilityPurge(String availabilityPurge) { - this.availabilityPurge = availabilityPurge; - } - - /** - * @return the baselineFrequency - */ - public String getBaselineFrequency() { - return baselineFrequency; - } - - /** - * @param baselineFrequency the baselineFrequency to set - */ - public void setBaselineFrequency(String baselineFrequency) { - this.baselineFrequency = baselineFrequency; - } - - /** - * @return the baselineDataSet - */ - public String getBaselineDataSet() { - return baselineDataSet; + public void initFrom(Map<String, String> settings) { + entries.clear(); + for(Map.Entry<String, String> e : settings.entrySet()) { + entries.add(new Entry(e.getKey(), e.getValue())); + } }
- /** - * @param baselineDataSet the baselineDataSet to set - */ - public void setBaselineDataSet(String baselineDataSet) { - this.baselineDataSet = baselineDataSet; - } - @Override public String toString() { - StringBuilder bld = new StringBuilder("SystemSettings["); - - bld.append("JAASProvider='").append(jAASProvider); - bld.append("', JDBCJAASProvider='").append(jDBCJAASProvider); - bld.append("', LDAPJAASProvider='").append(lDAPJAASProvider); - bld.append("', LDAPFactory='").append(lDAPFactory); - bld.append("', LDAPUrl='").append(lDAPUrl); - bld.append("', LDAPProtocol='").append(lDAPProtocol); - bld.append("', LDAPLoginProperty='").append(lDAPLoginProperty); - bld.append("', LDAPFilter='").append(lDAPFilter); - bld.append("', LDAPGroupFilter='").append(lDAPGroupFilter); - bld.append("', LDAPGroupMember='").append(lDAPGroupMember); - bld.append("', LDAPBaseDN='").append(lDAPBaseDN); - bld.append("', LDAPBindDN='").append(lDAPBindDN); - bld.append("', LDAPBindPW='").append(lDAPBindPW); - bld.append("', BaseURL='").append(baseURL); - bld.append("', AgentMaxQuietTimeAllowed='").append(agentMaxQuietTimeAllowed); - bld.append("', EnableAgentAutoUpdate='").append(enableAgentAutoUpdate); - bld.append("', EnableDebugMode='").append(enableDebugMode); - bld.append("', EnableExperimentalFeatures='").append(enableExperimentalFeatures); - bld.append("', DataPurge1Hour='").append(dataPurge1Hour); - bld.append("', DataPurge6Hour='").append(dataPurge6Hour); - bld.append("', DataPurge1Day='").append(dataPurge1Day); - bld.append("', DataMaintenance='").append(dataMaintenance); - bld.append("', DataReindex='").append(dataReindex); - bld.append("', RtDataPurge='").append(rtDataPurge); - bld.append("', AlertPurge='").append(alertPurge); - bld.append("', EventPurge='").append(eventPurge); - bld.append("', TraitPurge='").append(traitPurge); - bld.append("', AvailabilityPurge='").append(availabilityPurge); - bld.append("', BaselineFrequency='").append(baselineFrequency); - bld.append("', BaselineDataSet='").append(baselineDataSet); - - bld.append("']"); - - return bld.toString(); + return "SystemSettings" + entries; } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java index 78134bc..2bd48b3 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/sync/importers/SystemSettingsImporter.java @@ -19,7 +19,12 @@
package org.rhq.enterprise.server.sync.importers;
-import javax.persistence.EntityManager; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; @@ -35,7 +40,6 @@ import org.rhq.core.domain.sync.entity.SystemSettings; import org.rhq.enterprise.server.sync.ExportReader; import org.rhq.enterprise.server.sync.NoSingleEntity; import org.rhq.enterprise.server.system.SystemManagerLocal; -import org.rhq.enterprise.server.util.LookupUtil;
/** * @@ -64,37 +68,11 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe public ConfigurationDefinition getImportConfigurationDefinition() { ConfigurationDefinition def = new ConfigurationDefinition("SystemSettingsConfiguration", null);
- addSwitchToConfigDef(def, "importJAASProvider", false); - addSwitchToConfigDef(def, "importJDBCJAASProvider", false); - addSwitchToConfigDef(def, "importLDAPJAASProvider", false); - addSwitchToConfigDef(def, "imoprtLDAPFactory", true); - addSwitchToConfigDef(def, "importLDAPUrl", false); - addSwitchToConfigDef(def, "importLDAPProtocol", false); - addSwitchToConfigDef(def, "imoprtLDAPLoginProperty", false); - addSwitchToConfigDef(def, "importLDAPFilter", false); - addSwitchToConfigDef(def, "importLDAPGroupFilter", false); - addSwitchToConfigDef(def, "importLDAPGroupMember", false); - addSwitchToConfigDef(def, "importLDAPBaseDN", false); - addSwitchToConfigDef(def, "importLDAPBindDN", false); - addSwitchToConfigDef(def, "importLDAPBindPW", false); - addSwitchToConfigDef(def, "importBaseURL", false); - addSwitchToConfigDef(def, "importAgentMaxQuietTimeAllowed", true); - addSwitchToConfigDef(def, "importEnableAgentAutoUpdate", true); - addSwitchToConfigDef(def, "importEnableDebugMode", true); - addSwitchToConfigDef(def, "importEnableExperimentalFeatures", true); - addSwitchToConfigDef(def, "importDataPurge1Hour", true); - addSwitchToConfigDef(def, "importDataPurge6Hour", true); - addSwitchToConfigDef(def, "importDataPurge1Day", true); - addSwitchToConfigDef(def, "importDataMaintenance", true); - addSwitchToConfigDef(def, "importDataReindex", true); - addSwitchToConfigDef(def, "imoprtRtDataPurge", true); - addSwitchToConfigDef(def, "importAlertPurge", true); - addSwitchToConfigDef(def, "importEventPurge", true); - addSwitchToConfigDef(def, "importTraitPurge", true); - addSwitchToConfigDef(def, "importAvailabilityPurge", true); - addSwitchToConfigDef(def, "importBaselineFrequency", true); - addSwitchToConfigDef(def, "importBaselineDataSet", true); - + PropertyDefinitionSimple props = new PropertyDefinitionSimple("propertiesToImport", "The names of the properties that should be imported. Note that these are the INTERNAL names as used in the RHQ database", true, PropertySimpleType.STRING); + props.setDefaultValue("AgentMaxQuietTimeAllowed, EnableAgentAutoUpdate, EnableDebugMode, EnableExperimentalFeatures, DataPurge1Hour, DataPurge6Hour, " + + "DataPurge1Day, DataMaintenance, DataReindex, RtDataPurge, AlertPurge, EventPurge, TraitPurge, AvailabilityPurge, BaselineFrequence, BaselineDataSet"); + def.put(props); + ConfigurationUtility.initializeDefaultTemplate(def);
return def; @@ -112,8 +90,24 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe
@Override public void update(NoSingleEntity entity, SystemSettings exportedEntity) throws Exception { - //TODO take the configuration into account - systemManager.setSystemConfiguration(subject, exportedEntity.toProperties(), true); + Properties props = exportedEntity.toProperties(); + + Set<String> propsToImport = getSettingNamesConfiguredForImport(importConfiguration); + + Set<String> propsToRemove = new HashSet<String>(); + + for(Object k : props.keySet()) { + String key = (String) k; + if (!propsToImport.contains(key)) { + propsToRemove.add(key); + } + } + + for(String p : propsToRemove) { + props.remove(p); + } + + systemManager.setSystemConfiguration(subject, props, true); }
@Override @@ -128,10 +122,16 @@ public class SystemSettingsImporter implements Importer<NoSingleEntity, SystemSe @Override public void finishImport() { } - - private void addSwitchToConfigDef(ConfigurationDefinition def, String name, boolean defaultValue) { - PropertyDefinitionSimple prop = new PropertyDefinitionSimple(name, null, true, PropertySimpleType.BOOLEAN); - prop.setDefaultValue(Boolean.toString(defaultValue)); - def.put(prop); + + private Set<String> getSettingNamesConfiguredForImport(Configuration importConfiguration) { + String settingsToImport = importConfiguration.getSimpleValue("propertiesToImport", null); + + if (settingsToImport == null) { + return Collections.emptySet(); + } else { + String[] vals = settingsToImport.split("\s*,\s*"); + + return new HashSet<String>(Arrays.asList(vals)); + } } } diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java index e5cd727..30ba4ec 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/sync/test/SystemSettingsExporterTest.java @@ -20,8 +20,8 @@ package org.rhq.enterprise.server.sync.test;
import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue;
+import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -53,11 +53,6 @@ import org.rhq.core.domain.sync.entity.SystemSettings; import org.rhq.enterprise.server.sync.ExportingInputStream; import org.rhq.enterprise.server.sync.Synchronizer; import org.rhq.enterprise.server.sync.SystemSettingsSynchronizer; -import org.rhq.enterprise.server.sync.exporters.Exporter; -import org.rhq.enterprise.server.sync.exporters.MetricTemplateExporter; -import org.rhq.enterprise.server.sync.exporters.SystemSettingsExporter; -import org.rhq.enterprise.server.sync.importers.SystemSettingsImporter; -import org.rhq.enterprise.server.sync.validators.ConsistencyValidator; import org.rhq.enterprise.server.system.InvalidSystemConfigurationException; import org.rhq.enterprise.server.system.SystemManagerLocal;
@@ -71,10 +66,7 @@ public class SystemSettingsExporterTest {
private static final Log LOG = LogFactory.getLog(MetricTemplateExporterTest.class);
- private SystemManagerLocal systemManagerStub = null; - - - /*new SystemManagerLocal() { + private SystemManagerLocal systemManagerStub = new SystemManagerLocal() {
@Override public long vacuumAppdef(Subject whoami) { @@ -133,9 +125,9 @@ public class SystemSettingsExporterTest {
@Override public Properties getSystemConfiguration(Subject subject) { - SystemSettings settings = new SystemSettings(); - - settings.setBaseURL("herethereandeverywhere"); + HashMap<String, String> values = new HashMap<String, String>(); + values.put("BaseURL", "herethereandeverywhere"); + SystemSettings settings = new SystemSettings(values);
return settings.toProperties(); } @@ -168,9 +160,16 @@ public class SystemSettingsExporterTest { public long analyze(Subject whoami) { return 0; } - };*/
- private void testCanExport() throws Exception { + @Override + public org.rhq.core.domain.common.composite.SystemSettings getSystemSettings(Subject subject) { + return null; + } + + + }; + + public void testCanExport() throws Exception { SystemSettingsSynchronizer exporter = new SystemSettingsSynchronizer(systemManagerStub);
Set<Synchronizer<?, ?>> exporters = new HashSet<Synchronizer<?, ?>>(); @@ -178,11 +177,11 @@ public class SystemSettingsExporterTest {
InputStream eis = new ExportingInputStream(exporters, new HashMap<String, ExporterMessages>(), 65536, false);
- // String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); - // - // LOG.warn("Export contents:\n" + exportContents); - // - // eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8")); + String exportContents = readAll(new InputStreamReader(eis, "UTF-8")); + + LOG.warn("Export contents:\n" + exportContents); + + eis = new ByteArrayInputStream(exportContents.getBytes("UTF-8"));
// <?xml version="1.0" ?> // <configuration-export> @@ -190,36 +189,7 @@ public class SystemSettingsExporterTest { // <entity> // <data> // <systemSettings referencedEntityId="0"> -// <jAASProvider></jAASProvider> -// <jDBCJAASProvider></jDBCJAASProvider> -// <lDAPJAASProvider></lDAPJAASProvider> -// <lDAPFactory></lDAPFactory> -// <lDAPUrl></lDAPUrl> -// <lDAPProtocol></lDAPProtocol> -// <lDAPLoginProperty></lDAPLoginProperty> -// <lDAPFilter></lDAPFilter> -// <lDAPGroupFilter></lDAPGroupFilter> -// <lDAPGroupMember></lDAPGroupMember> -// <lDAPBaseDN></lDAPBaseDN> -// <lDAPBindDN></lDAPBindDN> -// <lDAPBindPW></lDAPBindPW> -// <baseURL>herethereandeverywhere</baseURL> -// <agentMaxQuietTimeAllowed></agentMaxQuietTimeAllowed> -// <enableAgentAutoUpdate></enableAgentAutoUpdate> -// <enableDebugMode></enableDebugMode> -// <enableExperimentalFeatures></enableExperimentalFeatures> -// <dataPurge1Hour></dataPurge1Hour> -// <dataPurge6Hour></dataPurge6Hour> -// <dataPurge1Day></dataPurge1Day> -// <dataMaintenance></dataMaintenance> -// <dataReindex></dataReindex> -// <rtDataPurge></rtDataPurge> -// <alertPurge></alertPurge> -// <eventPurge></eventPurge> -// <traitPurge></traitPurge> -// <availabilityPurge></availabilityPurge> -// <baselineFrequency></baselineFrequency> -// <baselineDataSet></baselineDataSet> +// <entry key="BaseUrl">herethereandeverywhere</entry> // </systemSettings> // </data> // </entity> @@ -245,17 +215,15 @@ public class SystemSettingsExporterTest {
assertEquals(m.getAttribute("referencedEntityId"), "0", "Unexpected referencedEntityId value");
- //i'm too lazy to repeat the check for the presence of all 30 properties in the export file - //let's just count them. - assertEquals(m.getChildNodes().getLength(), 30, "Unexpected number of properties in the system settings."); + assertEquals(m.getChildNodes().getLength(), 1, "Unexpected number of properties in the system settings.");
- //but let's check that the explicitly assigned value to baseURL has been exported. - NodeList baseURLs = m.getElementsByTagName("baseURL"); + NodeList baseURLs = m.getElementsByTagName("entry");
assertEquals(baseURLs.getLength(), 1, "Unexpected number of baseURL elements in the system settings export.");
Element baseURL = (Element) baseURLs.item(0);
+ assertEquals(baseURL.getAttribute("key"), "BaseURL"); assertEquals(baseURL.getTextContent(), "herethereandeverywhere", "Unexpected value of baseURL"); } }
commit 34621517feb36e8548fd687a80da51d1eedd49b0 Author: John Sanda jsanda@redhat.com Date: Fri Aug 5 13:39:27 2011 -0400
Adding TODO comment
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java index 1b29177..7e6e7b8 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java @@ -43,6 +43,10 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> { Query<MongoDBChangeSet> query = createQuery();
if (criteria.getFilterId() != null) { + // TODO use the $slice operator + // The slice operator will allow us to return only the requested entry in the + // change set document. Morphia does not yet support the $slice operator so + // we will hae to drop down to the mongo driver to issue a query. String[] ids = criteria.getFilterId().split(":"); ObjectId changeSetId = new ObjectId(ids[0]); query.field("id").equal(changeSetId);
commit adcebbe49e0c7c8ca347f91d591e5f4bfe3e1467 Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 23:00:26 2011 -0400
Support filtering on drift id in mongodb drift plugin
There is stil a bit of work to do. We can use mongo's $slice operator to limit the entries returned in the change set.
diff --git a/modules/enterprise/binding/src/test/java/org/rhq/bindings/FakeRhqFacade.java b/modules/enterprise/binding/src/test/java/org/rhq/bindings/FakeRhqFacade.java index 6060d9e..4fb2364 100644 --- a/modules/enterprise/binding/src/test/java/org/rhq/bindings/FakeRhqFacade.java +++ b/modules/enterprise/binding/src/test/java/org/rhq/bindings/FakeRhqFacade.java @@ -34,7 +34,6 @@ import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; import org.rhq.enterprise.server.discovery.DiscoveryBossRemote; import org.rhq.enterprise.server.drift.DriftManagerRemote; -import org.rhq.enterprise.server.drift.DriftServerRemote; import org.rhq.enterprise.server.event.EventManagerRemote; import org.rhq.enterprise.server.install.remote.RemoteInstallManagerRemote; import org.rhq.enterprise.server.measurement.AvailabilityManagerRemote; @@ -180,10 +179,6 @@ public class FakeRhqFacade implements RhqFacade { return null; }
- public DriftServerRemote getDriftServer() { - return null; - } - @Override public DriftManagerRemote getDriftManager() { return null; diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java index 26ae5b7..1b29177 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java @@ -42,6 +42,16 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> { public List<MongoDBChangeSet> findByDriftCriteria(DriftCriteria criteria) { Query<MongoDBChangeSet> query = createQuery();
+ if (criteria.getFilterId() != null) { + String[] ids = criteria.getFilterId().split(":"); + ObjectId changeSetId = new ObjectId(ids[0]); + query.field("id").equal(changeSetId); + + // If the id filter is set, there is no need to process other filters since the id + // filter uniquely identifies both the change set and the drift entry. + return query.asList(); + } + if (criteria.getFilterResourceIds() != null && criteria.getFilterResourceIds().length > 0) { query.field("resourceId").in(asList(criteria.getFilterResourceIds())); } 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 46804ab..e7dd05d 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 @@ -1,3 +1,22 @@ +/* + * 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.server.plugins.drift.mongodb.dao;
import java.util.List; @@ -26,6 +45,7 @@ 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.assertNotNull; +import static org.testng.AssertJUnit.assertEquals;
public class ChangeSetDAOTest {
@@ -177,6 +197,49 @@ public class ChangeSetDAOTest { expected, actual, ignore); }
+ @Test(enabled = ENABLED) + public void findByDriftCriteriaWithCategoriesFilter() throws Exception { + MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1).add(new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED)); + dao.save(c1); + + MongoDBChangeSet c2 = createChangeSet(DRIFT, 2, 1, 1) + .add(new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED)) + .add(new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED)); + dao.save(c2); + + MongoDBChangeSet c3 = createChangeSet(DRIFT, 3, 1, 1).add(new MongoDBChangeSetEntry("c1-1.txt", FILE_REMOVED)); + dao.save(c3); + + GenericDriftCriteria criteria = new GenericDriftCriteria(); + criteria.addFilterCategories(FILE_CHANGED, FILE_REMOVED); + + List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria); + List<MongoDBChangeSet> expected = asList(c2, c3); + + String ignore = "drifts"; + assertCollectionMatchesNoOrder("Failed to find change sets by drift criteria with categories filter.", + expected, actual, ignore); + } + + @Test(enabled = ENABLED) + public void findByDriftCriteriaWithIdFilter() throws Exception { + MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1); + MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED); + c1.add(entry); + + dao.save(c1); + + GenericDriftCriteria criteria = new GenericDriftCriteria(); + criteria.addFilterId(entry.getId()); + + List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria); + List<MongoDBChangeSet> expected = asList(c1); + + assertEquals("Expected to get back only one change set when searching by drift criteria with id filter.", + 1, actual.size()); + assertChangeSetMatches("Failed to find change set by drift criteria with id filter.", c1, actual.get(0)); + } + /** * This method first checks that the actual change set is not null. It then performs a * property-wise comparison against the expected change set using @@ -219,9 +282,6 @@ public class ChangeSetDAOTest { return changeSet; }
-// MongoDBChangeSetEntry createEntry(String path, DriftCategory category) { -// MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(path, category); -// // TODO init oldFile -// } +
}
commit 7b9d5d4e4cb5a3fee79f01256c47096d044c2160 Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 21:02:01 2011 -0400
Adding initial support for mongodb drift criteria
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 2a0fd89..816055e 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 @@ -64,6 +64,8 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; import org.rhq.enterprise.server.resource.ResourceManagerLocal;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; + public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
//private final Log log = LogFactory.getLog(MongoDBDriftServer.class); diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java index 2f263f0..26ae5b7 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java @@ -19,18 +19,38 @@
package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
+import java.util.List; + import com.google.code.morphia.Morphia; import com.google.code.morphia.dao.BasicDAO; +import com.google.code.morphia.query.Query; import com.mongodb.Mongo;
import org.bson.types.ObjectId;
+import org.rhq.core.domain.criteria.DriftCriteria; import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import static java.util.Arrays.asList; + public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
public ChangeSetDAO(Morphia morphia, Mongo mongo, String db) { super(mongo, morphia, db); }
+ public List<MongoDBChangeSet> findByDriftCriteria(DriftCriteria criteria) { + Query<MongoDBChangeSet> query = createQuery(); + + if (criteria.getFilterResourceIds() != null && criteria.getFilterResourceIds().length > 0) { + query.field("resourceId").in(asList(criteria.getFilterResourceIds())); + } + + if (criteria.getFilterCategories() != null && criteria.getFilterCategories().length > 0) { + query.field("files.category").in(asList(criteria.getFilterCategories())); + } + + return query.asList(); + } + } 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 2604350..46804ab 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 @@ -1,5 +1,7 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
+import java.util.List; + import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.google.code.morphia.query.Query; @@ -9,11 +11,16 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test;
+import org.rhq.core.domain.criteria.GenericDriftCriteria; +import org.rhq.core.domain.drift.DriftChangeSetCategory; import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet; import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry; import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
+import static java.util.Arrays.asList; 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 static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT; import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder; @@ -99,9 +106,75 @@ public class ChangeSetDAOTest { }
@Test(enabled = ENABLED) - public void findByDriftCriteriaWithFileCategoryandResourceIdFilters() throws Exception { + public void findByDriftCriteriaWithResourceIdFilter() throws Exception { MongoDBChangeSet c1 = new MongoDBChangeSet(); c1.setCategory(DRIFT); + c1.setVersion(1); + c1.setResourceId(1); + c1.setDriftConfigurationId(1); + dao.save(c1); + + MongoDBChangeSet c2 = new MongoDBChangeSet(); + c2.setCategory(DRIFT); + c2.setVersion(1); + c2.setResourceId(2); + c2.setDriftConfigurationId(2); + + GenericDriftCriteria criteria = new GenericDriftCriteria(); + criteria.addFilterResourceIds(1); + + List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria); + List<MongoDBChangeSet> expected = asList(c1); + + String ignore = "drifts"; + assertCollectionMatchesNoOrder("Failed to find change sets by drift criteria with resource id filter.", + expected, actual, ignore); + } + + @Test(enabled = ENABLED) + public void findByDriftCriteriaWithResourceIdsFilter() throws Exception { + MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1); + dao.save(c1); + + MongoDBChangeSet c2 = createChangeSet(COVERAGE, 1, 2, 2); + dao.save(c2); + + MongoDBChangeSet c3 = createChangeSet(COVERAGE, 1, 3, 3); + dao.save(c3); + + GenericDriftCriteria criteria = new GenericDriftCriteria(); + criteria.addFilterResourceIds(1, 2); + + List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria); + List<MongoDBChangeSet> expected = asList(c1, c2); + + String ignore = "drifts"; + assertCollectionMatchesNoOrder("Failed to find change sets by drift criteria with resource ids filter.", + expected, actual, ignore); + } + + @Test + public void findByDriftCriteriaWithCategoryFilter() throws Exception { + MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1).add(new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED)); + dao.save(c1); + + MongoDBChangeSet c2 = createChangeSet(DRIFT, 2, 1, 1) + .add(new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED)) + .add(new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED)); + dao.save(c2); + + MongoDBChangeSet c3 = createChangeSet(DRIFT, 3, 1, 1).add(new MongoDBChangeSetEntry("c1-1.txt", FILE_REMOVED)); + dao.save(c3); + + GenericDriftCriteria criteria = new GenericDriftCriteria(); + criteria.addFilterCategories(FILE_ADDED); + + List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria); + List<MongoDBChangeSet> expected = asList(c1, c2); + + String ignore = "drifts"; + assertCollectionMatchesNoOrder("Failed to find change sets by drift criteria with category filter.", + expected, actual, ignore); }
/** @@ -127,4 +200,28 @@ public class ChangeSetDAOTest { expected.getDrifts(), actual.getDrifts(), ignore); }
+ /** + * A convenience factory method for creating a change set. + * + * @param category A {@link DriftChangeSetCategory} + * @param version The change set version + * @param resourceId The owning resource id + * @param driftConfigId The drift configuration id + * @return A {@link MongoDBChangeSet} + */ + MongoDBChangeSet createChangeSet(DriftChangeSetCategory category, int version, int resourceId, int driftConfigId) { + MongoDBChangeSet changeSet = new MongoDBChangeSet(); + changeSet.setCategory(category); + changeSet.setVersion(version); + changeSet.setResourceId(resourceId); + changeSet.setDriftConfigurationId(driftConfigId); + + return changeSet; + } + +// MongoDBChangeSetEntry createEntry(String path, DriftCategory category) { +// MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(path, category); +// // TODO init oldFile +// } + }
commit 86289eb5cde0f73ebef992461d2328699b19bfd2 Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 16:23:24 2011 -0400
Removing class that has been renamed
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetTest.java deleted file mode 100644 index ac20ac4..0000000 --- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.rhq.enterprise.server.plugins.drift.mongodb.entities; - -import java.util.List; - -import com.google.code.morphia.Datastore; -import com.google.code.morphia.Morphia; -import com.google.code.morphia.query.Query; -import com.mongodb.Mongo; - -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import org.rhq.core.domain.drift.DriftCategory; - -import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE; -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.assertNotNull; - -public class MongoDBChangeSetTest { - - Mongo connection; - - Morphia morphia; - - Datastore ds; - - @BeforeClass - public void initDB() throws Exception { - connection = new Mongo("localhost"); - - morphia = new Morphia() - .map(MongoDBChangeSet.class) - .map(MongoDBChangeSetEntry.class) - .map(MongoDBFile.class); - - ds = morphia.createDatastore(connection, "rhqtest"); - } - - @BeforeMethod - public void clearCollections() throws Exception { - Query deleteAll = ds.createQuery(MongoDBChangeSet.class); - ds.delete(deleteAll); - } - - @Test(enabled = false) - public void saveAndLoadEmptyChangeSet() throws Exception { - MongoDBChangeSet expected = new MongoDBChangeSet(); - expected.setCategory(COVERAGE); - expected.setVersion(1); - expected.setDriftConfigurationId(1); - - ds.save(expected); - MongoDBChangeSet actual = ds.get(MongoDBChangeSet.class, expected.getObjectId()); - - assertNotNull(actual, "Failed to load change set"); - assertPropertiesMatch("Failed to save change set", expected, actual); - } - - @Test(enabled = false) - public void saveAndLoadChangeSetWithOneEntry() throws Exception { - MongoDBChangeSet expected = new MongoDBChangeSet(); - expected.setResourceId(10001); - expected.add(new MongoDBChangeSetEntry("foo", DriftCategory.FILE_ADDED)); - - ds.save(expected); - - MongoDBChangeSet actual = ds.get(MongoDBChangeSet.class, expected.getObjectId()); - - assertNotNull(expected, "Failed to load change set"); - assertPropertiesMatch("Failed to save change set", expected, actual, "drifts"); - assertCollectionMatchesNoOrder("Failed to save change set entries", expected.getDrifts(), actual.getDrifts(), - "changeSet"); - } - - @Test(enabled = false) - public void saveAndFindChangeSetById() throws Exception { - MongoDBChangeSet expected = new MongoDBChangeSet(); - expected.setCategory(COVERAGE); - expected.setVersion(1); - expected.setDriftConfigurationId(1); - - ds.save(expected); - - List<MongoDBChangeSet> results = ds.createQuery(MongoDBChangeSet.class) - .filter("id = ", expected.getObjectId()) - .asList(); - - assertEquals(results.size(), 1, "Expected to get back one change set"); - - } - -}
commit 4cb5c9a00f6b28d6fd88e7d85e1b0b88822d7b1f Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 16:19:42 2011 -0400
Working on domain model to provide for efficient access to change set entries
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 4490e15..2a0fd89 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 @@ -1,7 +1,23 @@ +/* + * 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.server.plugins.drift.mongodb;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; - import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java new file mode 100644 index 0000000..2f263f0 --- /dev/null +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java @@ -0,0 +1,36 @@ +/* + * 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.server.plugins.drift.mongodb.dao; + +import com.google.code.morphia.Morphia; +import com.google.code.morphia.dao.BasicDAO; +import com.mongodb.Mongo; + +import org.bson.types.ObjectId; + +import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet; + +public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> { + + public ChangeSetDAO(Morphia morphia, Mongo mongo, String db) { + super(mongo, morphia, db); + } + +} 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 bcf9f5c..61fdad0 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 @@ -1,3 +1,21 @@ +/* + * 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.server.plugins.drift.mongodb.entities;
import java.io.Serializable; @@ -14,16 +32,30 @@ import org.bson.types.ObjectId; import org.rhq.core.domain.drift.DriftChangeSet; import org.rhq.core.domain.drift.DriftChangeSetCategory;
+/** + * A change set that is stored in a MongoDB database. The change set along with its entries + * are stored as a single document. + */ @Entity("changesets") public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>, Serializable {
private static final long serialVersionUID = 1L;
+ /** + * The database primary key. This is auto-generated. + */ @Id private ObjectId id;
+ /** + * The time that the change set was created. + */ private Long ctime = System.currentTimeMillis();
+ /** + * Each change set is assigned a version number that is unique across change sets + * belonging to a given drift configuration (and corresponding resource). + */ private int version;
private DriftChangeSetCategory category; @@ -104,6 +136,7 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
public MongoDBChangeSet add(MongoDBChangeSetEntry entry) { entries.add(entry); + entry.setId(entries.size() - 1); entry.setChangeSet(this); return this; } 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 dddfb02..ef4a185 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 @@ -8,15 +8,35 @@ import com.google.code.morphia.annotations.Transient; import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.drift.DriftCategory;
+/** + * A MongoChangeSetEntry is embedded in a {@link MongoDBChangeSet}. In the database, a change set + * is stored as a single document, and the document contains an array of its entries. + */ @Embedded public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFile>, Serializable {
private static final long serialVersionUID = 1L;
+ /** + * This id field is only unique within the parent change set. The purpose of this field + * is to provide fast, efficient access to a file entry a change set document. + */ + private int id; + + /** + * The time that the entry was created. + */ private Long ctime = System.currentTimeMillis();
+ /** + * The category is one added, removed, or changed. + */ private DriftCategory category;
+ /** + * This is the path relative to the base directory defined in the + * {@link org.rhq.core.domain.drift.DriftConfiguration} + */ private String path;
@Transient @@ -30,13 +50,56 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil this.category = category; }
+ /** + * Returns an id that uniquely identifies this entry. Since a MongoChangeSetEntry does + * have a PK in the database, this is a combination of the change set id with the id + * assigned by the owning change set. The format is: + * <p/> + * <pre> + * <changeset_id>:<n> + * </pre> + * <p/> + * where <i>n</i> is an integer id assigned by the owning change set that is unique + * within that change set. + * + * @return A unique identifier for the change set entry + */ @Override public String getId() { - return changeSet.getId() + ":" + path; + return changeSet.getId() + ":" + id; }
+ /** + * Sets the id for the entry which is assumed to be an integer that is assigned + * by the owning change set. + * + * @param id An integer id that should be unique among other entries within the owning + * change set. + */ @Override public void setId(String id) { + this.id = Integer.parseInt(id); + } + + /** + * Returns the change set assigned id. This id is unique across file entries within + * the owning change set. + * + * @return The change set assigned id + */ + public int getInternalId() { + return id; + } + + /** + * Sets the id for the entry which is assumed to be an integer that is assigned + * by the owning change set. + * + * @param id An integer id that should be unique among other entries within the owning + * change set. + */ + public void setId(int id) { + this.id = id; }
@Override 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 new file mode 100644 index 0000000..2604350 --- /dev/null +++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java @@ -0,0 +1,130 @@ +package org.rhq.enterprise.server.plugins.drift.mongodb.dao; + +import com.google.code.morphia.Datastore; +import com.google.code.morphia.Morphia; +import com.google.code.morphia.query.Query; +import com.mongodb.Mongo; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet; +import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry; +import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; + +import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED; +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.assertNotNull; + +public class ChangeSetDAOTest { + + static final boolean ENABLED = true; + + Mongo connection; + + Morphia morphia; + + Datastore ds; + + ChangeSetDAO dao; + + @BeforeClass + public void initDB() throws Exception { + connection = new Mongo("localhost"); + + morphia = new Morphia() + .map(MongoDBChangeSet.class) + .map(MongoDBChangeSetEntry.class) + .map(MongoDBFile.class); + + ds = morphia.createDatastore(connection, "rhqtest"); + } + + @BeforeMethod + public void clearCollections() throws Exception { + Query deleteAll = ds.createQuery(MongoDBChangeSet.class); + ds.delete(deleteAll); + + dao = new ChangeSetDAO(morphia, connection, "rhqtest"); + } + + @Test(enabled = ENABLED) + public void saveAndLoadEmptyChangeSet() throws Exception { + MongoDBChangeSet expected = new MongoDBChangeSet(); + expected.setCategory(COVERAGE); + expected.setVersion(1); + expected.setDriftConfigurationId(1); + expected.setResourceId(1); + + dao.save(expected); + MongoDBChangeSet actual = dao.get(expected.getObjectId()); + + assertChangeSetMatches("Failed to save/load change set with no entries", expected, actual); + } + + @Test(enabled = ENABLED) + public void saveAndLoadChangeSetWithOneEntry() throws Exception { + MongoDBChangeSet expected = new MongoDBChangeSet(); + expected.setCategory(DRIFT); + expected.setResourceId(1); + expected.setDriftConfigurationId(1); + expected.setVersion(1); + expected.add(new MongoDBChangeSetEntry("foo", FILE_ADDED)); + + dao.save(expected); + + MongoDBChangeSet actual = dao.get(expected.getObjectId()); + + assertChangeSetMatches("Failed to save/load change set with one entry", expected, actual); + } + + @Test(enabled = ENABLED) + public void saveAndLoadChangeSetWithMultipleEntries() throws Exception { + MongoDBChangeSet expected = new MongoDBChangeSet(); + expected.setCategory(DRIFT); + expected.setVersion(1); + expected.setResourceId(1); + expected.setDriftConfigurationId(1); + expected.add(new MongoDBChangeSetEntry("foo", FILE_ADDED)).add(new MongoDBChangeSetEntry("bar", FILE_ADDED)); + + dao.save(expected); + + MongoDBChangeSet actual = dao.get(expected.getObjectId()); + + assertChangeSetMatches("Failed to save/load change set with multiple entries", expected, actual); + } + + @Test(enabled = ENABLED) + public void findByDriftCriteriaWithFileCategoryandResourceIdFilters() throws Exception { + MongoDBChangeSet c1 = new MongoDBChangeSet(); + c1.setCategory(DRIFT); + } + + /** + * This method first checks that the actual change set is not null. It then performs a + * property-wise comparison against the expected change set using + * {@link org.rhq.test.AssertUtils#assertPropertiesMatch(String, Object, Object, String...) assertPropertiesMatch}. + * The {@link org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet#getDrifts() drifts} + * property is then tested separately using + * {@link org.rhq.test.AssertUtils#assertCollectionMatchesNoOrder(String, java.util.Collection, java.util.Collection, String...) assertCollectionMatches}. + * + * @param msg An error message + * @param expected The expected change set to test against + * @param actual The actual change set under test + */ + void assertChangeSetMatches(String msg, MongoDBChangeSet expected, MongoDBChangeSet actual) { + assertNotNull(actual, msg + ": change set is null"); + + String ignore = "drifts"; + assertPropertiesMatch(msg, expected, actual, ignore); + + ignore = "changeSet"; + assertCollectionMatchesNoOrder(msg + ": " + "change set entries do not match expected entries.", + expected.getDrifts(), actual.getDrifts(), ignore); + } + +}
commit 439887a193ead06f7e136d8a5138995cee163d05 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 4 20:48:53 2011 -0400
fix troublesome test
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 5f06189..69f0984 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 @@ -49,7 +49,6 @@ import org.rhq.core.domain.drift.DriftChangeSet; import org.rhq.core.domain.drift.DriftConfiguration; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus; -import org.rhq.core.domain.drift.JPADriftFile; import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.InventoryStatus; @@ -222,7 +221,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(2, driftConfigs.size()); + assertEquals(4, driftConfigs.size()); for (Iterator<Configuration> i = driftConfigs.iterator(); i.hasNext();) { driftConfig = new DriftConfiguration(i.next()); if ("testDriftConfig".equals(driftConfig.getName())) {
commit 285abd31c97d4ec3d1b46b4eeb4c2a3fb3b22752 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 4 20:48:42 2011 -0400
Drift History View - Add config name column - Add config name to DriftComposite - todo: mongodb is not provising the real value, waiting on possible tweaks to data model - Added start/end changeSetVersion filters to DriftCriteria - Omit changeset version 0 (coverage) drift entries from history view
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java index 25c1e53..de55f02 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java @@ -30,39 +30,51 @@ import org.rhq.core.domain.util.PageOrdering; */ public interface DriftCriteria extends BaseCriteria {
+ // Filters void addFilterId(String filterId);
- String getFilterId(); - void addFilterCategories(DriftCategory... filterCategories);
- DriftCategory[] getFilterCategories(); - void addFilterChangeSetId(String filterChangeSetId);
- String getFilterChangeSetId(); + void addFilterChangeSetStartVersion(Integer filterChangeSetStartVersion);
- void addFilterPath(String filterPath); + void addFilterChangeSetEndVersion(Integer filterChangeSetEndVersion);
- String getFilterPath(); + void addFilterPath(String filterPath);
void addFilterResourceIds(Integer... filterResourceIds);
- Integer[] getFilterResourceIds(); - void addFilterStartTime(Long filterStartTime);
- Long getFilterStartTime(); - void addFilterEndTime(Long filterEndTime);
- Long getFilterEndTime(); + // sorting + void addSortCtime(PageOrdering sortCtime);
+ // optional data fetch void fetchChangeSet(boolean fetchChangeSet);
- boolean isFetchChangeSet(); + // getters for inspecting settings + String getFilterId();
- void addSortCtime(PageOrdering sortCtime); + DriftCategory[] getFilterCategories(); + + String getFilterChangeSetId(); + + Integer getFilterChangeSetStartVersion(); + + Integer getFilterChangeSetEndVersion(); + + String getFilterPath(); + + Integer[] getFilterResourceIds(); + + Long getFilterStartTime(); + + Long getFilterEndTime(); + + boolean isFetchChangeSet();
PageOrdering getSortCtime();
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java index b8a84d8..6ef58a0 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java @@ -48,6 +48,10 @@ public class GenericDriftCriteria implements Serializable, DriftCriteria {
private String filterChangeSetId;
+ private Integer filterChangeSetStartVersion; + + private Integer filterChangeSetEndVersion; + private String filterPath;
private List<Integer> filterResourceIds = new ArrayList<Integer>(); @@ -93,6 +97,26 @@ public class GenericDriftCriteria implements Serializable, DriftCriteria { }
@Override + public void addFilterChangeSetStartVersion(Integer filterChangeSetStartVersion) { + this.filterChangeSetStartVersion = filterChangeSetStartVersion; + } + + @Override + public Integer getFilterChangeSetStartVersion() { + return filterChangeSetStartVersion; + } + + @Override + public void addFilterChangeSetEndVersion(Integer filterChangeSetEndVersion) { + this.filterChangeSetEndVersion = filterChangeSetEndVersion; + } + + @Override + public Integer getFilterChangeSetEndVersion() { + return filterChangeSetEndVersion; + } + + @Override public void addFilterPath(String filterPath) { this.filterPath = filterPath; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java index 2962b57..0ef3c95 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java @@ -43,6 +43,8 @@ public class JPADriftCriteria extends Criteria implements DriftCriteria { private Integer filterId; private List<DriftCategory> filterCategories = new ArrayList<DriftCategory>(); private Integer filterChangeSetId; // needs override + private Integer filterChangeSetStartVersion; // needs override + private Integer filterChangeSetEndVersion; // needs override private String filterPath; private List<Integer> filterResourceIds = new ArrayList<Integer>(); private Long filterStartTime; // requires overrides @@ -58,6 +60,8 @@ public class JPADriftCriteria extends Criteria implements DriftCriteria {
public JPADriftCriteria(DriftCriteria driftCriteria) { filterOverrides.put("changeSetId", "changeSet.id = ?"); + filterOverrides.put("changeSetStartVersion", "changeSet.version >= ?"); + filterOverrides.put("changeSetEndVersion", "changeSet.version <= ?"); filterOverrides.put("categories", "category IN ( ? )"); filterOverrides.put("resourceIds", "changeSet.resource.id IN ( ? )"); filterOverrides.put("startTime", "ctime >= ?"); @@ -69,6 +73,8 @@ public class JPADriftCriteria extends Criteria implements DriftCriteria {
this.addFilterCategories(driftCriteria.getFilterCategories()); this.addFilterChangeSetId(driftCriteria.getFilterChangeSetId()); + this.addFilterChangeSetStartVersion(driftCriteria.getFilterChangeSetStartVersion()); + this.addFilterChangeSetEndVersion(driftCriteria.getFilterChangeSetEndVersion()); this.addFilterEndTime(driftCriteria.getFilterEndTime()); this.addFilterId(driftCriteria.getFilterId()); this.addFilterPath(driftCriteria.getFilterPath()); @@ -104,6 +110,7 @@ public class JPADriftCriteria extends Criteria implements DriftCriteria { return filterCategories.toArray(new DriftCategory[filterCategories.size()]); }
+ @Override public void addFilterChangeSetId(String filterChangeSetId) { if (filterChangeSetId != null) { this.filterChangeSetId = Integer.parseInt(filterChangeSetId); @@ -115,6 +122,26 @@ public class JPADriftCriteria extends Criteria implements DriftCriteria { return filterChangeSetId == null ? null : filterChangeSetId.toString(); }
+ @Override + public Integer getFilterChangeSetStartVersion() { + return filterChangeSetStartVersion; + } + + @Override + public void addFilterChangeSetStartVersion(Integer filterChangeSetStartVersion) { + this.filterChangeSetStartVersion = filterChangeSetStartVersion; + } + + @Override + public Integer getFilterChangeSetEndVersion() { + return filterChangeSetEndVersion; + } + + @Override + public void addFilterChangeSetEndVersion(Integer filterChangeSetEndVersion) { + this.filterChangeSetEndVersion = filterChangeSetEndVersion; + } + public void addFilterPath(String filterPath) { this.filterPath = filterPath; } 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 5bae99f..072f432 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 @@ -12,12 +12,15 @@ public class DriftComposite implements Serializable {
private Resource resource;
+ private String driftConfigName; + public DriftComposite() { }
- public DriftComposite(Drift<?, ?> drift, Resource resource) { + public DriftComposite(Drift<?, ?> drift, Resource resource, String driftConfigName) { this.drift = drift; this.resource = resource; + this.driftConfigName = driftConfigName; }
public Drift<?, ?> getDrift() { @@ -35,4 +38,13 @@ public class DriftComposite implements Serializable { public void setResource(Resource resource) { this.resource = resource; } + + public String getDriftConfigName() { + return driftConfigName; + } + + public void setDriftConfigName(String driftConfigName) { + this.driftConfigName = driftConfigName; + } + } 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 5fd4e3e..9b1608f 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 @@ -70,8 +70,9 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC public static final String ATTR_ID = "id"; public static final String ATTR_CTIME = "ctime"; public static final String ATTR_CATEGORY = "category"; - public static final String ATTR_PATH = "path"; public static final String ATTR_CHANGESET_VERSION = "changeSetVersion"; + public static final String ATTR_CHANGESET_CONFIG = "changSetConfig"; + public static final String ATTR_PATH = "path";
public static final String FILTER_CATEGORIES = "categories";
@@ -103,6 +104,9 @@ 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_configuration()); + fields.add(changeSetConfigField); + ListGridField changeSetVersionField = new ListGridField(ATTR_CHANGESET_VERSION, MSG .view_drift_table_changeSet()); fields.add(changeSetVersionField); @@ -266,8 +270,12 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC }
GenericDriftCriteria criteria = new GenericDriftCriteria(); + // grab the change set for the drift criteria.fetchChangeSet(true); + // only get the desired drift categories criteria.addFilterCategories(categoriesFilter); + // do not fetch tracking entries from the coverage changeset + criteria.addFilterChangeSetStartVersion(1);
switch (entityContext.getType()) { case Resource: @@ -303,7 +311,7 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftC
public static ListGridRecord convert(DriftComposite from) { ListGridRecord record = new ListGridRecord(); - Drift drift = from.getDrift(); + Drift<?, ?> drift = from.getDrift(); record.setAttribute(ATTR_ID, drift.getId()); record.setAttribute(ATTR_CTIME, new Date(drift.getCtime())); switch (drift.getChangeSet().getCategory()) { @@ -315,6 +323,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_VERSION, drift.getChangeSet().getVersion());
// for ancestry handling 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 4cb139b..c66b900 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 @@ -132,7 +132,10 @@ public class JPADriftServerBean implements JPADriftServerLocal { PageList<JPADrift> drifts = findDriftsByCriteria(subject, criteria); PageList<DriftComposite> composites = new PageList<DriftComposite>(); for (JPADrift drift : drifts) { - composites.add(new DriftComposite(drift, drift.getChangeSet().getResource())); + JPADriftChangeSet changeSet = drift.getChangeSet(); + DriftConfiguration driftConfig = new DriftConfiguration(entityManager.find(Configuration.class, changeSet + .getDriftConfigurationId())); + composites.add(new DriftComposite(drift, changeSet.getResource(), driftConfig.getName())); } return composites; } 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 fd1eb79..4490e15 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 @@ -181,7 +181,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC for (MongoDBChangeSet changeSet : query) { DriftChangeSetDTO changeSetDTO = toDTO(changeSet); for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) { - results.add(new DriftComposite(toDTO(entry, changeSetDTO), resources.get(changeSet.getResourceId()))); + // TODO: need to access config name + results.add(new DriftComposite(toDTO(entry, changeSetDTO), resources.get(changeSet.getResourceId()), + "TODO")); } }
commit b7b17d040c923f43e948aa235b800d9d159d8f6b Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 4 17:40:35 2011 -0400
add top level to the tree - the drift config. add new icons for config folders (disabled and enabled)
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 2151eee..c40cc8c 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,6 +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.util.PageList; import org.rhq.core.domain.util.PageOrdering; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -87,8 +88,13 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc
String parentId = request.getCriteria().getAttribute(ATTR_PARENT_ID);
- if (parentId == null) { + // if parentId is null, the nodes that we need to create are the top-level drift configurations + // if parentId is a number (that is, a string that doesn't have a "_" separator), it is a drift config node. + // if parentId is has two numbers separated with a "_", it is a changeset
+ if (parentId == null) { + fetchDriftConfigurations(request, response); // we are at the root of the tree - get the top nodes (the drift configs) + } else if (parentId.indexOf('_') == -1) { // There is no parent - we are at the root of the tree. // Get the top nodes (the change sets) but to be as fast as possible don't load their drifts. // We will lazily load drifts when the these changeset tree nodes are opened @@ -109,7 +115,7 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc } }); } else { - String changesetId = parentId; + String changesetId = parentId.substring(parentId.indexOf('_') + 1); GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.addFilterChangeSetId(changesetId);
@@ -126,45 +132,19 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc processResponse(request.getRequestId(), response); } }); - - /* - * I am leaving this code commented for future reference. Because today the drit change set tree only - * shows simple changeset->drift tree, we don't need this. But if we need to have - * multiple types of child nodes, we'll need something like below to query - * for the different child node data. For example, we'd need this if we have a tree like: - * ChangeSet - * |____Resources - * | |____ My resource 1 - * | |____ ... - * |_____Drifts - * |___ Drift #1 - * |___ Drift #2 - * |___ ... - * Today we only have Drifts child nodes, so we don't need to have that intermediate - * "Drifts" node. If we later want to introduce different node types (like Resources) - * we need additional code like below. - * - - // we are at an inner node, being asked to get the children of it - if (p.endsWith("_drifts")) { - // ...load drift items like above in the real code... - } else if (p.endsWith("_resources")) { - // ...load resource items and put those nodes in the tree... - } else { - // This is an unknown type of node, so just log an error. - // Note that if, in the future, we have other types of nodes (like maybe resource nodes for group change sets?) - // we'll add more if-else statements above to process those different nodes. - CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadFailure()); - } - - * - */ }
return; }
/** + * Fetches the top level node data - the drift configuration nodes. + * @param request + * @param response + */ + protected abstract void fetchDriftConfigurations(DSRequest request, DSResponse response); + + /** * Returns a criteria that will be used to obtain the root nodes for the tree - that is, * the top level change set entries. * @@ -196,10 +176,6 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc
@Override public ListGridRecord[] buildRecords(Collection dataObjects) { - return buildRecordsForKnownChangeSets(dataObjects, null); - } - - public ListGridRecord[] buildRecordsForKnownChangeSets(Collection dataObjects, Integer changeSetId) { if (dataObjects == null) { return null; } @@ -207,36 +183,7 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc final List<ListGridRecord> records = new ArrayList<ListGridRecord>();
for (Object item : dataObjects) { - - // the resultant item is a direct node to build records.add(copyValues(item)); - - // now build the children of the node - /* - * We do not have the need for building any intermeidate nodes today. - * There is nothing to do, but if in the future we have differnet node types, - * we'll probably want intermediate nodes that we create here. See BundleTreeDataSource - * for an example of where this is already done. Commenting this out just as an - * example of how this can be done. - - if (item instanceof DriftChangeSet) { - DriftChangeSet changeset = (DriftChangeSet) item; - - // each bundle has two direct children - the versions and destinations folders - TreeNode versionNode = new TreeNode(MSG.view_drift()); - versionNode.setID(changeset.getId() + "_drifts"); - versionNode.setParentID(changeset.getId()); - versionNode.setName(MSG.view_drift()); - versionNode.setAttribute("name", MSG.view_drift()); - records.add(versionNode); - } else if (item instanceof Drift) { - if (canManageDrift) { - records.add(copyValuesForKnownDriftChangeSet(driftItem, changeSetId)); - } - } - - * - */ }
return records.toArray(new ListGridRecord[records.size()]); @@ -244,12 +191,11 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc
@Override public ListGridRecord copyValues(Object from) { - return copyValuesForKnownDriftChangeSet(from, null); - } - - public ListGridRecord copyValuesForKnownDriftChangeSet(Object from, Integer changeSetId) { TreeNode node; - if (from instanceof DriftChangeSet) { + if (from instanceof DriftConfiguration) { + DriftConfiguration driftConfig = (DriftConfiguration) from; + node = new AbstractDriftChangeSetsTreeView.DriftConfigurationTreeNode(driftConfig); + } else if (from instanceof DriftChangeSet) { DriftChangeSet changeset = (DriftChangeSet) from; node = new AbstractDriftChangeSetsTreeView.ChangeSetTreeNode(changeset); } else if (from instanceof Drift) { @@ -258,7 +204,6 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc } else { throw new IllegalArgumentException("please report this bug - bad value: " + from); } - // if, in the future, we add more node types, we'll add more else-if statements here
return node; } 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 9a05c5f..2aa8388 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 @@ -44,6 +44,7 @@ import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; 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.DriftConfigurationDefinition; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ImageManager; @@ -282,22 +283,43 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid return ((TreeNode) node).getTitle(); }
- @SuppressWarnings("unchecked") + static class DriftConfigurationTreeNode extends TreeNode { + public DriftConfigurationTreeNode(DriftConfiguration driftConfig) { + setIsFolder(true); + if (driftConfig.getEnabled()) { + setIcon("subsystems/drift/DriftConfig_Folder_16.png"); + } else { + setIcon("subsystems/drift/DriftConfig_Disabled_Folder_16.png"); + } + setShowOpenIcon(true); + setID(String.valueOf(driftConfig.getId())); + setName(buildNodeName(driftConfig)); // we sort on this column + } + + @Override + public String getTitle() { + return super.getName(); + } + + private String buildNodeName(DriftConfiguration driftConfig) { + return driftConfig.getName(); + } + } + static class ChangeSetTreeNode extends TreeNode { - public ChangeSetTreeNode(DriftChangeSet changeset) { + public ChangeSetTreeNode(DriftChangeSet<?> changeset) { setIsFolder(true); setShowOpenIcon(true); - setID(changeset.getId()); + String parentID = String.valueOf(changeset.getDriftConfigurationId()); + setParentID(parentID); + setID(parentID + "_" + changeset.getId()); setName(padWithZeroes(changeset.getVersion())); // we sort on this column, hence we make sure the version # is padded - setTitle(buildDriftChangeSetNodeName(changeset)); - - switch (changeset.getCategory()) { - case COVERAGE: - setIcon("subsystems/drift/ChangeSet_Coverage_16.png"); - break; - case DRIFT: - setIcon("subsystems/drift/ChangeSet_16.png"); - break; + setTitle(buildNodeName(changeset)); + + if (changeset.getVersion() == 0) { + setIcon("subsystems/drift/ChangeSet_Coverage_Folder_16.png"); + } else { + setIcon("subsystems/drift/ChangeSet_Folder_16.png"); } }
@@ -305,7 +327,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid return getAttribute("id"); }
- private String buildDriftChangeSetNodeName(DriftChangeSet changeset) { + private String buildNodeName(DriftChangeSet<?> changeset) { StringBuilder str = new StringBuilder(); str.append(MSG.common_title_version()); str.append(' '); @@ -316,30 +338,16 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid str.append(")"); return str.toString(); } - - private String padWithZeroes(int numberToPad) { - String stringToPad = String.valueOf(numberToPad); - char[] zeroes = new char[10 - stringToPad.length()]; - for (int i = 0; i < zeroes.length; i++) - zeroes[i] = '0'; - return new String(zeroes) + stringToPad; - } }
- @SuppressWarnings("unchecked") static class DriftTreeNode extends TreeNode { - public DriftTreeNode(Drift drift) { + public DriftTreeNode(Drift<?, ?> drift) { setIsFolder(false); setIcon(ImageManager.getDriftCategoryIcon(drift.getCategory())); - String parentID = drift.getChangeSet().getId(); - setParentID(parentID); - setID(parentID + '_' + drift.getId()); + DriftChangeSet<?> changeset = drift.getChangeSet(); + setParentID(String.valueOf(changeset.getDriftConfigurationId()) + "_" + changeset.getId()); + setID(drift.getId()); setName(drift.getPath()); // we sort on this column - setAttribute("driftId", drift.getId()); - } - - public String getDriftId() { - return getAttribute("driftId"); }
@Override @@ -347,4 +355,12 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid return super.getName(); } } + + static private String padWithZeroes(int numberToPad) { + String stringToPad = String.valueOf(numberToPad); + char[] zeroes = new char[10 - stringToPad.length()]; + for (int i = 0; i < zeroes.length; i++) + zeroes[i] = '0'; + return new String(zeroes) + stringToPad; + } } 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 f0f6049..519abf5 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 @@ -19,10 +19,21 @@
package org.rhq.enterprise.gui.coregui.client.drift;
+import java.util.Set; + +import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; +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.resource.Resource; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.gwt.ResourceGWTServiceAsync;
/** * @author John Mazzitelli @@ -30,6 +41,7 @@ import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria; public class ResourceDriftChangeSetsTreeDataSource extends AbstractDriftChangeSetsTreeDataSource {
private final EntityContext context; + private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
public ResourceDriftChangeSetsTreeDataSource(boolean canManageDrift, EntityContext context) { super(canManageDrift); @@ -42,6 +54,27 @@ public class ResourceDriftChangeSetsTreeDataSource extends AbstractDriftChangeSe }
@Override + protected void fetchDriftConfigurations(final DSRequest request, final DSResponse response) { + ResourceCriteria criteria = new ResourceCriteria(); + criteria.addFilterId(context.getResourceId()); + criteria.fetchDriftConfigurations(true); + this.resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { + public void onSuccess(PageList<Resource> result) { + Set<DriftConfiguration> driftConfigs = DriftConfiguration.valueOf(result.get(0)); + response.setData(buildRecords(driftConfigs)); + response.setTotalRows(result.getTotalSize()); + processResponse(request.getRequestId(), response); + } + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadFailure(), caught); + response.setStatus(DSResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + }); + } + + @Override protected GenericDriftChangeSetCriteria getDriftChangeSetCriteria(final DSRequest request) { GenericDriftChangeSetCriteria criteria = super.getDriftChangeSetCriteria(request); criteria.addFilterResourceId(this.context.resourceId); diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16.png deleted file mode 100644 index e728bc8..0000000 Binary files a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16.png and /dev/null differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16_open.png deleted file mode 100644 index 1ca204f..0000000 Binary files a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_16_open.png and /dev/null differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16.png deleted file mode 100644 index 7ae8f52..0000000 Binary files a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16.png and /dev/null differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16_open.png deleted file mode 100644 index 85e3cf4..0000000 Binary files a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_16_open.png and /dev/null differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16.png new file mode 100644 index 0000000..7ae8f52 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16_open.png new file mode 100644 index 0000000..85e3cf4 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Coverage_Folder_16_open.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16.png new file mode 100644 index 0000000..e728bc8 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16_open.png new file mode 100644 index 0000000..1ca204f Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/ChangeSet_Folder_16_open.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_16.png new file mode 100644 index 0000000..a580e4e Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16.png new file mode 100644 index 0000000..0d82665 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16_open.png new file mode 100644 index 0000000..79e1933 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Disabled_Folder_16_open.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16.png new file mode 100644 index 0000000..d09ac01 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16.png differ diff --git a/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16_open.png b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16_open.png new file mode 100644 index 0000000..bb01e36 Binary files /dev/null and b/modules/enterprise/gui/coregui/src/main/webapp/images/subsystems/drift/DriftConfig_Folder_16_open.png differ
commit 28ebe1cdd0cb7875433ceaa8ae9a707b85ecdf48 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 4 16:50:09 2011 -0400
Replace the test class, lost in a bad merge.
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 b71224f..5f06189 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 @@ -64,12 +64,17 @@ import org.rhq.enterprise.server.util.LookupUtil;
/** * Test for {@link DriftManagerBean} SLSB. + * + * !!! Actually, this is really testing only the JPA impl, it does not actually go through the + * !!! configured drift server plugin. To enhance this to do that then you may need to model this + * !!! mode like BundleManagerBeanTest */ @Test(groups = "drift-manager") public class DriftManagerBeanTest extends AbstractEJB3Test {
private static final boolean ENABLE_TESTS = true;
+ private JPADriftServerLocal jpaDriftServer; private DriftManagerLocal driftManager; private Subject overlord; private Resource newResource; @@ -81,6 +86,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { */ @BeforeClass public void beforeClass() { + jpaDriftServer = LookupUtil.getJPADriftServer(); driftManager = LookupUtil.getDriftManager(); overlord = LookupUtil.getSubjectManager().getOverlord();
@@ -118,33 +124,33 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { public void testStoreChangeSet() throws Exception { File changeset1 = new File("./src/test/resources/org/rhq/enterprise/server/drift/changeset-1.zip"); assertTrue(changeset1.exists()); - driftManager.storeChangeSet(newResource.getId(), changeset1); + jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeset1);
JPADriftChangeSetCriteria c = new JPADriftChangeSetCriteria(); c.addFilterResourceId(newResource.getId()); c.fetchDrifts(true); - List<? extends DriftChangeSet<?>> changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); + List<? extends DriftChangeSet<?>> changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(overlord, c); assertEquals(1, changeSets.size()); DriftChangeSet<?> changeSet = changeSets.get(0); assertEquals(0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size());
- JPADriftFile driftFile = driftManager.getDriftFile(overlord, "aaaaa"); + DriftFile driftFile = jpaDriftServer.getDriftFile(overlord, "aaaaa"); assertNotNull(driftFile); assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus());
// the second change set should report drift File changeset2 = new File("./src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip"); assertTrue(changeset2.exists()); - driftManager.storeChangeSet(newResource.getId(), changeset2); + jpaDriftServer.storeChangeSet(overlord, newResource.getId(), changeset2); c.addSortVersion(PageOrdering.ASC); - changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); + changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(overlord, c); assertEquals(2, changeSets.size()); changeSet = changeSets.get(0); - assertEquals("", 0, changeSet.getVersion()); + assertEquals("The change set version is wrong", 0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size()); changeSet = changeSets.get(1); - assertEquals("The change set version is wrong", 0, changeSet.getVersion()); + assertEquals(1, changeSet.getVersion()); assertEquals(1, changeSet.getDrifts().size()); Drift<?, ?> drift = changeSet.getDrifts().iterator().next(); assertEquals("dir/filename.ext", drift.getPath()); @@ -152,7 +158,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals("bbbbb", drift.getNewDriftFile().getHashId()); assertEquals(DriftCategory.FILE_CHANGED, drift.getCategory());
- driftFile = driftManager.getDriftFile(overlord, "bbbbb"); + driftFile = jpaDriftServer.getDriftFile(overlord, "bbbbb"); assertNotNull(driftFile); assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus()); } @@ -216,7 +222,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(4, driftConfigs.size()); + assertEquals(2, driftConfigs.size()); for (Iterator<Configuration> i = driftConfigs.iterator(); i.hasNext();) { driftConfig = new DriftConfiguration(i.next()); if ("testDriftConfig".equals(driftConfig.getName())) {
commit dba7f670d89f5eee14d7187a29e4bc5f3a91f6fb Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 4 15:24:09 2011 -0400
Add some jdoc explaining the Subject param on signatures in this facet.
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 8a7ea91..1da1738 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 @@ -35,6 +35,10 @@ import org.rhq.core.domain.util.PageList; * All drift server plugins must implement this facet. The methods here must all be defined in * DriftManagerLocal as well. See DriftManagerLocal for jdoc of these methods. * + * Note that the Subject parameter is provided as a convenience to the plugin methods. It is not expected that + * authz be performed by the plugin code. But, it may be useful to have the user name or session id for logging, or + * for unknown need to interact with the RHQ SLSBs. + * * @author Jay Shaughnessy * @author John Sanda */
commit c71ba4e320febe67e36055720de622ac65ac3e75 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Aug 4 15:04:42 2011 -0400
Drift SLSB Refactoring - DriftManagerBean -> JPADriftServerBean - DriftManagerLocal -> JPADriftServerLocal - DriftManagerRemote -> deleted - DriftServerBean -> DriftManagerBean - DriftServerLocal -> DriftManagerLocal - DriftServerRemote -> DriftManagerRemote - DriftServerPluginComponent -> JPADriftServerPluginComponent
So, now the JPA-specific SLSB is in place and trimmed appropriately. DriftManagerBean implements only the SLSB methods required for RHQ drift management and defers to the server plugins for any methods defined in DriftServerPluginFacet. Note that more methods will probably migrate from DriftManagerLocal to DriftServerPluginFacet. Similarly, more DriftManagerLocal methods should probably be defined as remote instead. - added Subject param to a couple of SLSB methods - remove warnings in DriftComposite - all tests enabled and passing locally - alphabetized ordering in various places for my own sanity during this exercise
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 3313755..5bae99f 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 @@ -8,23 +8,23 @@ public class DriftComposite implements Serializable {
private static final long serialVersionUID = 1L;
- private Drift drift; + private Drift<?, ?> drift;
private Resource resource;
public DriftComposite() { }
- public DriftComposite(Drift drift, Resource resource) { + public DriftComposite(Drift<?, ?> drift, Resource resource) { this.drift = drift; this.resource = resource; }
- public Drift getDrift() { + public Drift<?, ?> getDrift() { return drift; }
- public void setDrift(Drift drift) { + public void setDrift(Drift<?, ?> drift) { this.drift = drift; }
diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqFacade.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqFacade.java index 8538d9a..a965cb9 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqFacade.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqFacade.java @@ -32,7 +32,6 @@ import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; import org.rhq.enterprise.server.discovery.DiscoveryBossRemote; import org.rhq.enterprise.server.drift.DriftManagerRemote; -import org.rhq.enterprise.server.drift.DriftServerRemote; import org.rhq.enterprise.server.event.EventManagerRemote; import org.rhq.enterprise.server.install.remote.RemoteInstallManagerRemote; import org.rhq.enterprise.server.measurement.AvailabilityManagerRemote; @@ -90,8 +89,6 @@ public interface RhqFacade {
DiscoveryBossRemote getDiscoveryBoss();
- DriftServerRemote getDriftServer(); - DriftManagerRemote getDriftManager();
EventManagerRemote getEventManager(); diff --git a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManagers.java b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManagers.java index ff632d7..473d95e 100644 --- a/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManagers.java +++ b/modules/enterprise/binding/src/main/java/org/rhq/bindings/client/RhqManagers.java @@ -29,7 +29,6 @@ import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; import org.rhq.enterprise.server.discovery.DiscoveryBossRemote; import org.rhq.enterprise.server.drift.DriftManagerRemote; -import org.rhq.enterprise.server.drift.DriftServerRemote; import org.rhq.enterprise.server.event.EventManagerRemote; import org.rhq.enterprise.server.install.remote.RemoteInstallManagerRemote; import org.rhq.enterprise.server.measurement.AvailabilityManagerRemote; @@ -65,7 +64,6 @@ public enum RhqManagers { ConfigurationManager(ConfigurationManagerRemote.class), // ContentManager(ContentManagerRemote.class), // DataAccessManager(DataAccessManagerRemote.class), // - DriftServer(DriftServerRemote.class), DriftManager(DriftManagerRemote.class), // DiscoveryBoss(DiscoveryBossRemote.class), // EventManager(EventManagerRemote.class), // 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 264ed26..e71c602 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 @@ -31,7 +31,6 @@ import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.drift.DriftManagerLocal; -import org.rhq.enterprise.server.drift.DriftServerLocal; import org.rhq.enterprise.server.util.LookupUtil;
/** @@ -42,8 +41,6 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift
private DriftManagerLocal driftManager = LookupUtil.getDriftManager();
- private DriftServerLocal driftServer = LookupUtil.getDriftServer(); - @Override public int deleteDrifts(String[] driftIds) throws RuntimeException { try { @@ -87,7 +84,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public void detectDrift(EntityContext entityContext, DriftConfiguration driftConfig) { try { - this.driftServer.detectDrift(getSessionSubject(), entityContext, driftConfig); + this.driftManager.detectDrift(getSessionSubject(), entityContext, driftConfig); } catch (Throwable t) { throw getExceptionToThrowToClient(t); } @@ -96,7 +93,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) { try { - PageList<? extends DriftChangeSet<?>> results = driftServer.findDriftChangeSetsByCriteria( + PageList<? extends DriftChangeSet<?>> results = driftManager.findDriftChangeSetsByCriteria( getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftChangeSetsByCriteria"); } catch (Throwable t) { @@ -107,7 +104,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public PageList<? extends Drift<?, ?>> findDriftsByCriteria(GenericDriftCriteria criteria) throws RuntimeException { try { - PageList<? extends Drift<?, ?>> results = driftServer.findDriftsByCriteria(getSessionSubject(), criteria); + PageList<? extends Drift<?, ?>> results = driftManager.findDriftsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftsByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); @@ -117,7 +114,8 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria) { try { - PageList<DriftComposite> results = driftServer.findDriftCompositesByCriteria(getSessionSubject(), criteria); + PageList<DriftComposite> results = driftManager + .findDriftCompositesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftCompositesByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); @@ -127,7 +125,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) { try { - return driftServer.createSnapshot(subject, criteria); + return driftManager.createSnapshot(subject, criteria); } catch (Throwable t) { throw getExceptionToThrowToClient(t); } @@ -137,7 +135,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift public DriftConfiguration getDriftConfiguration(EntityContext entityContext, int driftConfigId) throws RuntimeException { try { - DriftConfiguration driftConfig = driftServer.getDriftConfiguration(getSessionSubject(), entityContext, + DriftConfiguration driftConfig = driftManager.getDriftConfiguration(getSessionSubject(), entityContext, driftConfigId); return SerialUtility.prepare(driftConfig, "DriftService.getDriftConfiguration"); } catch (Throwable t) { @@ -148,7 +146,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift @Override public void updateDriftConfiguration(EntityContext entityContext, DriftConfiguration driftConfig) { try { - this.driftServer.updateDriftConfiguration(getSessionSubject(), entityContext, driftConfig); + this.driftManager.updateDriftConfiguration(getSessionSubject(), entityContext, driftConfig); } catch (Throwable t) { throw getExceptionToThrowToClient(t); } diff --git a/modules/enterprise/remoting/client-api/src/main/java/org/rhq/enterprise/client/RemoteClient.java b/modules/enterprise/remoting/client-api/src/main/java/org/rhq/enterprise/client/RemoteClient.java index 2d9973d..0460864 100644 --- a/modules/enterprise/remoting/client-api/src/main/java/org/rhq/enterprise/client/RemoteClient.java +++ b/modules/enterprise/remoting/client-api/src/main/java/org/rhq/enterprise/client/RemoteClient.java @@ -44,7 +44,6 @@ import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; import org.rhq.enterprise.server.discovery.DiscoveryBossRemote; import org.rhq.enterprise.server.drift.DriftManagerRemote; -import org.rhq.enterprise.server.drift.DriftServerRemote; import org.rhq.enterprise.server.event.EventManagerRemote; import org.rhq.enterprise.server.install.remote.RemoteInstallManagerRemote; import org.rhq.enterprise.server.measurement.AvailabilityManagerRemote; @@ -276,10 +275,6 @@ public class RemoteClient implements RhqFacade { return RemoteClientProxy.getProcessor(this, RhqManagers.CallTimeDataManager); }
- public DriftServerRemote getDriftServer() { - return RemoteClientProxy.getProcessor(this, RhqManagers.DriftServer); - } - public DriftManagerRemote getDriftManager() { return RemoteClientProxy.getProcessor(this, RhqManagers.DriftManager); } diff --git a/modules/enterprise/server/client-api/src/main/java/org/rhq/enterprise/client/LocalClient.java b/modules/enterprise/server/client-api/src/main/java/org/rhq/enterprise/client/LocalClient.java index b3c2b8c..96778f9 100644 --- a/modules/enterprise/server/client-api/src/main/java/org/rhq/enterprise/client/LocalClient.java +++ b/modules/enterprise/server/client-api/src/main/java/org/rhq/enterprise/client/LocalClient.java @@ -41,7 +41,6 @@ import org.rhq.enterprise.server.content.ContentManagerRemote; import org.rhq.enterprise.server.content.RepoManagerRemote; import org.rhq.enterprise.server.discovery.DiscoveryBossRemote; import org.rhq.enterprise.server.drift.DriftManagerRemote; -import org.rhq.enterprise.server.drift.DriftServerRemote; import org.rhq.enterprise.server.event.EventManagerRemote; import org.rhq.enterprise.server.install.remote.RemoteInstallManagerRemote; import org.rhq.enterprise.server.measurement.AvailabilityManagerRemote; @@ -133,10 +132,6 @@ public class LocalClient implements RhqFacade { return getProxy(LookupUtil.getDiscoveryBoss(), DiscoveryBossRemote.class); }
- public DriftServerRemote getDriftServer() { - return getProxy(LookupUtil.getDriftServer(), DriftServerRemote.class); - } - public DriftManagerRemote getDriftManager() { return getProxy(LookupUtil.getDriftManager(), DriftManagerRemote.class); } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftChangesetBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftChangesetBean.java index 72e9121..38aa0c0 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftChangesetBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftChangesetBean.java @@ -37,6 +37,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.core.util.stream.StreamUtil; +import org.rhq.enterprise.server.auth.SubjectManagerLocal;
@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @@ -51,7 +52,10 @@ public class DriftChangesetBean implements MessageListener { private final Log log = LogFactory.getLog(DriftChangesetBean.class);
@EJB - private DriftServerLocal driftServer; + private DriftManagerLocal driftManager; + + @EJB + private SubjectManagerLocal subjectManager;
@Override public void onMessage(Message message) { @@ -76,7 +80,7 @@ public class DriftChangesetBean implements MessageListener { + "]"); }
- driftServer.saveChangeSet(request.getResourceId(), tempFile); + driftManager.saveChangeSet(subjectManager.getOverlord(), request.getResourceId(), tempFile);
} catch (IOException e) { log.error(e); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftFileBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftFileBean.java index 588fc68..b5b9356 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftFileBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftFileBean.java @@ -37,6 +37,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.core.util.stream.StreamUtil; +import org.rhq.enterprise.server.auth.SubjectManagerLocal;
@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @@ -50,7 +51,10 @@ public class DriftFileBean implements MessageListener { private final Log log = LogFactory.getLog(DriftFileBean.class);
@EJB - private DriftServerLocal driftServer; + private DriftManagerLocal driftManager; + + @EJB + private SubjectManagerLocal subjectManager;
@Override public void onMessage(Message message) { @@ -76,7 +80,7 @@ public class DriftFileBean implements MessageListener { + "]"); }
- driftServer.saveChangeSetFiles(tempFile); + driftManager.saveChangeSetFiles(subjectManager.getOverlord(), tempFile);
} catch (IOException e) { log.error(e); 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 419ad99..2289bf6 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 @@ -1,8 +1,7 @@ /* * 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. + * 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 @@ -19,19 +18,13 @@ */ package org.rhq.enterprise.server.drift;
+import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
-import java.io.BufferedInputStream; -import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream;
import javax.ejb.EJB; import javax.ejb.Stateless; @@ -48,55 +41,59 @@ import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hibernate.Hibernate;
import org.jboss.remoting.CannotConnectException;
-import org.rhq.common.drift.ChangeSetReader; -import org.rhq.common.drift.ChangeSetReaderImpl; -import org.rhq.common.drift.DirectoryEntry; -import org.rhq.common.drift.FileEntry; -import org.rhq.common.drift.Headers; 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.configuration.Configuration; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; import org.rhq.core.domain.criteria.DriftCriteria; -import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; import org.rhq.core.domain.criteria.JPADriftCriteria; import org.rhq.core.domain.drift.Drift; 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.DriftFile; -import org.rhq.core.domain.drift.DriftFileStatus; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.drift.JPADrift; -import org.rhq.core.domain.drift.JPADriftChangeSet; -import org.rhq.core.domain.drift.JPADriftFile; -import org.rhq.core.domain.drift.JPADriftFileBits; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; -import org.rhq.core.util.ZipUtil; -import org.rhq.core.util.file.FileUtil; import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.agentclient.AgentClient; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.core.AgentManagerLocal; -import org.rhq.enterprise.server.util.CriteriaQueryGenerator; -import org.rhq.enterprise.server.util.CriteriaQueryRunner; +import org.rhq.enterprise.server.plugin.pc.MasterServerPluginContainer; +import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginContainer; +import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; +import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginManager; +import org.rhq.enterprise.server.util.LookupUtil;
/** - * The SLSB implementation for Drift Management. - * + * The SLSB supporting Drift management to clients. + * + * Wrappers are provided for the methods defined in DriftServerPluginFacet and the work is deferred to the plugin + * No assumption is made about the any back end implementation of a drift server plugin and therefore does not + * declare any transactioning (the NOT_SUPPORTED transaction attribute is used for all wrappers). + * + * For methods not deferred to the server plugin, the implementations are done here. + * + * @author John Sanda + * @author John Mazzitelli * @author Jay Shaughnessy - @ @author John Sanda */ @Stateless -public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { - private final Log log = LogFactory.getLog(this.getClass()); +public class DriftManagerBean implements DriftManagerLocal { + + // TODO Should security checks be handled here instead of delegating to the drift plugin? + // Currently any security checks that need to be performed are delegated to the plugin. + // This is fine *so far* since the only plugin is the default which is our existing SLSB + // layer backed by the RHQ database. If the plugins are only supposed to be responsible + // for persistence management of drift entities and content, then they should not be + // responsible for other concerns like security. + + private Log log = LogFactory.getLog(DriftManagerBean.class);
@javax.annotation.Resource(mappedName = "java:/JmsXA") private ConnectionFactory factory; @@ -107,17 +104,17 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { @javax.annotation.Resource(mappedName = "queue/DriftFileQueue") private Queue fileQueue;
- @EJB - AgentManagerLocal agentManager; + @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME) + private EntityManager entityManager;
@EJB - DriftManagerLocal driftManager; + private AgentManagerLocal agentManager;
@EJB - SubjectManagerLocal subjectManager; + private DriftManagerLocal driftManager;
- @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME) - private EntityManager entityManager; + @EJB + private SubjectManagerLocal subjectManager;
// use a new transaction when putting things on the JMS queue. see // http://management-platform.blogspot.com/2008/11/transaction-recovery-in-jbos... @@ -148,235 +145,52 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - @TransactionAttribute(REQUIRES_NEW) - public void storeChangeSet(final int resourceId, File changeSetZip) throws Exception { - final Resource resource = entityManager.find(Resource.class, resourceId); - if (null == resource) { - throw new IllegalArgumentException("Resource not found [" + resourceId + "]"); - } - - try { - ZipUtil.walkZipFile(changeSetZip, new ChangeSetFileVisitor() { - - @Override - public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception { - List<JPADriftFile> emptyDriftFiles = new ArrayList<JPADriftFile>(); - JPADriftChangeSet driftChangeSet = null; - - try { - ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader( - stream))); - - // store the new change set info (not the actual blob) - DriftConfiguration config = findDriftConfiguration(resource, reader.getHeaders()); - int version = getChangeSetVersion(resource, config); - - if (config == null) { - log.error("Unable to locate DriftConfiguration for Resource [" + resource - + "]. Change set cannot be saved."); - return false; - } - - DriftChangeSetCategory category = reader.getHeaders().getType(); - driftChangeSet = new JPADriftChangeSet(resource, version, category, config.getId()); - entityManager.persist(driftChangeSet); - - for (DirectoryEntry dir = reader.readDirectoryEntry(); null != dir; dir = reader - .readDirectoryEntry()) { - - for (Iterator<FileEntry> i = dir.iterator(); i.hasNext();) { - FileEntry entry = i.next(); - JPADriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), - (List<JPADriftFile>) emptyDriftFiles); - JPADriftFile newDriftFile = getDriftFile(entry.getNewSHA(), - (List<JPADriftFile>) emptyDriftFiles); - - // TODO Figure out an efficient way to save coverage change sets. - // The initial/coverage change set could contain hundreds or even thousands - // of entries. We probably want to consider doing some kind of batch insert - // - // jsanda - - // use a path with only forward slashing to ensure consistent paths across reports - String path = new File(dir.getDirectory(), entry.getFile()).getPath(); - path = FileUtil.useForwardSlash(path); - JPADrift drift = new JPADrift(driftChangeSet, path, entry.getType(), oldDriftFile, - newDriftFile); - entityManager.persist(drift); - - } - } - // send a message to the agent requesting the empty JPADriftFile content - if (!emptyDriftFiles.isEmpty()) { - - AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), - resourceId); - DriftAgentService service = agentClient.getDriftAgentService(); - try { - if (service.requestDriftFiles(resourceId, reader.getHeaders(), emptyDriftFiles)) { - for (DriftFile driftFile : emptyDriftFiles) { - driftFile.setStatus(DriftFileStatus.REQUESTED); - } - } - } catch (Exception e) { - log.warn(" Unable to inform agent of drift file request [" + emptyDriftFiles + "]", e); - } - } - } catch (Exception e) { - String msg = "Failed to store drift changeset [" + driftChangeSet + "]"; - log.error(msg, e); - return false; - } - - return true; - } - }); - } catch (Exception e) { - String msg = "Failed to store drift changeset for "; - if (null != resource) { - msg += resource; - } else { - msg += ("resourceId " + resourceId); - } - log.error(msg, e); - - } finally { - // delete the changeSetFile? - } - } - - /** - * 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 - */ - 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(); - } - - DriftConfiguration findDriftConfiguration(Resource resource, Headers headers) { - for (Configuration config : resource.getDriftConfigurations()) { - DriftConfiguration driftConfig = new DriftConfiguration(config); - if (driftConfig.getName().equals(headers.getDriftConfigurationName())) { - return driftConfig; - } - } - return null; - } - - private abstract class ChangeSetFileVisitor implements ZipUtil.ZipEntryVisitor { - } - - private JPADriftFile getDriftFile(String sha256, List<JPADriftFile> emptyDriftFiles) { - JPADriftFile result = null; - - if (null == sha256 || "0".equals(sha256)) { - return result; - } - - result = entityManager.find(JPADriftFile.class, sha256); - // if the JPADriftFile is not yet in the db, then it needs to be fetched from the agent - if (null == result) { - result = persistDriftFile(new JPADriftFile(sha256)); - emptyDriftFiles.add(result); - } - - return result; - } - - @Override - public JPADriftFile persistDriftFile(JPADriftFile driftFile) { - - entityManager.persist(driftFile); - return driftFile; + @TransactionAttribute(NOT_SUPPORTED) + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.createSnapshot(subject, criteria); }
@Override - @TransactionAttribute(REQUIRES_NEW) - public void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception { - - JPADriftFileBits df = entityManager.find(JPADriftFileBits.class, driftFile.getHashId()); - if (null == df) { - throw new IllegalArgumentException("JPADriftFile not found [" + driftFile.getHashId() + "]"); - } - df.setData(Hibernate.createBlob(new BufferedInputStream(data))); - df.setStatus(DriftFileStatus.LOADED); - } + public void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig) { + switch (context.getType()) { + case Resource: + int resourceId = context.getResourceId(); + Resource resource = entityManager.find(Resource.class, resourceId); + if (null == resource) { + throw new IllegalArgumentException("Resource not found [" + resourceId + "]"); + }
- @Override - public void storeFiles(File filesZip) throws Exception { - // No longer using ZipUtil.walkZipFile because an IOException was getting thrown - // after reading the first entry, resulting in subsequent entries being skipped. - // DriftFileVisitor passed the ZipInputStream to Hibernate.createBlob, and either - // Hibernate, the JDBC driver, or something else is closing the stream which in - // turn causes the exception. - // - // jsanda - - String zipFileName = filesZip.getName(); - File tmpDir = new File(System.getProperty("java.io.tmpdir")); - File dir = new File(tmpDir, zipFileName.substring(0, zipFileName.indexOf("."))); - dir.mkdir(); - - ZipUtil.unzipFile(filesZip, dir); - for (File file : dir.listFiles()) { - JPADriftFile driftFile = new JPADriftFile(file.getName()); + AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); + DriftAgentService service = agentClient.getDriftAgentService(); + // 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 { - driftManager.persistDriftFileData(driftFile, new FileInputStream(file)); - } catch (Exception e) { - LogFactory.getLog(getClass()).info("Skipping bad drift file", e); + service.detectDrift(resourceId, driftConfig); + } 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 + "]"); } - }
- for (File file : dir.listFiles()) { - file.delete(); - } - boolean deleted = dir.delete(); - if (!deleted) { - LogFactory.getLog(getClass()).info( - "Unable to delete " + dir.getAbsolutePath() + ". This directory and " - + "its contents are no longer needed. It can be deleted."); - } - - // DriftFileVisitor dfVisitor = new DriftFileVisitor(driftManager); - // ZipUtil.walkZipFile(filesZip, dfVisitor); + break;
+ default: + throw new IllegalArgumentException("Entity Context Type not supported [" + context + "]"); + } }
- /* TODO: dead code ? - private static class DriftFileVisitor implements ZipUtil.ZipEntryVisitor { - - private DriftManagerLocal driftManager; + @Override + public int deleteDrifts(Subject subject, String[] driftIds) { + // avoid big transactions by doing this one at a time. if this is too slow we can chunk in bigger increments. + int result = 0;
- public DriftFileVisitor(DriftManagerLocal driftManager) { - this.driftManager = driftManager; + for (String driftId : driftIds) { + result += driftManager.deleteDriftsInNewTransaction(subject, driftId); }
- public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { - String sha256 = entry.getName(); - JPADriftFile driftFile = new JPADriftFile(sha256); - - // TODO use server plugin - try { - driftManager.persistDriftFileData(driftFile, stream); - } catch (Exception e) { - LogFactory.getLog(this.getClass()).info("Skipping bad drift file", e); - } - - return true; - } + return result; } - */
@Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @@ -395,18 +209,6 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public int deleteDrifts(Subject subject, String[] driftIds) { - // avoid big transactions by doing this one at a time. if this is too slow we can chunk in bigger increments. - int result = 0; - - for (String driftId : driftIds) { - result += driftManager.deleteDriftsInNewTransaction(subject, driftId); - } - - return result; - } - - @Override public int deleteDriftsByContext(Subject subject, EntityContext entityContext) throws RuntimeException { int result = 0; JPADriftCriteria criteria = new JPADriftCriteria(); @@ -475,89 +277,29 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) { - switch (entityContext.getType()) { - case Resource: - int resourceId = entityContext.getResourceId(); - Resource resource = entityManager.find(Resource.class, resourceId); - if (null == resource) { - throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); - } - - for (Iterator<Configuration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = new DriftConfiguration(i.next()); - if (dc.getName().equals(driftConfig.getName())) { - i.remove(); - break; - } - } - - resource.getDriftConfigurations().add(driftConfig.getConfiguration()); - entityManager.merge(resource); - - AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); - DriftAgentService service = agentClient.getDriftAgentService(); - try { - service.scheduleDriftDetection(resourceId, driftConfig); - } catch (Exception e) { - log.warn(" Unable to inform agent of unscheduled drift detection [" + driftConfig + "]", e); - } - - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); - } - } - - // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl - @Override + @TransactionAttribute(NOT_SUPPORTED) public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { - - JPADriftChangeSetCriteria jpaCriteria = (criteria instanceof JPADriftChangeSetCriteria) ? (JPADriftChangeSetCriteria) criteria - : new JPADriftChangeSetCriteria(criteria); - - CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); - CriteriaQueryRunner<JPADriftChangeSet> queryRunner = new CriteriaQueryRunner<JPADriftChangeSet>(jpaCriteria, - generator, entityManager); - PageList<JPADriftChangeSet> result = queryRunner.execute(); - - return result; + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.findDriftChangeSetsByCriteria(subject, criteria); }
- // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl @Override + @TransactionAttribute(NOT_SUPPORTED) public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { - - PageList<? extends Drift<?, ?>> drifts = findDriftsByCriteria(subject, criteria); - PageList<DriftComposite> composites = new PageList<DriftComposite>(); - for (Drift<?, ?> drift : drifts) { - JPADrift d = (JPADrift) drift; - composites.add(new DriftComposite(drift, d.getChangeSet().getResource())); - } - return composites; + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.findDriftCompositesByCriteria(subject, criteria); }
- // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl @Override + @TransactionAttribute(NOT_SUPPORTED) public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { - - JPADriftCriteria jpaCriteria = (criteria instanceof JPADriftCriteria) ? (JPADriftCriteria) criteria - : new JPADriftCriteria(criteria); - - CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); - CriteriaQueryRunner<JPADrift> queryRunner = new CriteriaQueryRunner<JPADrift>(jpaCriteria, generator, - entityManager); - PageList<JPADrift> result = queryRunner.execute(); - - return result; + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.findDriftsByCriteria(subject, criteria); }
@Override - public DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId) - throws RuntimeException { - + public DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId) { DriftConfiguration result = null;
switch (entityContext.getType()) { @@ -581,7 +323,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
if (null == result) { - throw new IllegalArgumentException("JPADrift Configuration Id [" + driftConfigId + throw new IllegalArgumentException("Drift Configuration Id [" + driftConfigId + "] not found for entityContext [" + entityContext + "]"); }
@@ -589,51 +331,78 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public JPADriftFile getDriftFile(Subject subject, String sha256) { - JPADriftFile result = entityManager.find(JPADriftFile.class, sha256); - return result; + @TransactionAttribute(NOT_SUPPORTED) + public DriftFile getDriftFile(Subject subject, String hashId) throws Exception { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + return driftServerPlugin.getDriftFile(subject, hashId); }
@Override - public void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig) { + @TransactionAttribute(NOT_SUPPORTED) + public void saveChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + driftServerPlugin.saveChangeSet(subject, resourceId, changeSetZip); + }
- switch (context.getType()) { + @Override + @TransactionAttribute(NOT_SUPPORTED) + public void saveChangeSetFiles(Subject subject, File changeSetFilesZip) throws Exception { + DriftServerPluginFacet driftServerPlugin = getServerPlugin(); + driftServerPlugin.saveChangeSetFiles(subject, changeSetFilesZip); + } + + @Override + public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) { + switch (entityContext.getType()) { case Resource: - int resourceId = context.getResourceId(); + int resourceId = entityContext.getResourceId(); Resource resource = entityManager.find(Resource.class, resourceId); if (null == resource) { - throw new IllegalArgumentException("Resource not found [" + resourceId + "]"); + throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); + } + + for (Iterator<Configuration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { + DriftConfiguration dc = new DriftConfiguration(i.next()); + if (dc.getName().equals(driftConfig.getName())) { + i.remove(); + break; + } }
+ resource.getDriftConfigurations().add(driftConfig.getConfiguration()); + entityManager.merge(resource); + AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService(); - // 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); - } 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 + "]"); + service.updateDriftDetection(resourceId, driftConfig); + } catch (Exception e) { + log.warn(" Unable to inform agent of unscheduled drift detection [" + driftConfig + "]", e); }
break;
default: - throw new IllegalArgumentException("Entity Context Type not supported [" + context + "]"); + throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); } }
- @Override - public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { - // TODO security checks - DriftSnapshot snapshot = new DriftSnapshot(); - PageList<? extends DriftChangeSet<?>> changeSets = findDriftChangeSetsByCriteria(subject, criteria); + private DriftServerPluginFacet getServerPlugin() { + MasterServerPluginContainer masterPC = LookupUtil.getServerPluginService().getMasterPluginContainer(); + if (masterPC == null) { + log.warn(MasterServerPluginContainer.class.getSimpleName() + " is not started yet"); + return null; + }
- for (DriftChangeSet<?> changeSet : changeSets) { - snapshot.add(changeSet); + DriftServerPluginContainer pc = masterPC.getPluginContainerByClass(DriftServerPluginContainer.class); + if (pc == null) { + log.warn(DriftServerPluginContainer.class + " has not been loaded by the " + masterPC.getClass() + " yet"); + return null; }
- return snapshot; + DriftServerPluginManager pluginMgr = (DriftServerPluginManager) pc.getPluginManager(); + + return pluginMgr.getDriftServerPluginComponent(); } + } 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 70843d4..ca98149 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 @@ -19,25 +19,17 @@ */ package org.rhq.enterprise.server.drift;
-import java.io.File; import java.io.InputStream;
import javax.ejb.Local;
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.DriftCriteria; -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.DriftSnapshot; -import org.rhq.core.domain.drift.JPADriftFile; -import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
@Local -public interface DriftManagerLocal extends DriftManagerRemote { +public interface DriftManagerLocal extends DriftServerPluginFacet, DriftManagerRemote {
/** * This method initiates an out-of-band (JMS-Based) server-side pull of the change-set file. Upon successful @@ -62,29 +54,32 @@ public interface DriftManagerLocal extends DriftManagerRemote { */ void addFiles(int resourceId, long zipSize, InputStream zipStream) throws Exception;
+ //TODO Should probably move to DriftServerPluginFacet /** - * Remove the specified drift in its own transaction. This is used for chunking transactions and - * should not be exposed in a Remote interface. - * + * Remove the specified drifts. Ids not identifying an actual drift record will be ignored. + * * @param subject * @param * @param driftConfig - * + * * @return the number of Drift records deleted */ - int deleteDriftsInNewTransaction(Subject subject, String... driftIds); + int deleteDrifts(Subject subject, String[] driftIds);
+ //TODO Should probably move to JPADriftServerLocal when deleteDrifts graduates to server plugin facet /** - * Remove the specified drifts. Ids not identifying an actual drift record will be ignored. - * + * Remove the specified drift in its own transaction. This is used for chunking transactions and + * should not be exposed in a Remote interface. + * * @param subject * @param * @param driftConfig - * + * * @return the number of Drift records deleted */ - int deleteDrifts(Subject subject, String[] driftIds); + int deleteDriftsInNewTransaction(Subject subject, String... driftIds);
+ //TODO Should probably move to DriftServerPluginFacet /** * Remove all drifts on the specified entity context. * @@ -105,30 +100,13 @@ public interface DriftManagerLocal extends DriftManagerRemote { void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName);
/** - * Simple get method for a JPADriftFile. Does not return the content. - * @param subject - * @param sha256 - * @return The JPADriftFile sans content. - */ - JPADriftFile getDriftFile(Subject subject, String sha256); - - /** - * Standard criteria based fetch method - * @param subject - * @param criteria - * @return The DriftChangeSets matching the criteria - */ - PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); - - PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria); - - /** - * Standard criteria based fetch method - * @param subject - * @param criteria - * @return The Drifts matching the criteria + * One time on-demand request to detect drift on the specified entities, using the supplied config. + * + * @param entityContext + * @param driftConfig + * @throws RuntimeException */ - PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria); + void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig);
/** * Get the specified drift configuration for the specified context. @@ -141,27 +119,6 @@ public interface DriftManagerLocal extends DriftManagerRemote { DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId);
/** - * This method stores the provided change-set file for the resource. The version will be incremented based - * on the max version of existing change-sets for the resource. The change-set will be processed generating - * requests for drift file content and/or drift instances as required. - * - * @param resourceId The resource for which the change-set is being reported. - * @param changeSetZip The change-set zip file - * @throws Exception - */ - void storeChangeSet(int resourceId, File changeSetZip) throws Exception; - - /** - * This method stores the provided drift files. The files should correspond to requested drift files. - * The unzipped files will have their sha256 generated. Those not corresponding to needed content will - * be logged and ignored. - * - * @param filesZip The change-set zip file - * @throws Exception - */ - void storeFiles(File filesZip) throws Exception; - - /** * Update the provided driftConfig (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 @@ -169,25 +126,4 @@ public interface DriftManagerLocal extends DriftManagerRemote { * @param driftConfig */ void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig); - - // TODO, the stuff below is very preliminary and will change - - /** - * SUPPORTS DRIFT RHQ SERVER PLUGIN - * @param driftFile - * @return - * @throws Exception - */ - JPADriftFile persistDriftFile(JPADriftFile driftFile) throws Exception; - - /** - * SUPPORTS DRIFT RHQ SERVER PLUGIN - * @param driftFile - * @param data - * @throws Exception - */ - void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception; - - DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); - } 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 25a1562..8088839 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 @@ -25,8 +25,12 @@ import javax.jws.WebService; import javax.jws.soap.SOAPBinding;
import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.common.EntityContext; -import org.rhq.core.domain.drift.DriftConfiguration; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +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.DriftSnapshot; +import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.system.ServerVersion;
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT) @@ -34,16 +38,30 @@ import org.rhq.enterprise.server.system.ServerVersion; @Remote public interface DriftManagerRemote {
+ @WebMethod + DriftSnapshot createSnapshot(// + @WebParam(name = "subject") Subject subject, // + @WebParam(name = "criteria") DriftChangeSetCriteria criteria) throws Exception; + /** - * One time on-demand request to detect drift on the specified entities, using the supplied config. - * - * @param entityContext - * @param driftConfig - * @throws RuntimeException + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The DriftChangeSets matching the criteria */ @WebMethod - void detectDrift(// + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(// + @WebParam(name = "subject") Subject subject, // + @WebParam(name = "criteria") DriftChangeSetCriteria criteria) throws Exception; + + /** + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The Drifts matching the criteria + */ + PageList<? extends Drift<?, ?>> findDriftsByCriteria(// @WebParam(name = "subject") Subject subject, // - @WebParam(name = "entityContext") EntityContext entityContext, // - @WebParam(name = "driftConfiguration") DriftConfiguration driftConfiguration) throws Exception; + @WebParam(name = "criteria") DriftCriteria criteria) throws Exception; + } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java deleted file mode 100644 index 9bad08f..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.rhq.enterprise.server.drift; - -import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; - -import java.io.File; -import java.util.Iterator; - -import javax.ejb.EJB; -import javax.ejb.Stateless; -import javax.ejb.TransactionAttribute; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.jboss.remoting.CannotConnectException; - -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.configuration.Configuration; -import org.rhq.core.domain.criteria.DriftChangeSetCriteria; -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.DriftComposite; -import org.rhq.core.domain.drift.DriftConfiguration; -import org.rhq.core.domain.drift.DriftSnapshot; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.server.RHQConstants; -import org.rhq.enterprise.server.agentclient.AgentClient; -import org.rhq.enterprise.server.auth.SubjectManagerLocal; -import org.rhq.enterprise.server.core.AgentManagerLocal; -import org.rhq.enterprise.server.plugin.pc.MasterServerPluginContainer; -import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginContainer; -import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; -import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginManager; -import org.rhq.enterprise.server.util.LookupUtil; - -@Stateless -public class DriftServerBean implements DriftServerLocal, DriftServerRemote { - - // TODO Should security checks be handled here instead of delegating to the drift plugin? - // Currently any security checks that need to be performed are delegated to the plugin. - // This is fine *so far* since the only plugin is the default which is our existing SLSB - // layer backed by the RHQ database. If the plugins are only supposed to be responsible - // for persistence management of drift entities and content, then they should not be - // responsible for other concerns like security. - - private Log log = LogFactory.getLog(DriftServerBean.class); - - @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME) - private EntityManager entityMgr; - - @EJB - private SubjectManagerLocal subjectMgr; - - @EJB - private AgentManagerLocal agentMgr; - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, - DriftChangeSetCriteria criteria) { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - return driftServerPlugin.findDriftChangeSetsByCriteria(subject, criteria); - } - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - return driftServerPlugin.findDriftsByCriteria(subject, criteria); - } - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - return driftServerPlugin.findDriftCompositesByCriteria(subject, criteria); - } - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public void saveChangeSet(int resourceId, File changeSetZip) throws Exception { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - driftServerPlugin.saveChangeSet(resourceId, changeSetZip); - } - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public void saveChangeSetFiles(File changeSetFilesZip) throws Exception { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - driftServerPlugin.saveChangeSetFiles(changeSetFilesZip); - } - - @Override - @TransactionAttribute(NOT_SUPPORTED) - public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { - DriftServerPluginFacet driftServerPlugin = getServerPlugin(); - return driftServerPlugin.createSnapshot(subject, criteria); - } - - DriftServerPluginFacet getServerPlugin() { - MasterServerPluginContainer masterPC = LookupUtil.getServerPluginService().getMasterPluginContainer(); - if (masterPC == null) { - log.warn(MasterServerPluginContainer.class.getSimpleName() + " is not started yet"); - return null; - } - - DriftServerPluginContainer pc = masterPC.getPluginContainerByClass(DriftServerPluginContainer.class); - if (pc == null) { - log.warn(DriftServerPluginContainer.class + " has not been loaded by the " + masterPC.getClass() + " yet"); - return null; - } - - DriftServerPluginManager pluginMgr = (DriftServerPluginManager) pc.getPluginManager(); - - return pluginMgr.getDriftServerPluginComponent(); - } - - @Override - public void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig) { - switch (entityContext.getType()) { - case Resource: - int resourceId = entityContext.getResourceId(); - Resource resource = entityMgr.find(Resource.class, resourceId); - if (null == resource) { - throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); - } - - for (Iterator<Configuration> i = resource.getDriftConfigurations().iterator(); i.hasNext();) { - DriftConfiguration dc = new DriftConfiguration(i.next()); - if (dc.getName().equals(driftConfig.getName())) { - i.remove(); - break; - } - } - - resource.getDriftConfigurations().add(driftConfig.getConfiguration()); - entityMgr.merge(resource); - - AgentClient agentClient = agentMgr.getAgentClient(subjectMgr.getOverlord(), resourceId); - DriftAgentService service = agentClient.getDriftAgentService(); - try { - service.updateDriftDetection(resourceId, driftConfig); - } catch (Exception e) { - log.warn(" Unable to inform agent of unscheduled drift detection [" + driftConfig + "]", e); - } - - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); - } - } - - @Override - public DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId) { - DriftConfiguration result = null; - - switch (entityContext.getType()) { - case Resource: - Resource resource = entityMgr.find(Resource.class, entityContext.getResourceId()); - if (null == resource) { - throw new IllegalArgumentException("Entity not found [" + entityContext + "]"); - } - - for (Configuration config : resource.getDriftConfigurations()) { - if (config.getId() == driftConfigId) { - result = new DriftConfiguration(config); - break; - } - } - - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); - } - - if (null == result) { - throw new IllegalArgumentException("Drift Configuration Id [" + driftConfigId - + "] not found for entityContext [" + entityContext + "]"); - } - - return result; - } - - @Override - public void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig) { - switch (context.getType()) { - case Resource: - int resourceId = context.getResourceId(); - Resource resource = entityMgr.find(Resource.class, resourceId); - if (null == resource) { - throw new IllegalArgumentException("Resource not found [" + resourceId + "]"); - } - - AgentClient agentClient = agentMgr.getAgentClient(subjectMgr.getOverlord(), resourceId); - DriftAgentService service = agentClient.getDriftAgentService(); - // 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); - } 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 + "]"); - } - - break; - - default: - throw new IllegalArgumentException("Entity Context Type not supported [" + context + "]"); - } - } - -} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java deleted file mode 100644 index 3c9da33..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.rhq.enterprise.server.drift; - -import java.io.File; - -import javax.ejb.Local; - -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.DriftCriteria; -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.DriftSnapshot; -import org.rhq.core.domain.util.PageList; - -@Local -public interface DriftServerLocal { - - void saveChangeSet(int resourceId, File changeSetZip) throws Exception; - - void saveChangeSetFiles(File changeSetFilesZip) throws Exception; - - void updateDriftConfiguration(Subject subject, EntityContext entityContext, DriftConfiguration driftConfig); - - DriftConfiguration getDriftConfiguration(Subject subject, EntityContext entityContext, int driftConfigId); - - void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig); - - PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); - - PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria); - - PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria); - - DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); - -} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java deleted file mode 100644 index 33f1aa7..0000000 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.rhq.enterprise.server.drift; - -import javax.ejb.Remote; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.criteria.DriftChangeSetCriteria; -import org.rhq.core.domain.drift.DriftChangeSet; -import org.rhq.core.domain.drift.DriftSnapshot; -import org.rhq.core.domain.util.PageList; - -@Remote -public interface DriftServerRemote { - - PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); - - DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); - -} 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 new file mode 100644 index 0000000..4cb139b --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerBean.java @@ -0,0 +1,361 @@ +/* + * 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.server.drift; + +import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.Hibernate; + +import org.rhq.common.drift.ChangeSetReader; +import org.rhq.common.drift.ChangeSetReaderImpl; +import org.rhq.common.drift.DirectoryEntry; +import org.rhq.common.drift.FileEntry; +import org.rhq.common.drift.Headers; +import org.rhq.core.clientapi.agent.drift.DriftAgentService; +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +import org.rhq.core.domain.criteria.DriftCriteria; +import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; +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.DriftFile; +import org.rhq.core.domain.drift.DriftFileStatus; +import org.rhq.core.domain.drift.DriftSnapshot; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.JPADriftChangeSet; +import org.rhq.core.domain.drift.JPADriftFile; +import org.rhq.core.domain.drift.JPADriftFileBits; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.ZipUtil; +import org.rhq.core.util.file.FileUtil; +import org.rhq.enterprise.server.RHQConstants; +import org.rhq.enterprise.server.agentclient.AgentClient; +import org.rhq.enterprise.server.auth.SubjectManagerLocal; +import org.rhq.enterprise.server.core.AgentManagerLocal; +import org.rhq.enterprise.server.util.CriteriaQueryGenerator; +import org.rhq.enterprise.server.util.CriteriaQueryRunner; + +/** + * The SLSB method implementation needed to support the JPA (RHQ Default) Drift Server Plugin. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +@Stateless +public class JPADriftServerBean implements JPADriftServerLocal { + private final Log log = LogFactory.getLog(this.getClass()); + + @EJB + AgentManagerLocal agentManager; + + @EJB + JPADriftServerLocal JPADriftServer; + + @EJB + SubjectManagerLocal subjectManager; + + @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME) + private EntityManager entityManager; + + @Override + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + // TODO security checks + DriftSnapshot snapshot = new DriftSnapshot(); + PageList<? extends DriftChangeSet<?>> changeSets = findDriftChangeSetsByCriteria(subject, criteria); + + for (DriftChangeSet<?> changeSet : changeSets) { + snapshot.add(changeSet); + } + + return snapshot; + } + + @Override + public PageList<JPADriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { + + JPADriftChangeSetCriteria jpaCriteria = (criteria instanceof JPADriftChangeSetCriteria) ? (JPADriftChangeSetCriteria) criteria + : new JPADriftChangeSetCriteria(criteria); + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); + CriteriaQueryRunner<JPADriftChangeSet> queryRunner = new CriteriaQueryRunner<JPADriftChangeSet>(jpaCriteria, + generator, entityManager); + PageList<JPADriftChangeSet> result = queryRunner.execute(); + + return result; + } + + @Override + public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { + + PageList<JPADrift> drifts = findDriftsByCriteria(subject, criteria); + PageList<DriftComposite> composites = new PageList<DriftComposite>(); + for (JPADrift drift : drifts) { + composites.add(new DriftComposite(drift, drift.getChangeSet().getResource())); + } + return composites; + } + + @Override + public PageList<JPADrift> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + + JPADriftCriteria jpaCriteria = (criteria instanceof JPADriftCriteria) ? (JPADriftCriteria) criteria + : new JPADriftCriteria(criteria); + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); + CriteriaQueryRunner<JPADrift> queryRunner = new CriteriaQueryRunner<JPADrift>(jpaCriteria, generator, + entityManager); + PageList<JPADrift> result = queryRunner.execute(); + + return result; + } + + @Override + public JPADriftFile getDriftFile(Subject subject, String sha256) { + JPADriftFile result = entityManager.find(JPADriftFile.class, sha256); + return result; + } + + @Override + public JPADriftFile persistDriftFile(JPADriftFile driftFile) { + + entityManager.persist(driftFile); + return driftFile; + } + + @Override + @TransactionAttribute(REQUIRES_NEW) + public void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception { + + JPADriftFileBits df = entityManager.find(JPADriftFileBits.class, driftFile.getHashId()); + if (null == df) { + throw new IllegalArgumentException("JPADriftFile not found [" + driftFile.getHashId() + "]"); + } + df.setData(Hibernate.createBlob(new BufferedInputStream(data))); + df.setStatus(DriftFileStatus.LOADED); + } + + @Override + @TransactionAttribute(REQUIRES_NEW) + public void storeChangeSet(Subject subject, final int resourceId, File changeSetZip) throws Exception { + final Resource resource = entityManager.find(Resource.class, resourceId); + if (null == resource) { + throw new IllegalArgumentException("Resource not found [" + resourceId + "]"); + } + + try { + ZipUtil.walkZipFile(changeSetZip, new ChangeSetFileVisitor() { + + @Override + public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception { + List<JPADriftFile> emptyDriftFiles = new ArrayList<JPADriftFile>(); + JPADriftChangeSet driftChangeSet = null; + + try { + ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader( + stream))); + + // store the new change set info (not the actual blob) + DriftConfiguration config = findDriftConfiguration(resource, reader.getHeaders()); + int version = getChangeSetVersion(resource, config); + + if (config == null) { + log.error("Unable to locate DriftConfiguration for Resource [" + resource + + "]. Change set cannot be saved."); + return false; + } + + DriftChangeSetCategory category = reader.getHeaders().getType(); + driftChangeSet = new JPADriftChangeSet(resource, version, category, config.getId()); + entityManager.persist(driftChangeSet); + + for (DirectoryEntry dir = reader.readDirectoryEntry(); null != dir; dir = reader + .readDirectoryEntry()) { + + for (Iterator<FileEntry> i = dir.iterator(); i.hasNext();) { + FileEntry entry = i.next(); + JPADriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), + (List<JPADriftFile>) emptyDriftFiles); + JPADriftFile newDriftFile = getDriftFile(entry.getNewSHA(), + (List<JPADriftFile>) emptyDriftFiles); + + // TODO Figure out an efficient way to save coverage change sets. + // The initial/coverage change set could contain hundreds or even thousands + // of entries. We probably want to consider doing some kind of batch insert + // + // jsanda + + // use a path with only forward slashing to ensure consistent paths across reports + String path = new File(dir.getDirectory(), entry.getFile()).getPath(); + path = FileUtil.useForwardSlash(path); + JPADrift drift = new JPADrift(driftChangeSet, path, entry.getType(), oldDriftFile, + newDriftFile); + entityManager.persist(drift); + + } + } + // send a message to the agent requesting the empty JPADriftFile content + if (!emptyDriftFiles.isEmpty()) { + + AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), + resourceId); + DriftAgentService service = agentClient.getDriftAgentService(); + try { + if (service.requestDriftFiles(resourceId, reader.getHeaders(), emptyDriftFiles)) { + for (DriftFile driftFile : emptyDriftFiles) { + driftFile.setStatus(DriftFileStatus.REQUESTED); + } + } + } catch (Exception e) { + log.warn(" Unable to inform agent of drift file request [" + emptyDriftFiles + "]", e); + } + } + } catch (Exception e) { + String msg = "Failed to store drift changeset [" + driftChangeSet + "]"; + log.error(msg, e); + return false; + } + + return true; + } + }); + } catch (Exception e) { + String msg = "Failed to store drift changeset for "; + if (null != resource) { + msg += resource; + } else { + msg += ("resourceId " + resourceId); + } + log.error(msg, e); + + } finally { + // delete the changeSetFile? + } + } + + private JPADriftFile getDriftFile(String sha256, List<JPADriftFile> emptyDriftFiles) { + JPADriftFile result = null; + + if (null == sha256 || "0".equals(sha256)) { + return result; + } + + result = entityManager.find(JPADriftFile.class, sha256); + // if the JPADriftFile is not yet in the db, then it needs to be fetched from the agent + if (null == result) { + result = persistDriftFile(new JPADriftFile(sha256)); + emptyDriftFiles.add(result); + } + + 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 (Configuration config : resource.getDriftConfigurations()) { + DriftConfiguration driftConfig = new DriftConfiguration(config); + if (driftConfig.getName().equals(headers.getDriftConfigurationName())) { + return driftConfig; + } + } + return null; + } + + private abstract class ChangeSetFileVisitor implements ZipUtil.ZipEntryVisitor { + } + + @Override + public void storeFiles(Subject subject, File filesZip) throws Exception { + // No longer using ZipUtil.walkZipFile because an IOException was getting thrown + // after reading the first entry, resulting in subsequent entries being skipped. + // DriftFileVisitor passed the ZipInputStream to Hibernate.createBlob, and either + // Hibernate, the JDBC driver, or something else is closing the stream which in + // turn causes the exception. + // + // jsanda + + String zipFileName = filesZip.getName(); + File tmpDir = new File(System.getProperty("java.io.tmpdir")); + File dir = new File(tmpDir, zipFileName.substring(0, zipFileName.indexOf("."))); + dir.mkdir(); + + ZipUtil.unzipFile(filesZip, dir); + for (File file : dir.listFiles()) { + JPADriftFile driftFile = new JPADriftFile(file.getName()); + try { + JPADriftServer.persistDriftFileData(driftFile, new FileInputStream(file)); + } catch (Exception e) { + LogFactory.getLog(getClass()).info("Skipping bad drift file", e); + } + } + + for (File file : dir.listFiles()) { + file.delete(); + } + boolean deleted = dir.delete(); + if (!deleted) { + LogFactory.getLog(getClass()).info( + "Unable to delete " + dir.getAbsolutePath() + ". This directory and " + + "its contents are no longer needed. It can be deleted."); + } + } +} 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 new file mode 100644 index 0000000..7f1516c --- /dev/null +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/JPADriftServerLocal.java @@ -0,0 +1,111 @@ +/* + * 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.server.drift; + +import java.io.File; +import java.io.InputStream; + +import javax.ejb.Local; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +import org.rhq.core.domain.criteria.DriftCriteria; +import org.rhq.core.domain.drift.DriftComposite; +import org.rhq.core.domain.drift.DriftSnapshot; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.JPADriftChangeSet; +import org.rhq.core.domain.drift.JPADriftFile; +import org.rhq.core.domain.util.PageList; + +/** + * The SLSB methods needed to support the JPA (RHQ Default) Drift Server Plugin. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +@Local +public interface JPADriftServerLocal { + + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + + /** + * Simple get method for a JPADriftFile. Does not return the content. + * @param subject + * @param sha256 + * @return The JPADriftFile sans content. + */ + JPADriftFile getDriftFile(Subject subject, String sha256); + + /** + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The DriftChangeSets matching the criteria + */ + PageList<JPADriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); + + PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria); + + /** + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The Drifts matching the criteria + */ + PageList<JPADrift> findDriftsByCriteria(Subject subject, DriftCriteria criteria); + + /** + * SUPPORTS JPA DRIFT SERVER PLUGIN + * @param driftFile + * @return + * @throws Exception + */ + JPADriftFile persistDriftFile(JPADriftFile driftFile) throws Exception; + + /** + * SUPPORTS JPA DRIFT SERVER PLUGIN + * @param driftFile + * @param data + * @throws Exception + */ + void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception; + + /** + * This method stores the provided change-set file for the resource. The version will be incremented based + * on the max version of existing change-sets for the resource. The change-set will be processed generating + * requests for drift file content and/or drift instances as required. + * + * @param resourceId The resource for which the change-set is being reported. + * @param changeSetZip The change-set zip file + * @throws Exception + */ + void storeChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception; + + /** + * This method stores the provided drift files. The files should correspond to requested drift files. + * The unzipped files will have their sha256 generated. Those not corresponding to needed content will + * be logged and ignored. + * + * @param filesZip The change-set zip file + * @throws Exception + */ + void storeFiles(Subject subject, File filesZip) throws Exception; + +} 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 5130a5a..8a7ea91 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 @@ -27,27 +27,48 @@ 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.DriftComposite; +import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent;
/** - * All drift server plugins must implement this facet. + * All drift server plugins must implement this facet. The methods here must all be defined in + * DriftManagerLocal as well. See DriftManagerLocal for jdoc of these methods. * * @author Jay Shaughnessy * @author John Sanda */ -public interface DriftServerPluginFacet extends ServerPluginComponent { +public interface DriftServerPluginFacet {
- PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria);
- PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria); + /** + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The DriftChangeSets matching the criteria + */ + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria);
PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria);
- void saveChangeSet(int resourceId, File changeSetZip) throws Exception; + /** + * Standard criteria based fetch method + * @param subject + * @param criteria + * @return The Drifts matching the criteria + */ + PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria);
- void saveChangeSetFiles(File changeSetFilesZip) throws Exception; + /** + * Simple get method for a DriftFile. Does not return the content. + * @param subject + * @param hashId + * @return The DriftFile sans content. + */ + DriftFile getDriftFile(Subject subject, String hashId) throws Exception;
- DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + void saveChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception; + + void saveChangeSetFiles(Subject subject, File changeSetFilesZip) throws Exception; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java index 480d60c..f6b7b58 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java @@ -105,8 +105,8 @@ import org.rhq.enterprise.server.discovery.DiscoveryBossBean; import org.rhq.enterprise.server.discovery.DiscoveryBossLocal; import org.rhq.enterprise.server.drift.DriftManagerBean; import org.rhq.enterprise.server.drift.DriftManagerLocal; -import org.rhq.enterprise.server.drift.DriftServerBean; -import org.rhq.enterprise.server.drift.DriftServerLocal; +import org.rhq.enterprise.server.drift.JPADriftServerBean; +import org.rhq.enterprise.server.drift.JPADriftServerLocal; import org.rhq.enterprise.server.entitlement.EntitlementManagerBean; import org.rhq.enterprise.server.entitlement.EntitlementManagerLocal; import org.rhq.enterprise.server.event.EventManagerBean; @@ -453,16 +453,14 @@ public final class LookupUtil { return lookupLocal(ContentSourceManagerBean.class); }
- public static DriftServerLocal getDriftServer() { - return lookupLocal(DriftServerBean.class); - } - - // TODO should this reference to DriftManagerLocal be removed? - // DriftManagerBean should only be referenced from the drift-rhq server plugin public static DriftManagerLocal getDriftManager() { return lookupLocal(DriftManagerBean.class); }
+ public static JPADriftServerLocal getJPADriftServer() { + return lookupLocal(JPADriftServerBean.class); + } + public static RepoManagerLocal getRepoManagerLocal() { return lookupLocal(RepoManagerBean.class); } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java index 75ea9a4..c9ee8c6 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java @@ -80,6 +80,8 @@ import org.rhq.core.domain.criteria.BundleFileCriteria; import org.rhq.core.domain.criteria.BundleResourceDeploymentCriteria; import org.rhq.core.domain.criteria.BundleVersionCriteria; import org.rhq.core.domain.criteria.Criteria; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +import org.rhq.core.domain.criteria.DriftCriteria; import org.rhq.core.domain.criteria.EventCriteria; import org.rhq.core.domain.criteria.GroupOperationHistoryCriteria; import org.rhq.core.domain.criteria.InstalledPackageCriteria; @@ -96,7 +98,9 @@ import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria; import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.criteria.RoleCriteria; import org.rhq.core.domain.criteria.SubjectCriteria; -import org.rhq.core.domain.drift.DriftConfiguration; +import org.rhq.core.domain.drift.Drift; +import org.rhq.core.domain.drift.DriftChangeSet; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.event.Event; import org.rhq.core.domain.event.EventSeverity; import org.rhq.core.domain.measurement.Availability; @@ -590,9 +594,20 @@ public class WebservicesManagerBean implements WebservicesRemote { // DRIFTMANAGER: BEGIN ----------------------------------
@Override - public void detectDrift(Subject subject, EntityContext entityContext, DriftConfiguration driftConfiguration) + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) throws Exception { + return driftManager.createSnapshot(subject, criteria); + } + + @Override + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) throws Exception { + return driftManager.findDriftChangeSetsByCriteria(subject, criteria); + } + + @Override + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) throws Exception { - driftManager.detectDrift(subject, entityContext, driftConfiguration); + return driftManager.findDriftsByCriteria(subject, criteria); }
// DRIFTMANAGER: END ------------------------------------ diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.txt b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.txt index c3c90f4..af59629 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.txt +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.txt @@ -1,4 +1,4 @@ -test-2 +test-1 /test D dir 1 diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip index c0137e7..95e7a76 100644 Binary files a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip and b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/drift/changeset-2.zip differ 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 d58c3f1..fd1eb79 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 @@ -31,6 +31,7 @@ import org.rhq.core.domain.criteria.ResourceCriteria; 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.DriftFile; import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.drift.dto.DriftChangeSetDTO; import org.rhq.core.domain.drift.dto.DriftDTO; @@ -39,6 +40,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.ZipUtil; import org.rhq.core.util.file.FileUtil; +import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent; import org.rhq.enterprise.server.plugin.pc.ServerPluginContext; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet; @@ -46,7 +48,7 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; import org.rhq.enterprise.server.resource.ResourceManagerLocal;
-public class MongoDBDriftServer implements DriftServerPluginFacet { +public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
//private final Log log = LogFactory.getLog(MongoDBDriftServer.class);
@@ -81,7 +83,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override - public void saveChangeSet(final int resourceId, final File changeSetZip) throws Exception { + public void saveChangeSet(final Subject subject, final int resourceId, final File changeSetZip) throws Exception { ZipUtil.walkZipFile(changeSetZip, new ZipUtil.ZipEntryVisitor() { @Override public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception { @@ -113,7 +115,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override - public void saveChangeSetFiles(File changeSetFilesZip) throws Exception { + public void saveChangeSetFiles(final Subject subject, final File changeSetFilesZip) throws Exception {
}
@@ -187,6 +189,12 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override + public DriftFile getDriftFile(Subject subject, String hashId) throws Exception { + // TODO + return null; + } + + @Override public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { return null; } @@ -234,5 +242,4 @@ public class MongoDBDriftServer implements DriftServerPluginFacet {
return dto; } - } diff --git a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java deleted file mode 100644 index 7a28b53..0000000 --- a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java +++ /dev/null @@ -1,107 +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.server.plugins.drift; - -import static org.rhq.enterprise.server.util.LookupUtil.getDriftManager; - -import java.io.File; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.criteria.DriftChangeSetCriteria; -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.DriftComposite; -import org.rhq.core.domain.drift.DriftSnapshot; -import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.server.drift.DriftManagerLocal; -import org.rhq.enterprise.server.plugin.pc.ServerPluginContext; -import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; - -/** - * A drift server-side plugin component that the server uses to process drift files. - * - * @author Jay Shaughnessy - * @author John Sanda - */ -public class DriftServerPluginComponent implements DriftServerPluginFacet { - - private final Log log = LogFactory.getLog(DriftServerPluginComponent.class); - - @SuppressWarnings("unused") - private ServerPluginContext context; - - public void initialize(ServerPluginContext context) throws Exception { - this.context = context; - log.debug("The RHQ Drift plugin has been initialized!!! : " + this); - } - - public void start() { - log.debug("The RHQ Drift plugin has started!!! : " + this); - } - - public void stop() { - log.debug("The RHQ Drift plugin has stopped!!! : " + this); - } - - public void shutdown() { - log.debug("The RHQ Drift plugin has been shut down!!! : " + this); - } - - @Override - public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, - DriftChangeSetCriteria criteria) { - PageList<? extends DriftChangeSet<?>> results = getDriftManager().findDriftChangeSetsByCriteria(subject, - criteria); - return results; - } - - @Override - public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { - PageList<? extends Drift<?, ?>> results = getDriftManager().findDriftsByCriteria(subject, criteria); - return results; - } - - @Override - public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { - return getDriftManager().findDriftCompositesByCriteria(subject, criteria); - } - - @Override - public void saveChangeSet(int resourceId, File changeSetZip) throws Exception { - DriftManagerLocal driftMgr = getDriftManager(); - driftMgr.storeChangeSet(resourceId, changeSetZip); - } - - @Override - public void saveChangeSetFiles(File changeSetFilesZip) throws Exception { - DriftManagerLocal driftMgr = getDriftManager(); - driftMgr.storeFiles(changeSetFilesZip); - } - - @Override - public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { - DriftManagerLocal driftMgr = getDriftManager(); - return driftMgr.createSnapshot(subject, criteria); - } -} 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 new file mode 100644 index 0000000..e213e2f --- /dev/null +++ b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/JPADriftServerPluginComponent.java @@ -0,0 +1,116 @@ +/* + * 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.server.plugins.drift; + +import static org.rhq.enterprise.server.util.LookupUtil.getJPADriftServer; + +import java.io.File; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +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.DriftComposite; +import org.rhq.core.domain.drift.DriftFile; +import org.rhq.core.domain.drift.DriftSnapshot; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.JPADriftChangeSet; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent; +import org.rhq.enterprise.server.plugin.pc.ServerPluginContext; +import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; + +/** + * A drift server-side plugin component that the server uses to process drift files. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public class JPADriftServerPluginComponent implements DriftServerPluginFacet, ServerPluginComponent { + + private final Log log = LogFactory.getLog(JPADriftServerPluginComponent.class); + + @SuppressWarnings("unused") + private ServerPluginContext context; + + @Override + public void initialize(ServerPluginContext context) throws Exception { + this.context = context; + log.debug("The RHQ Drift plugin has been initialized!!! : " + this); + } + + @Override + public void start() { + log.debug("The RHQ Drift plugin has started!!! : " + this); + } + + @Override + public void stop() { + log.debug("The RHQ Drift plugin has stopped!!! : " + this); + } + + @Override + public void shutdown() { + log.debug("The RHQ Drift plugin has been shut down!!! : " + this); + } + + @Override + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + return getJPADriftServer().createSnapshot(subject, criteria); + } + + @Override + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) { + PageList<JPADriftChangeSet> results = getJPADriftServer().findDriftChangeSetsByCriteria(subject, criteria); + return results; + } + + @Override + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + PageList<JPADrift> results = getJPADriftServer().findDriftsByCriteria(subject, criteria); + return results; + } + + @Override + public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { + return getJPADriftServer().findDriftCompositesByCriteria(subject, criteria); + } + + @Override + public DriftFile getDriftFile(Subject subject, String hashId) throws Exception { + return getJPADriftServer().getDriftFile(subject, hashId); + } + + @Override + public void saveChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception { + getJPADriftServer().storeChangeSet(subject, resourceId, changeSetZip); + } + + @Override + public void saveChangeSetFiles(Subject subject, File changeSetFilesZip) throws Exception { + getJPADriftServer().storeFiles(subject, changeSetFilesZip); + } + +} diff --git a/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml index e245d04..0131cd7 100644 --- a/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml @@ -15,7 +15,7 @@ Provides back-end store and retrieve for drift files. ]]></serverplugin:help>
- <serverplugin:plugin-component class="DriftServerPluginComponent"> + <serverplugin:plugin-component class="JPADriftServerPluginComponent"> <!-- <serverplugin:control name="testControl" description="A test control operation"> </serverplugin:control>
commit 7da15261e884d1acbdea504afdf4256fa650713f Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 13:39:25 2011 -0400
ren-enabling and fixing test
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 05044eb..b71224f 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 @@ -141,7 +141,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); assertEquals(2, changeSets.size()); changeSet = changeSets.get(0); - assertEquals("The change set version is wrong", 0, changeSet.getVersion()); + assertEquals("", 0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size()); changeSet = changeSets.get(1); assertEquals("The change set version is wrong", 0, changeSet.getVersion()); @@ -157,7 +157,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus()); }
- @Test(enabled = false) + @Test(enabled = ENABLE_TESTS) public void testDriftConfig() throws Exception { Configuration config = new Configuration(); config.put(new PropertySimple("name", "testDriftConfig")); @@ -179,7 +179,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); Set<Configuration> driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(1, driftConfigs.size()); + assertEquals(3, driftConfigs.size()); DriftConfiguration driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getName(), driftConfig.getName()); @@ -194,7 +194,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(1, driftConfigs.size()); + assertEquals(3, driftConfigs.size()); driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getName(), driftConfig.getName()); @@ -216,7 +216,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(2, driftConfigs.size()); + assertEquals(4, driftConfigs.size()); for (Iterator<Configuration> i = driftConfigs.iterator(); i.hasNext();) { driftConfig = new DriftConfiguration(i.next()); if ("testDriftConfig".equals(driftConfig.getName())) { @@ -228,7 +228,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getBasedir(), driftConfig.getBasedir()); assertEquals(driftConfigPojo.getInterval(), driftConfig.getInterval()); - } else { + } else if (!"test-1".equals(driftConfig.getName()) && !"test-2".equals(driftConfig.getName())) { fail("Unexpected drift config name: " + driftConfig.getName()); } } @@ -239,7 +239,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertEquals(1, resources.size()); driftConfigs = resources.get(0).getDriftConfigurations(); assertNotNull(driftConfigs); - assertEquals(1, driftConfigs.size()); + assertEquals(3, driftConfigs.size()); driftConfig = new DriftConfiguration(driftConfigs.iterator().next()); assertTrue(driftConfig.getConfiguration().getId() > 0); // persisted assertEquals(driftConfigPojo.getName(), driftConfig.getName());
commit 043ed8eadfcea376809e0284e6513680dfdf6e1b Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 4 12:29:35 2011 -0400
rename the method to be more descriptive
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 20e5bf1..9a05c5f 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 @@ -164,12 +164,12 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid
/** * Returns the link (as a string) that the client should be redirected to - * if the given node is clicked. + * if the given node's details are to be shown. * - * @param node the node whose target link is to be returned - * @return the node's link + * @param node the node whose target details link is to be returned + * @return the node's details link */ - protected abstract String getNodeTargetLink(TreeNode node); + protected abstract String getNodeDetailsLink(TreeNode node);
/** * Builds the right-mouse-click context menu for the given drift node @@ -197,7 +197,7 @@ public abstract class AbstractDriftChangeSetsTreeView extends LocatableTreeGrid MenuItem detailsItem = new MenuItem(MSG.common_title_details()); detailsItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { - String link = getNodeTargetLink(node); + String link = getNodeDetailsLink(node); if (link != null) { CoreGUI.goToView(link); } 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 51f2ec2..527513c 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 @@ -44,7 +44,8 @@ public class ResourceDriftChangeSetsTreeView extends AbstractDriftChangeSetsTree setDataSource(new ResourceDriftChangeSetsTreeDataSource(canManageDrift, context)); }
- protected String getNodeTargetLink(TreeNode node) { + @Override + protected String getNodeDetailsLink(TreeNode node) { if (node instanceof DriftTreeNode) { String driftIdStr = node.getAttribute(AbstractDriftChangeSetsTreeDataSource.ATTR_ID).split("_")[1]; String path = LinkManager.getDriftHistoryLink(this.context.resourceId, driftIdStr);
commit 90b60f72e109b6ce6373c2f1358dafd06c751515 Author: John Mazzitelli mazz@redhat.com Date: Thu Aug 4 12:20:55 2011 -0400
make the tree auto-refresh
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftChangeSetsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftChangeSetsView.java index 56b4aa2..9822575 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftChangeSetsView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/drift/DriftChangeSetsView.java @@ -25,6 +25,7 @@ import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.core.domain.common.EntityContext; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableToolStrip; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; @@ -34,10 +35,11 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * * @author John Mazzitelli */ -public class DriftChangeSetsView extends LocatableVLayout { +public class DriftChangeSetsView extends LocatableVLayout implements RefreshableView {
private EntityContext context; private boolean hasWriteAccess; + private ResourceDriftChangeSetsTreeView tree;
protected DriftChangeSetsView(String locatorId, String tableTitle, EntityContext context, boolean hasWriteAccess) { super(locatorId); @@ -49,9 +51,8 @@ public class DriftChangeSetsView extends LocatableVLayout { protected void onDraw() { super.onDraw();
- final ResourceDriftChangeSetsTreeView tree = new ResourceDriftChangeSetsTreeView(extendLocatorId("Tree"), - this.hasWriteAccess, this.context); - addMember(tree); + this.tree = new ResourceDriftChangeSetsTreeView(extendLocatorId("Tree"), this.hasWriteAccess, this.context); + addMember(this.tree);
ToolStrip toolStrip = new LocatableToolStrip(extendLocatorId("toolstrip")); toolStrip.setBackgroundImage(null); @@ -61,7 +62,7 @@ public class DriftChangeSetsView extends LocatableVLayout { IButton refreshButton = new LocatableIButton(extendLocatorId("refreshButton"), MSG.common_button_refresh()); refreshButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { - tree.refresh(); + DriftChangeSetsView.this.tree.refresh(); } }); toolStrip.addMember(refreshButton); @@ -75,4 +76,11 @@ public class DriftChangeSetsView extends LocatableVLayout { protected boolean hasWriteAccess() { return this.hasWriteAccess; } + + @Override + public void refresh() { + if (this.tree != null) { + this.tree.refresh(); + } + } }
commit d3eaa1037b34f852dd638f37644a79d822509dd4 Author: John Sanda jsanda@redhat.com Date: Thu Aug 4 10:24:51 2011 -0400
fixing failing test
The test failure was caused as a result of a code change in DriftManagerBean, and the corresponding test code was not updated. The logic for setting change set version numbers was updated to assign unique version numbers across drift configs (and their owning resource) whereas previously version numbers were not unique for change sets belonging to a particular drift config.
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 6520ce9..05044eb 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 @@ -141,10 +141,10 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); assertEquals(2, changeSets.size()); changeSet = changeSets.get(0); - assertEquals(0, changeSet.getVersion()); + assertEquals("The change set version is wrong", 0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size()); changeSet = changeSets.get(1); - assertEquals(1, changeSet.getVersion()); + assertEquals("The change set version is wrong", 0, changeSet.getVersion()); assertEquals(1, changeSet.getDrifts().size()); Drift<?, ?> drift = changeSet.getDrifts().iterator().next(); assertEquals("dir/filename.ext", drift.getPath());
commit 27ae72b6db6a638bbf787df47cc962c11bf63257 Author: John Sanda jsanda@redhat.com Date: Wed Aug 3 22:22:08 2011 -0400
adding javadocs
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 b0cd61d..c6db79a 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 @@ -21,8 +21,18 @@ package org.rhq.core.domain.drift; import java.util.Set;
/** - * To support pluggable drift server implementations this Interface provides the contract required for - * defining and persisting each DriftChangeSet reported from an Agent. + * A DriftChangeSet is somewhat similar to a commit in version control systems. It contains + * information about files being monitored or tracked for drift detection. A change set + * tells us about files that are added, modified, and deleted. + * <p/> + * Agents generate and send change set reports to the RHQ server. This interface provides + * 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 + * in turn owned by a {@link org.rhq.core.domain.resource.Resource Resource} and a resource + * can have multiple drift configurations. * * @param <D> A server plugin's Drift implementation * @@ -30,27 +40,92 @@ import java.util.Set; * @author John Sanda */ public interface DriftChangeSet<D extends Drift<?, ?>> { + /** + * Returns a string that uniquely identifies the change set. The format of the string + * is implementation dependent and as such there is no requirement that the id be + * stored as a string, only that it has a string representation. + * + * @return A unique id as a string + */ String getId();
+ /** + * Sets the change set id which should be unique. Implementations are free to store the + * id in any format. + * + * @param id The change set identifier that should be unique + */ void setId(String id);
+ /** @return The time that the change set was created */ Long getCtime();
+ /** + * 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 + * version control system like SVN. + * + * @return The change set version number that is unique within the context of its + * owning {@link DriftConfiguration}. + */ 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 + * increasing order. The first change set saved should have a version of N, the second + * should have a value of N + 1, etc. + * + * @param version The version number. + */ void setVersion(int version);
+ /** + * Retturns the category that identifies the change set type. + * @return The change set category + * @see DriftChangeSetCategory + */ DriftChangeSetCategory getCategory();
+ /** + * Sets the change set category. + * + * @param category The category that identifies the change set type + * @see DriftChangeSetCategory + */ void setCategory(DriftChangeSetCategory category);
+ /** + * Returns the id of the owning drift configuration. 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. + * + * @return The {@link DriftConfiguration} id + */ int getDriftConfigurationId();
+ /** + * Sets the id of the owning drift configuration. Note that while server plugins are + * responsible for managing the persistence of change sets, the RHQ server manages the + * persistence of the drift configuration. + * + * @param id The {@link DriftConfiguration} id + */ void setDriftConfigurationId(int id);
+ /** + * Returns the id of the resource to which the drift configuration 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 + */ int getResourceId();
+ /** @return The entries that comprise this change set */ Set<D> getDrifts();
+ /** @param drifts The entries that make up this change set */ void setDrifts(Set<D> drifts); } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSetCategory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSetCategory.java index 5c3e436..2b938ad 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSetCategory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftChangeSetCategory.java @@ -23,12 +23,27 @@ package org.rhq.core.domain.drift;
/** - * Type of change set report. + * Type of change set report. There are two types of change sets, coverage and drift. A + * coverage change set is in effect a snapshot of the files that are being monitored for + * drift detection. A drift change set on the hand, represents a delta between one or more + * files on disk and their versions in the previous change set. + * <p/> + * A DriftChangeSetCategory has a single representation which is suitable for persisting + * in a database. * * @author Jay Shaughnesssy */ public enum DriftChangeSetCategory { + /** + * A coverage change set is a snapshot of the files that are being monitored for drift + * detection. + */ COVERAGE("C"), // Reports only on files being covered by a drift configuration. + + /** + * A drift change set represents a change between one or more files and their versions + * in the previous change set. + */ DRIFT("D"); // Reports on actual drift.
private final String code; @@ -37,10 +52,18 @@ public enum DriftChangeSetCategory { this.code = code; }
+ /** @return The single character code */ public String code() { return code; }
+ /** + * Parses the single character code into a DriftChangeSetCategory object. + * + * @param code A single character code + * @return The corresponding DriftChangeSetCategory + * @throws IllegalArgumentException if the code is not recognized + */ public static DriftChangeSetCategory fromCode(String code) { for (DriftChangeSetCategory type : DriftChangeSetCategory.values()) { if (type.code.equals(code)) {
commit 607e5aa25e51621b1886fb77fa71263fa78b13c8 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 3 09:23:04 2011 -0400
Make analogous addition of driftConfigId filter to change set criteria, in the refactored code.
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 d73c744..331400c 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 @@ -65,12 +65,13 @@ public class JPADriftChangeSetCriteria extends Criteria implements DriftChangeSe filterOverrides.put("createdBefore", "ctime <= ?");
if (null != changeSetCriteria) { - this.addFilterId(changeSetCriteria.getFilterId()); - this.addFilterResourceId(changeSetCriteria.getFilterResourceId()); this.addFilterCategory(changeSetCriteria.getFilterCategory()); this.addFilterCreatedAfter(changeSetCriteria.getFilterCreatedAfter()); this.addFilterCreatedBefore(changeSetCriteria.getFilterCreatedBefore()); + this.addFilterDriftConfigurationId(changeSetCriteria.getFilterDriftConfigurationId()); this.addFilterEndVersion(changeSetCriteria.getFilterEndVersion()); + this.addFilterId(changeSetCriteria.getFilterId()); + this.addFilterResourceId(changeSetCriteria.getFilterResourceId()); this.addFilterStartVersion(changeSetCriteria.getFilterStartVersion()); this.addFilterVersion(changeSetCriteria.getFilterVersion());
commit d459906cc666e125cb5eafe9a346c46fd831aa41 Author: Jay Shaughnessy jshaughn@redhat.com Date: Wed Aug 3 09:21:29 2011 -0400
Change eclipse .classpath for new morphia dep version.
diff --git a/.classpath b/.classpath index bdc2f4f..a46eaf4 100644 --- a/.classpath +++ b/.classpath @@ -117,8 +117,8 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/unitils/unitils-testng/3.1/unitils-testng-3.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-core-asl/1.7.4/jackson-core-asl-1.7.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.7.4/jackson-mapper-asl-1.7.4.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.3/mongo-java-driver-2.6.3.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/morphia/morphia/1.00-SNAPSHOT/morphia-1.00-SNAPSHOT.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.3/mongo-java-driver-2.6.3.jar"/> + <classpathentry kind="var" path="M2_REPO/com/google/code/morphia/morphia/0.99/morphia-0.99.jar"/> <classpathentry exported="true" kind="lib" path="modules/enterprise/remoting/webservices/target/rhq-remoting-webservices-4.1.0-SNAPSHOT/wsconsume-output"/> <classpathentry kind="src" path="modules/common/ant-bundle/src/main/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/drift-mongodb/src/main/java"/>
commit 73d50a6fde3bcbd8568e38e3978e2fee79c636c8 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 2 17:25:46 2011 -0400
Drift Refactoring - Settle on 'JPA' as the prefix for RHQ's default drift plugin. This avoids using the rhq project name in the naming scheme. And reflects that this is a JPA (well actually Hibernate) drift backend implementation. - Prefix more classes with 'Drift' for easier classification. - Settle on prefix-based naming for drift Criteria hierarchy - Add copyright and class-level jdoc to several classes - Ensure CoreGUI uses only GenericXXXCriteria classes and Interfaces. It was assuming the JPA drift impl in places. (note, 'Generic' was previously 'Basic' but is changed to better reflect that the class does not rely on any backend implementation choice.) - Change various signatures as needed to support drift plugin architecture. - remove a lot of warnings by qualifying type decls. - Reenable DriftManagerBeanTests
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 c269e5a..6137400 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 @@ -40,7 +40,7 @@ public interface DriftAgentService { * @param driftFiles * @return the results of the immediate scheduling */ - boolean requestDriftFiles(int resourceId, Headers headers, List<DriftFile> driftFiles); + boolean requestDriftFiles(int resourceId, Headers headers, List<? extends DriftFile> driftFiles);
/** * Execute drift detection immediately. If any drift is found, the agent will send the diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml index 8dbc06e..0675792 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml @@ -126,8 +126,8 @@ DEFAULT_PROPERTY_VALUE="false" FREAD_ONLY="FALSE"/>
<!-- default drift server plugin settings --> - <data ID="57" PROPERTY_KEY="ACTIVE_DRIFT_PLUGIN" PROPERTY_VALUE="drift-rhq" - DEFAULT_PROPERTY_VALUE="drift-rhq" FREAD_ONLY="FALSE"/> + <data ID="57" PROPERTY_KEY="ACTIVE_DRIFT_PLUGIN" PROPERTY_VALUE="drift-jpa" + DEFAULT_PROPERTY_VALUE="drift-jpa" FREAD_ONLY="FALSE"/>
</table>
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index fe5f1f6..98e7438 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3590,7 +3590,7 @@ <schema-directSQL> <statement desc="Adding drift server plugin active plugin system configuration property"> INSERT INTO rhq_system_config (id, property_key, property_value, default_property_value) - VALUES (57, 'ACTIVE_DRIFT_PLUGIN', 'drift-rhq', 'drift-rhq') + VALUES (57, 'ACTIVE_DRIFT_PLUGIN', 'drift-jpa', 'drift-jpa') </statement> </schema-directSQL> </schemaSpec> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BaseCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BaseCriteria.java index f377ade..b95ef28 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BaseCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BaseCriteria.java @@ -1,11 +1,28 @@ +/* + * 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 org.rhq.core.domain.util.PageControl;
/** * All criteria, regardless of the backend storage that will be queried with this criteria, needs - * to support certain base functionality (like paging). - * This base interface provides that common API. + * to support certain base functionality (like paging). This base interface provides that common API. * * @author John Sanda */ diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftChangeSetCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftChangeSetCriteria.java deleted file mode 100644 index ba46bc2..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftChangeSetCriteria.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.rhq.core.domain.criteria; - -import org.rhq.core.domain.drift.DriftChangeSetCategory; -import org.rhq.core.domain.util.PageControl; -import org.rhq.core.domain.util.PageOrdering; - -public class BasicDriftChangeSetCriteria implements DriftChangeSetCriteria { - - private static final long serialVersionUID = 1L; - - private String filterId; - - private String filterVersion; - - private String filterStartVersion; - - private String filterEndVersion; - - private Long filterCreatedAfter; - - private Long filterCreatedBefore; - - private Integer filterResourceId; - - private Integer filterDriftConfigId; - - private DriftChangeSetCategory filterCategory; - - private boolean fetchDrifts; - - private PageOrdering sortVersion; - - private PageControl pageControl; - - @Override - public void addFilterId(String filterId) { - this.filterId = filterId; - } - - @Override - public String getFilterId() { - return filterId; - } - - @Override - public void addFilterVersion(String filterVersion) { - this.filterVersion = filterVersion; - } - - @Override - public String getFilterVersion() { - return filterVersion; - } - - @Override - public void addFilterStartVersion(String filterStartVersion) { - this.filterStartVersion = filterStartVersion; - } - - @Override - public String getFilterStartVersion() { - return filterStartVersion; - } - - @Override - public void addFilterEndVersion(String filterEndVersion) { - this.filterEndVersion = filterEndVersion; - } - - @Override - public String getFilterEndVersion() { - return filterEndVersion; - } - - @Override - public void addFilterCreatedAfter(Long filterCreatedAfter) { - this.filterCreatedAfter = filterCreatedAfter; - } - - @Override - public Long getFilterCreatedAfter() { - return filterCreatedAfter; - } - - @Override - public void addFilterCreatedBefore(Long filterCreatedBefore) { - this.filterCreatedBefore = filterCreatedBefore; - } - - @Override - public Long getFilterCreatedBefore() { - return filterCreatedBefore; - } - - @Override - public void addFilterResourceId(Integer filterResourceId) { - this.filterResourceId = filterResourceId; - } - - @Override - public Integer getFilterResourceId() { - return filterResourceId; - } - - @Override - public void addFilterDriftConfigurationId(Integer filterDriftConfigId) { - this.filterDriftConfigId = filterDriftConfigId; - } - - @Override - public Integer getFilterDriftConfigurationId() { - return filterDriftConfigId; - } - - @Override - public void addFilterCategory(DriftChangeSetCategory filterCategory) { - this.filterCategory = filterCategory; - } - - @Override - public DriftChangeSetCategory getFilterCategory() { - return filterCategory; - } - - @Override - public void fetchDrifts(boolean fetchDrifts) { - this.fetchDrifts = fetchDrifts; - } - - @Override - public boolean isFetchDrifts() { - return fetchDrifts; - } - - @Override - public void addSortVersion(PageOrdering sortVersion) { - this.sortVersion = sortVersion; - } - - @Override - public PageOrdering getSortVersion() { - return sortVersion; - } - - @Override - public PageControl getPageControlOverrides() { - return pageControl; - } - - @Override - public void setPageControl(PageControl pageControl) { - this.pageControl = pageControl; - } -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftCriteria.java deleted file mode 100644 index b1a5695..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BasicDriftCriteria.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.rhq.core.domain.criteria; - -import java.util.ArrayList; -import java.util.List; - -import org.rhq.core.domain.drift.DriftCategory; -import org.rhq.core.domain.util.PageControl; -import org.rhq.core.domain.util.PageOrdering; - -import static org.rhq.core.domain.util.CriteriaUtils.getListIgnoringNulls; - -public class BasicDriftCriteria implements DriftCriteria { - - private static final long serialVersionUID = 1L; - - private String filterId; - - private List<DriftCategory> filterCategories = new ArrayList<DriftCategory>(); - - private String filterChangeSetId; - - private String filterPath; - - private List<Integer> filterResourceIds = new ArrayList<Integer>(); - - private boolean fetchChangeSet; - - private Long filterStartTime; - - private Long filterEndTime; - - private PageControl pageControl; - - private PageOrdering sortCtime; - - @Override - public void addFilterId(String filterId) { - this.filterId = filterId; - } - - @Override - public String getFilterId() { - return filterId; - } - - @Override - public void addFilterCategories(DriftCategory... filterCategories) { - this.filterCategories = getListIgnoringNulls(filterCategories); - } - - @Override - public List<DriftCategory> getFilterCategories() { - return filterCategories; - } - - @Override - public void addFilterChangeSetId(String filterChangeSetId) { - this.filterChangeSetId = filterChangeSetId; - } - - @Override - public String getFilterChangeSetId() { - return filterChangeSetId; - } - - @Override - public void addFilterPath(String filterPath) { - this.filterPath = filterPath; - } - - @Override - public String getFilterPath() { - return filterPath; - } - - @Override - public void addFilterResourceIds(Integer... filterResourceIds) { - this.filterResourceIds = getListIgnoringNulls(filterResourceIds); - } - - @Override - public List<Integer> getFilterResourceIds() { - return filterResourceIds; - } - - @Override - public void addFilterStartTime(Long filterStartTime) { - this.filterStartTime = filterStartTime; - } - - @Override - public Long getFilterStartTime() { - return filterStartTime; - } - - @Override - public void addFilterEndTime(Long filterEndTime) { - this.filterEndTime = filterEndTime; - } - - @Override - public Long getFilterEndTime() { - return filterEndTime; - } - - @Override - public void fetchChangeSet(boolean fetchChangeSet) { - this.fetchChangeSet = fetchChangeSet; - } - - @Override - public boolean isFetchChangeSet() { - return fetchChangeSet; - } - - @Override - public void addSortCtime(PageOrdering sortCtime) { - this.sortCtime = sortCtime; - } - - @Override - public PageOrdering getSortCtime() { - return sortCtime; - } - - @Override - public PageControl getPageControlOverrides() { - return pageControl; - } - - @Override - public void setPageControl(PageControl pageControl) { - this.pageControl = pageControl; - } -} 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 273db4b..a3c61a6 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 @@ -1,11 +1,34 @@ +/* + * 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.io.Serializable; - import org.rhq.core.domain.drift.DriftChangeSetCategory; import org.rhq.core.domain.util.PageOrdering;
-public interface DriftChangeSetCriteria extends BaseCriteria, Serializable { +/** + * To support pluggable drift server implementations this Interface provides the contract required for + * Criteria based searching on DriftChangeSet. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public interface DriftChangeSetCriteria extends BaseCriteria {
void addFilterId(String filterId);
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetJPACriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetJPACriteria.java deleted file mode 100644 index 0ca1d36..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftChangeSetJPACriteria.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation version 2 of the License. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - */ - -package org.rhq.core.domain.criteria; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import org.rhq.core.domain.drift.DriftChangeSetCategory; -import org.rhq.core.domain.drift.RhqDriftChangeSet; -import org.rhq.core.domain.util.PageOrdering; - -/** - * @author Jay Shaughnessy - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -@SuppressWarnings("unused") -public class DriftChangeSetJPACriteria extends Criteria implements DriftChangeSetCriteria { - private static final long serialVersionUID = 1L; - - private Integer filterId; - private Integer filterInitial; // needs override - private Integer filterResourceId; // needs override - private Integer filterDriftConfigurationId; - private Integer filterVersion; - private Integer filterStartVersion; - private Integer filterEndVersion; - private Long filterCreatedAfter; - private Long filterCreatedBefore; - private DriftChangeSetCategory filterCategory; - private boolean fetchDrifts; - - private PageOrdering sortVersion; - - public DriftChangeSetJPACriteria() { - filterOverrides.put("initial", "version = 0"); - filterOverrides.put("resourceId", "resource.id = ?"); - filterOverrides.put("startVersion", "version >= ?"); - filterOverrides.put("endVersion", "version <= ?"); - filterOverrides.put("createdAfter", "ctime >= ?"); - filterOverrides.put("createdBefore", "ctime <= ?"); - } - - @Override - public Class<RhqDriftChangeSet> getPersistentClass() { - return RhqDriftChangeSet.class; - } - - public void addFilterId(String filterId) { - if (filterId != null) { - this.filterId = Integer.parseInt(filterId); - } - } - - @Override - public String getFilterId() { - return filterId == null ? null : filterId.toString(); - } - - public void addFilterVersion(String filterVersion) { - if (filterVersion != null) { - this.filterVersion = Integer.parseInt(filterVersion); - } - } - - @Override - public String getFilterVersion() { - return filterVersion == null ? null : filterVersion.toString(); - } - - @Override - public void addFilterStartVersion(String filterStartVersion) { - if (filterStartVersion != null) { - this.filterStartVersion = Integer.parseInt(filterStartVersion); - } - } - - @Override - public String getFilterStartVersion() { - return filterStartVersion == null ? null : filterStartVersion.toString(); - } - - @Override - public void addFilterEndVersion(String filterEndVersion) { - if (filterEndVersion != null) { - this.filterEndVersion = Integer.parseInt(filterEndVersion); - } - } - - @Override - public String getFilterEndVersion() { - return filterEndVersion == null ? null : filterEndVersion.toString(); - } - - @Override - public void addFilterCreatedAfter(Long filterCreatedAfter) { - this.filterCreatedAfter = filterCreatedAfter; - } - - @Override - public Long getFilterCreatedAfter() { - return filterCreatedAfter; - } - - @Override - public void addFilterCreatedBefore(Long filterCreatedBefore) { - this.filterCreatedBefore = filterCreatedBefore; - } - - @Override - public Long getFilterCreatedBefore() { - return filterCreatedBefore; - } - - public void addFilterResourceId(Integer filterResourceId) { - this.filterResourceId = filterResourceId; - } - - @Override - public Integer getFilterResourceId() { - return filterResourceId; - } - - @Override - public void addFilterDriftConfigurationId(Integer filterDriftConfigId) { - this.filterDriftConfigurationId = filterDriftConfigId; - } - - @Override - public Integer getFilterDriftConfigurationId() { - return filterDriftConfigurationId; - } - - public void addFilterCategory(DriftChangeSetCategory filterCategory) { - this.filterCategory = filterCategory; - } - - @Override - public DriftChangeSetCategory getFilterCategory() { - return filterCategory; - } - - public void fetchDrifts(boolean fetchDrifts) { - this.fetchDrifts = fetchDrifts; - } - - @Override - public boolean isFetchDrifts() { - return fetchDrifts; - } - - public void addSortVersion(PageOrdering sortVersion) { - addSortField("version"); - this.sortVersion = sortVersion; - } - - @Override - public PageOrdering getSortVersion() { - return sortVersion; - } -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java index cdd061e..25c1e53 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftCriteria.java @@ -1,12 +1,34 @@ +/* + * 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.io.Serializable; -import java.util.List; - import org.rhq.core.domain.drift.DriftCategory; import org.rhq.core.domain.util.PageOrdering;
-public interface DriftCriteria extends BaseCriteria, Serializable { +/** + * To support pluggable drift server implementations this Interface provides the contract required for + * Criteria based searching on Drift. + * + * @author Jay Shaughnessy + * + */ +public interface DriftCriteria extends BaseCriteria {
void addFilterId(String filterId);
@@ -14,7 +36,7 @@ public interface DriftCriteria extends BaseCriteria, Serializable {
void addFilterCategories(DriftCategory... filterCategories);
- List<DriftCategory> getFilterCategories(); + DriftCategory[] getFilterCategories();
void addFilterChangeSetId(String filterChangeSetId);
@@ -26,7 +48,7 @@ public interface DriftCriteria extends BaseCriteria, Serializable {
void addFilterResourceIds(Integer... filterResourceIds);
- List<Integer> getFilterResourceIds(); + Integer[] getFilterResourceIds();
void addFilterStartTime(Long filterStartTime);
@@ -44,6 +66,4 @@ public interface DriftCriteria extends BaseCriteria, Serializable {
PageOrdering getSortCtime();
- - } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftJPACriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftJPACriteria.java deleted file mode 100644 index 506cb06..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/DriftJPACriteria.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2009 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.ArrayList; -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.DriftCategory; -import org.rhq.core.domain.drift.RhqDrift; -import org.rhq.core.domain.util.CriteriaUtils; -import org.rhq.core.domain.util.PageOrdering; - -/** - * @author Jay Shaughnessy - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -@SuppressWarnings("unused") -public class DriftJPACriteria extends Criteria implements DriftCriteria { - private static final long serialVersionUID = 1L; - - private Integer filterId; - private List<DriftCategory> filterCategories = new ArrayList<DriftCategory>(); - private Integer filterChangeSetId; // needs override - private String filterPath; - private List<Integer> filterResourceIds = new ArrayList<Integer>(); - private Long filterStartTime; // requires overrides - private Long filterEndTime; // requires overrides - - private boolean fetchChangeSet; - - private PageOrdering sortCtime; - - public DriftJPACriteria() { - filterOverrides.put("changeSetId", "changeSet.id = ?"); - filterOverrides.put("categories", "category IN ( ? )"); - filterOverrides.put("resourceIds", "changeSet.resource.id IN ( ? )"); - filterOverrides.put("startTime", "ctime >= ?"); - filterOverrides.put("endTime", "ctime <= ?"); - } - - @Override - public Class<RhqDrift> getPersistentClass() { - return RhqDrift.class; - } - - public void addFilterId(String filterId) { - if (filterId != null) { - this.filterId = Integer.parseInt(filterId); - } - } - - @Override - public String getFilterId() { - return filterId == null ? null : filterId.toString(); - } - - public void addFilterCategories(DriftCategory... filterCategories) { - this.filterCategories = CriteriaUtils.getListIgnoringNulls(filterCategories); - } - - @Override - public List<DriftCategory> getFilterCategories() { - return filterCategories; - } - - public void addFilterChangeSetId(String filterChangeSetId) { - if (filterChangeSetId != null) { - this.filterChangeSetId = Integer.parseInt(filterChangeSetId); - } - } - - @Override - public String getFilterChangeSetId() { - return filterChangeSetId == null ? null : filterChangeSetId.toString(); - } - - public void addFilterPath(String filterPath) { - this.filterPath = filterPath; - } - - @Override - public String getFilterPath() { - return filterPath; - } - - public void addFilterResourceIds(Integer... filterResourceIds) { - this.filterResourceIds = CriteriaUtils.getListIgnoringNulls(filterResourceIds); - } - - @Override - public List<Integer> getFilterResourceIds() { - return filterResourceIds; - } - - public void addFilterStartTime(Long filterStartTime) { - this.filterStartTime = filterStartTime; - } - - @Override - public Long getFilterStartTime() { - return filterStartTime; - } - - public void addFilterEndTime(Long filterEndTime) { - this.filterEndTime = filterEndTime; - } - - @Override - public Long getFilterEndTime() { - return filterEndTime; - } - - public void fetchChangeSet(boolean fetchChangeSet) { - this.fetchChangeSet = fetchChangeSet; - } - - @Override - public boolean isFetchChangeSet() { - return fetchChangeSet; - } - - public void addSortCtime(PageOrdering sortCtime) { - addSortField("ctime"); - this.sortCtime = sortCtime; - } - - @Override - public PageOrdering getSortCtime() { - return sortCtime; - } -} 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 new file mode 100644 index 0000000..073d89e --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftChangeSetCriteria.java @@ -0,0 +1,184 @@ +/* + * 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.io.Serializable; + +import org.rhq.core.domain.drift.DriftChangeSetCategory; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageOrdering; + +/** + * The generic implementation of DriftChangeSetCriteria makes no assumptions about the actual drift server + * plugin that will service the relevant requests. It is a simple impl of the interface and is + * suitable for use by any component that can not assume a backend implmentation, like a GUI + * client. Server side implementations will use this to populate the plugin-specific implementation + * of the interface. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public class GenericDriftChangeSetCriteria implements Serializable, DriftChangeSetCriteria { + + private static final long serialVersionUID = 1L; + + private String filterId; + + private String filterVersion; + + private String filterStartVersion; + + private String filterEndVersion; + + private Long filterCreatedAfter; + + private Long filterCreatedBefore; + + private Integer filterResourceId; + + private Integer filterDriftConfigId; + + private DriftChangeSetCategory filterCategory; + + private boolean fetchDrifts; + + private PageOrdering sortVersion; + + private PageControl pageControl; + + @Override + public void addFilterId(String filterId) { + this.filterId = filterId; + } + + @Override + public String getFilterId() { + return filterId; + } + + @Override + public void addFilterVersion(String filterVersion) { + this.filterVersion = filterVersion; + } + + @Override + public String getFilterVersion() { + return filterVersion; + } + + @Override + public void addFilterStartVersion(String filterStartVersion) { + this.filterStartVersion = filterStartVersion; + } + + @Override + public String getFilterStartVersion() { + return filterStartVersion; + } + + @Override + public void addFilterEndVersion(String filterEndVersion) { + this.filterEndVersion = filterEndVersion; + } + + @Override + public String getFilterEndVersion() { + return filterEndVersion; + } + + @Override + public void addFilterCreatedAfter(Long filterCreatedAfter) { + this.filterCreatedAfter = filterCreatedAfter; + } + + @Override + public Long getFilterCreatedAfter() { + return filterCreatedAfter; + } + + @Override + public void addFilterCreatedBefore(Long filterCreatedBefore) { + this.filterCreatedBefore = filterCreatedBefore; + } + + @Override + public Long getFilterCreatedBefore() { + return filterCreatedBefore; + } + + @Override + public void addFilterResourceId(Integer filterResourceId) { + this.filterResourceId = filterResourceId; + } + + @Override + public Integer getFilterResourceId() { + return filterResourceId; + } + + @Override + public void addFilterDriftConfigurationId(Integer filterDriftConfigId) { + this.filterDriftConfigId = filterDriftConfigId; + } + + @Override + public Integer getFilterDriftConfigurationId() { + return filterDriftConfigId; + } + + @Override + public void addFilterCategory(DriftChangeSetCategory filterCategory) { + this.filterCategory = filterCategory; + } + + @Override + public DriftChangeSetCategory getFilterCategory() { + return filterCategory; + } + + @Override + public void fetchDrifts(boolean fetchDrifts) { + this.fetchDrifts = fetchDrifts; + } + + @Override + public boolean isFetchDrifts() { + return fetchDrifts; + } + + @Override + public void addSortVersion(PageOrdering sortVersion) { + this.sortVersion = sortVersion; + } + + @Override + public PageOrdering getSortVersion() { + return sortVersion; + } + + @Override + public PageControl getPageControlOverrides() { + return pageControl; + } + + @Override + public void setPageControl(PageControl pageControl) { + this.pageControl = pageControl; + } +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java new file mode 100644 index 0000000..b8a84d8 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/GenericDriftCriteria.java @@ -0,0 +1,164 @@ +/* + * 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 static org.rhq.core.domain.util.CriteriaUtils.getListIgnoringNulls; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.rhq.core.domain.drift.DriftCategory; +import org.rhq.core.domain.util.PageControl; +import org.rhq.core.domain.util.PageOrdering; + +/** + * The generic implementation of DriftCriteria makes no assumptions about the actual drift server + * plugin that will service the relevant requests. It is a simple impl of the interface and is + * suitable for use by any component that can not assume a backend implmentation, like a GUI + * client. Server side implementations will use this to populate the plugin-specific implementation + * of the interface. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public class GenericDriftCriteria implements Serializable, DriftCriteria { + + private static final long serialVersionUID = 1L; + + private String filterId; + + private List<DriftCategory> filterCategories = new ArrayList<DriftCategory>(); + + private String filterChangeSetId; + + private String filterPath; + + private List<Integer> filterResourceIds = new ArrayList<Integer>(); + + private boolean fetchChangeSet; + + private Long filterStartTime; + + private Long filterEndTime; + + private PageControl pageControl; + + private PageOrdering sortCtime; + + @Override + public void addFilterId(String filterId) { + this.filterId = filterId; + } + + @Override + public String getFilterId() { + return filterId; + } + + @Override + public void addFilterCategories(DriftCategory... filterCategories) { + this.filterCategories = getListIgnoringNulls(filterCategories); + } + + @Override + public DriftCategory[] getFilterCategories() { + return filterCategories.toArray(new DriftCategory[filterCategories.size()]); + } + + @Override + public void addFilterChangeSetId(String filterChangeSetId) { + this.filterChangeSetId = filterChangeSetId; + } + + @Override + public String getFilterChangeSetId() { + return filterChangeSetId; + } + + @Override + public void addFilterPath(String filterPath) { + this.filterPath = filterPath; + } + + @Override + public String getFilterPath() { + return filterPath; + } + + @Override + public void addFilterResourceIds(Integer... filterResourceIds) { + this.filterResourceIds = getListIgnoringNulls(filterResourceIds); + } + + @Override + public Integer[] getFilterResourceIds() { + return filterResourceIds.toArray(new Integer[filterResourceIds.size()]); + } + + @Override + public void addFilterStartTime(Long filterStartTime) { + this.filterStartTime = filterStartTime; + } + + @Override + public Long getFilterStartTime() { + return filterStartTime; + } + + @Override + public void addFilterEndTime(Long filterEndTime) { + this.filterEndTime = filterEndTime; + } + + @Override + public Long getFilterEndTime() { + return filterEndTime; + } + + @Override + public void fetchChangeSet(boolean fetchChangeSet) { + this.fetchChangeSet = fetchChangeSet; + } + + @Override + public boolean isFetchChangeSet() { + return fetchChangeSet; + } + + @Override + public void addSortCtime(PageOrdering sortCtime) { + this.sortCtime = sortCtime; + } + + @Override + public PageOrdering getSortCtime() { + return sortCtime; + } + + @Override + public PageControl getPageControlOverrides() { + return pageControl; + } + + @Override + public void setPageControl(PageControl pageControl) { + this.pageControl = pageControl; + } +} 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 new file mode 100644 index 0000000..d73c744 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftChangeSetCriteria.java @@ -0,0 +1,200 @@ +/* + * RHQ Management Platform + * Copyright (C) 2005-2009 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +package org.rhq.core.domain.criteria; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import org.rhq.core.domain.drift.DriftChangeSetCategory; +import org.rhq.core.domain.drift.JPADriftChangeSet; +import org.rhq.core.domain.util.PageOrdering; + +/** + * The JPA Drift Server plugin (the RHQ default) implementation of DriftChangeSetCriteria. + * + * @author Jay Shaughnessy + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@SuppressWarnings("unused") +public class JPADriftChangeSetCriteria extends Criteria implements DriftChangeSetCriteria { + private static final long serialVersionUID = 1L; + + private Integer filterId; + private Integer filterInitial; // needs override + private Integer filterResourceId; // needs override + private Integer filterDriftConfigurationId; + private Integer filterVersion; + private Integer filterStartVersion; + private Integer filterEndVersion; + private Long filterCreatedAfter; + private Long filterCreatedBefore; + private DriftChangeSetCategory filterCategory; + private boolean fetchDrifts; + + private PageOrdering sortVersion; + + public JPADriftChangeSetCriteria() { + this(null); + } + + public JPADriftChangeSetCriteria(DriftChangeSetCriteria changeSetCriteria) { + filterOverrides.put("initial", "version = 0"); + filterOverrides.put("resourceId", "resource.id = ?"); + filterOverrides.put("startVersion", "version >= ?"); + filterOverrides.put("endVersion", "version <= ?"); + filterOverrides.put("createdAfter", "ctime >= ?"); + filterOverrides.put("createdBefore", "ctime <= ?"); + + if (null != changeSetCriteria) { + this.addFilterId(changeSetCriteria.getFilterId()); + this.addFilterResourceId(changeSetCriteria.getFilterResourceId()); + this.addFilterCategory(changeSetCriteria.getFilterCategory()); + this.addFilterCreatedAfter(changeSetCriteria.getFilterCreatedAfter()); + this.addFilterCreatedBefore(changeSetCriteria.getFilterCreatedBefore()); + this.addFilterEndVersion(changeSetCriteria.getFilterEndVersion()); + this.addFilterStartVersion(changeSetCriteria.getFilterStartVersion()); + this.addFilterVersion(changeSetCriteria.getFilterVersion()); + + this.addSortVersion(changeSetCriteria.getSortVersion()); + + this.fetchDrifts(changeSetCriteria.isFetchDrifts()); + } + } + + @Override + public Class<JPADriftChangeSet> getPersistentClass() { + return JPADriftChangeSet.class; + } + + public void addFilterId(String filterId) { + if (filterId != null) { + this.filterId = Integer.parseInt(filterId); + } + } + + @Override + public String getFilterId() { + return filterId == null ? null : filterId.toString(); + } + + public void addFilterVersion(String filterVersion) { + if (filterVersion != null) { + this.filterVersion = Integer.parseInt(filterVersion); + } + } + + @Override + public String getFilterVersion() { + return filterVersion == null ? null : filterVersion.toString(); + } + + @Override + public void addFilterStartVersion(String filterStartVersion) { + if (filterStartVersion != null) { + this.filterStartVersion = Integer.parseInt(filterStartVersion); + } + } + + @Override + public String getFilterStartVersion() { + return filterStartVersion == null ? null : filterStartVersion.toString(); + } + + @Override + public void addFilterEndVersion(String filterEndVersion) { + if (filterEndVersion != null) { + this.filterEndVersion = Integer.parseInt(filterEndVersion); + } + } + + @Override + public String getFilterEndVersion() { + return filterEndVersion == null ? null : filterEndVersion.toString(); + } + + @Override + public void addFilterCreatedAfter(Long filterCreatedAfter) { + this.filterCreatedAfter = filterCreatedAfter; + } + + @Override + public Long getFilterCreatedAfter() { + return filterCreatedAfter; + } + + @Override + public void addFilterCreatedBefore(Long filterCreatedBefore) { + this.filterCreatedBefore = filterCreatedBefore; + } + + @Override + public Long getFilterCreatedBefore() { + return filterCreatedBefore; + } + + public void addFilterResourceId(Integer filterResourceId) { + this.filterResourceId = filterResourceId; + } + + @Override + public Integer getFilterResourceId() { + return filterResourceId; + } + + @Override + public void addFilterDriftConfigurationId(Integer filterDriftConfigId) { + this.filterDriftConfigurationId = filterDriftConfigId; + } + + @Override + public Integer getFilterDriftConfigurationId() { + return filterDriftConfigurationId; + } + + public void addFilterCategory(DriftChangeSetCategory filterCategory) { + this.filterCategory = filterCategory; + } + + @Override + public DriftChangeSetCategory getFilterCategory() { + return filterCategory; + } + + public void fetchDrifts(boolean fetchDrifts) { + this.fetchDrifts = fetchDrifts; + } + + @Override + public boolean isFetchDrifts() { + return fetchDrifts; + } + + public void addSortVersion(PageOrdering sortVersion) { + addSortField("version"); + this.sortVersion = sortVersion; + } + + @Override + public PageOrdering getSortVersion() { + return sortVersion; + } +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java new file mode 100644 index 0000000..2962b57 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/JPADriftCriteria.java @@ -0,0 +1,172 @@ +/* + * 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.ArrayList; +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.DriftCategory; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.util.CriteriaUtils; +import org.rhq.core.domain.util.PageOrdering; + +/** + * The JPA Drift Server plugin (the RHQ default) implementation of DriftCriteria. + * + * @author Jay Shaughnessy + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +public class JPADriftCriteria extends Criteria implements DriftCriteria { + private static final long serialVersionUID = 1L; + + private Integer filterId; + private List<DriftCategory> filterCategories = new ArrayList<DriftCategory>(); + private Integer filterChangeSetId; // needs override + private String filterPath; + private List<Integer> filterResourceIds = new ArrayList<Integer>(); + private Long filterStartTime; // requires overrides + private Long filterEndTime; // requires overrides + + private boolean fetchChangeSet; + + private PageOrdering sortCtime; + + public JPADriftCriteria() { + this(null); + } + + public JPADriftCriteria(DriftCriteria driftCriteria) { + filterOverrides.put("changeSetId", "changeSet.id = ?"); + filterOverrides.put("categories", "category IN ( ? )"); + filterOverrides.put("resourceIds", "changeSet.resource.id IN ( ? )"); + filterOverrides.put("startTime", "ctime >= ?"); + filterOverrides.put("endTime", "ctime <= ?"); + + // seed the JPA criteria with anything set in the provided criteria + if (null != driftCriteria) { + this.fetchChangeSet(driftCriteria.isFetchChangeSet()); + + this.addFilterCategories(driftCriteria.getFilterCategories()); + this.addFilterChangeSetId(driftCriteria.getFilterChangeSetId()); + this.addFilterEndTime(driftCriteria.getFilterEndTime()); + this.addFilterId(driftCriteria.getFilterId()); + this.addFilterPath(driftCriteria.getFilterPath()); + this.addFilterResourceIds(driftCriteria.getFilterResourceIds()); + this.addFilterStartTime(driftCriteria.getFilterStartTime()); + + this.addSortCtime(driftCriteria.getSortCtime()); + } + } + + @Override + public Class<JPADrift> getPersistentClass() { + return JPADrift.class; + } + + public void addFilterId(String filterId) { + if (filterId != null) { + this.filterId = Integer.parseInt(filterId); + } + } + + @Override + public String getFilterId() { + return filterId == null ? null : filterId.toString(); + } + + public void addFilterCategories(DriftCategory... filterCategories) { + this.filterCategories = CriteriaUtils.getListIgnoringNulls(filterCategories); + } + + @Override + public DriftCategory[] getFilterCategories() { + return filterCategories.toArray(new DriftCategory[filterCategories.size()]); + } + + public void addFilterChangeSetId(String filterChangeSetId) { + if (filterChangeSetId != null) { + this.filterChangeSetId = Integer.parseInt(filterChangeSetId); + } + } + + @Override + public String getFilterChangeSetId() { + return filterChangeSetId == null ? null : filterChangeSetId.toString(); + } + + public void addFilterPath(String filterPath) { + this.filterPath = filterPath; + } + + @Override + public String getFilterPath() { + return filterPath; + } + + public void addFilterResourceIds(Integer... filterResourceIds) { + this.filterResourceIds = CriteriaUtils.getListIgnoringNulls(filterResourceIds); + } + + @Override + public Integer[] getFilterResourceIds() { + return filterResourceIds.toArray(new Integer[filterResourceIds.size()]); + } + + public void addFilterStartTime(Long filterStartTime) { + this.filterStartTime = filterStartTime; + } + + @Override + public Long getFilterStartTime() { + return filterStartTime; + } + + public void addFilterEndTime(Long filterEndTime) { + this.filterEndTime = filterEndTime; + } + + @Override + public Long getFilterEndTime() { + return filterEndTime; + } + + public void fetchChangeSet(boolean fetchChangeSet) { + this.fetchChangeSet = fetchChangeSet; + } + + @Override + public boolean isFetchChangeSet() { + return fetchChangeSet; + } + + public void addSortCtime(PageOrdering sortCtime) { + addSortField("ctime"); + this.sortCtime = sortCtime; + } + + @Override + public PageOrdering getSortCtime() { + return sortCtime; + } +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractDriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractDriftFile.java deleted file mode 100644 index 8f92087..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractDriftFile.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.rhq.core.domain.drift; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.MappedSuperclass; -import javax.persistence.PrePersist; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; - -/** - * A RhqDriftFile represents one unique piece of content used for drift tracking. Because the bits are supported - * by java.sql.Blob and java.io streaming, we must hide the bits from entities used on the gwt client. This base - * class is used as the superclass for both RhqDriftFile (no blob) and DriftFileBits (blob). - * - * @author Jay Shaughnessy - * @author John Mazzitelli - * @author John Sanda - */ -@MappedSuperclass -@XmlAccessorType(XmlAccessType.FIELD) -public class AbstractDriftFile implements Serializable { - private static final long serialVersionUID = 1L; - - @Column(name = "CTIME", nullable = false) - protected Long ctime = -1L; - - @Column(name = "DATA_SIZE", nullable = true) - protected Long dataSize; - - @Column(name = "STATUS", nullable = false) - @Enumerated(EnumType.STRING) - protected DriftFileStatus status = DriftFileStatus.EMPTY; - - protected AbstractDriftFile() { - } - - public Long getCtime() { - return ctime; - } - - @PrePersist - void onPersist() { - this.ctime = System.currentTimeMillis(); - } - - public void setDataSize(Long dataSize) { - this.dataSize = dataSize; - } - - public Long getDataSize() { - return dataSize; - } - - public DriftFileStatus getStatus() { - return status; - } - - public void setStatus(DriftFileStatus status) { - this.status = status; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractJPADriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractJPADriftFile.java new file mode 100644 index 0000000..5988562 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/AbstractJPADriftFile.java @@ -0,0 +1,87 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.core.domain.drift; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.MappedSuperclass; +import javax.persistence.PrePersist; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +/** + * A JPADriftFile represents one unique piece of content used for drift tracking. Because the bits are supported + * by java.sql.Blob and java.io streaming, we must hide the bits from entities used on the gwt client. This base + * class is used as the superclass for both JPADriftFile (no blob) and JPADriftFileBits (blob). + * + * @author Jay Shaughnessy + * @author John Mazzitelli + * @author John Sanda + */ +@MappedSuperclass +@XmlAccessorType(XmlAccessType.FIELD) +public class AbstractJPADriftFile implements Serializable { + private static final long serialVersionUID = 1L; + + @Column(name = "CTIME", nullable = false) + protected Long ctime = -1L; + + @Column(name = "DATA_SIZE", nullable = true) + protected Long dataSize; + + @Column(name = "STATUS", nullable = false) + @Enumerated(EnumType.STRING) + protected DriftFileStatus status = DriftFileStatus.EMPTY; + + protected AbstractJPADriftFile() { + } + + public Long getCtime() { + return ctime; + } + + @PrePersist + void onPersist() { + this.ctime = System.currentTimeMillis(); + } + + public void setDataSize(Long dataSize) { + this.dataSize = dataSize; + } + + public Long getDataSize() { + return dataSize; + } + + public DriftFileStatus getStatus() { + return status; + } + + public void setStatus(DriftFileStatus status) { + this.status = status; + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DiffReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DiffReport.java deleted file mode 100644 index e0659d9..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DiffReport.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.rhq.core.domain.drift; - -import java.util.ArrayList; -import java.util.List; - -public class DiffReport<T> { - - private List<T> notInLeft = new ArrayList<T>(); - - private List<T> notInRight = new ArrayList<T>(); - - private List<T> conflicts = new ArrayList<T>(); - - public List<T> getElementsNotInLeft() { - return notInLeft; - } - - public void elementNotInLeft(T element) { - notInLeft.add(element); - } - - public List<T> getElementsNotInRight() { - return notInRight; - } - - public void elementNotInRight(T element) { - notInRight.add(element); - } - - public List<T> getElementsInConflict() { - return conflicts; - } - - public void elementInConflict(T element) { - conflicts.add(element); - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Drift.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Drift.java index aa20d15..3356e7a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Drift.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Drift.java @@ -1,6 +1,34 @@ +/* + * 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;
-public interface Drift<C extends DriftChangeSet, F extends DriftFile> { +/** + * To support pluggable drift server implementations this Interface provides the contract required for + * defining and persisting each Drift entry in a DriftChangeSet. + * + * @param <C> A server plugin's DriftChangeSet implementation + * @param <F> A server plugin's DriftFile implementation + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public interface Drift<C extends DriftChangeSet<?>, F extends DriftFile> { String getId();
void setId(String id); 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 70cc9a4..b0cd61d 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 @@ -1,8 +1,35 @@ +/* + * 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.Set;
-public interface DriftChangeSet<D extends Drift> { +/** + * To support pluggable drift server implementations this Interface provides the contract required for + * defining and persisting each DriftChangeSet reported from an Agent. + * + * @param <D> A server plugin's Drift implementation + * + * @author Jay Shaughnessy + * @author John Sanda + */ +public interface DriftChangeSet<D extends Drift<?, ?>> { String getId();
void setId(String id); diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDiffReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDiffReport.java new file mode 100644 index 0000000..b9551cf --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftDiffReport.java @@ -0,0 +1,38 @@ +package org.rhq.core.domain.drift; + +import java.util.ArrayList; +import java.util.List; + +public class DriftDiffReport<T> { + + private List<T> notInLeft = new ArrayList<T>(); + + private List<T> notInRight = new ArrayList<T>(); + + private List<T> conflicts = new ArrayList<T>(); + + public List<T> getElementsNotInLeft() { + return notInLeft; + } + + public void elementNotInLeft(T element) { + notInLeft.add(element); + } + + public List<T> getElementsNotInRight() { + return notInRight; + } + + public void elementNotInRight(T element) { + notInRight.add(element); + } + + public List<T> getElementsInConflict() { + return conflicts; + } + + public void elementInConflict(T element) { + conflicts.add(element); + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFile.java index 572e3da..94b1d3b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFile.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFile.java @@ -1,8 +1,30 @@ +/* + * 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.io.Serializable;
-public interface DriftFile extends Serializable { +/* + * To support pluggable drift server implementations this Interface provides the contract required for + * defining and persisting each DriftFile. A DriftFile represents one unique piece of content used for + * drift tracking. + */ +public interface DriftFile {
String getHashId();
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFileBits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFileBits.java deleted file mode 100644 index f85ef9c..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftFileBits.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.rhq.core.domain.drift; - -import java.io.InputStream; -import java.io.Serializable; -import java.sql.Blob; -import java.sql.SQLException; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; - -/** - * A RhqDriftFile represents one unique piece of content used for drift tracking. Note that DriftFileBits provides - * access to the bits through java.sql.Blob. This entity can not be used client-side (gwt) whereas its sister class, - * RhqDriftFile, can. Both enities share the same table and abstract superclass. See RHQDomain.gwt.xml for how to - * exclude unwanted domain classes from the gwt compile. - * - * @author Jay Shaughnessy - * @author John Mazzitelli - * @author John Sanda - */ -@Entity -@Table(name = "RHQ_DRIFT_FILE") -public class DriftFileBits extends AbstractDriftFile implements Serializable { - private static final long serialVersionUID = 1L; - - // this is a hash/digest that should uniquely identify the content - @Id - @Column(name = "HASH_ID", nullable = false) - private String hashId; - - protected DriftFileBits() { - super(); - } - - public DriftFileBits(String hashId) { - super(); - this.hashId = hashId; - } - - public String getHashId() { - return hashId; - } - - public void setHashId(String hashId) { - this.hashId = hashId; - } - - @Lob - @Column(name = "DATA", nullable = true) - private Blob data; - - public Blob getBlob() { - return data; - } - - public InputStream getData() throws SQLException { - return data.getBinaryStream(); - } - - public void setData(Blob blob) { - this.data = blob; - } - - @Override - public String toString() { - return "DriftFileContent [hashId=" + hashId + ", status=" + status + "]"; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftSnapshot.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftSnapshot.java new file mode 100644 index 0000000..58a11c7 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/DriftSnapshot.java @@ -0,0 +1,91 @@ +/* + * 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 org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED; + +import java.io.Serializable; +import java.util.Collection; +import java.util.Map; +import java.util.TreeMap; + +/** + * A representation of an agent's drift file monitoring. + * + * @author John Sanda + */ +public class DriftSnapshot implements Serializable { + + private static final long serialVersionUID = 1L; + + private int version; + + private Map<String, Drift<?, ?>> entries = new TreeMap<String, Drift<?, ?>>(); + + public int getVersion() { + return version; + } + + public Collection<Drift<?, ?>> getEntries() { + return entries.values(); + } + + public <D extends Drift<?, ?>> DriftSnapshot add(DriftChangeSet<D> changeSet) { + for (Drift<?, ?> entry : changeSet.getDrifts()) { + entries.remove(entry.getPath()); + if (entry.getCategory() != FILE_REMOVED) { + entries.put(entry.getPath(), entry); + } + } + version = changeSet.getVersion(); + return this; + } + + public DriftDiffReport<?> diff(DriftSnapshot right) { + DriftSnapshot left = this; + DriftDiffReport<Drift<?, ?>> diff = new DriftDiffReport<Drift<?, ?>>(); + + for (Map.Entry<String, Drift<?, ?>> entry : left.entries.entrySet()) { + if (!right.entries.containsKey(entry.getKey())) { + diff.elementNotInRight(entry.getValue()); + } + } + + for (Map.Entry<String, Drift<?, ?>> entry : right.entries.entrySet()) { + if (!left.entries.containsKey(entry.getKey())) { + diff.elementNotInLeft(entry.getValue()); + } + } + + for (Map.Entry<String, Drift<?, ?>> entry : left.entries.entrySet()) { + Drift<?, ?> rightDrift = right.entries.get(entry.getKey()); + if (rightDrift != null) { + DriftFile leftFile = entry.getValue().getNewDriftFile(); + DriftFile rightFile = rightDrift.getNewDriftFile(); + + if (!leftFile.getHashId().equals(rightFile.getHashId())) { + diff.elementInConflict(entry.getValue()); + } + } + } + + return diff; + } + +} 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 new file mode 100644 index 0000000..02d41da --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADrift.java @@ -0,0 +1,181 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.core.domain.drift; + +import java.io.Serializable; + +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.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +/** + * The JPA Drift Server plugin (the RHQ default) implementation of Drift. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +@Entity +@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 ) ) )") }) +@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"; + + @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 = "CATEGORY", nullable = false) + @Enumerated(EnumType.STRING) + private DriftCategory category; + + @Column(name = "PATH", nullable = false) + @Enumerated(EnumType.STRING) + private String path; + + @JoinColumn(name = "DRIFT_CHANGE_SET_ID", referencedColumnName = "ID", nullable = false) + @ManyToOne(fetch = FetchType.LAZY, optional = false) + private JPADriftChangeSet changeSet; + + @JoinColumn(name = "OLD_DRIFT_FILE", referencedColumnName = "HASH_ID", nullable = true) + @ManyToOne(fetch = FetchType.EAGER, optional = true) + private JPADriftFile oldDriftFile; + + @JoinColumn(name = "NEW_DRIFT_FILE", referencedColumnName = "HASH_ID", nullable = true) + @ManyToOne(fetch = FetchType.EAGER, optional = true) + private JPADriftFile newDriftFile; + + protected JPADrift() { + } + + /** + * @param resource + * @param category + * @param oldDriftFile required for FILE_CHANGED and FILE_REMOVED, null for FILE_ADDED + * @param newDriftFile required for FILE_CHANGED and FILE_ADDED, null for FILE_REMOVED + */ + public JPADrift(JPADriftChangeSet changeSet, String path, DriftCategory category, JPADriftFile oldDriftFile, + JPADriftFile newDriftFile) { + this.changeSet = changeSet; + this.path = path; + this.category = category; + this.oldDriftFile = oldDriftFile; + this.newDriftFile = newDriftFile; + } + + @Override + public String getId() { + return Integer.toString(id); + } + + @Override + public void setId(String id) { + this.id = Integer.parseInt(id); + } + + @Override + public Long getCtime() { + return ctime; + } + + @PrePersist + void onPersist() { + this.ctime = System.currentTimeMillis(); + } + + @Override + public JPADriftChangeSet getChangeSet() { + return changeSet; + } + + @Override + public void setChangeSet(JPADriftChangeSet changeSet) { + this.changeSet = changeSet; + } + + @Override + public DriftCategory getCategory() { + return category; + } + + @Override + public void setCategory(DriftCategory category) { + this.category = category; + } + + @Override + public String getPath() { + return path; + } + + @Override + public void setPath(String path) { + this.path = path; + } + + @Override + public JPADriftFile getOldDriftFile() { + return oldDriftFile; + } + + @Override + public void setOldDriftFile(JPADriftFile oldDriftFile) { + this.oldDriftFile = oldDriftFile; + } + + @Override + public JPADriftFile getNewDriftFile() { + return newDriftFile; + } + + @Override + public void setNewDriftFile(JPADriftFile newDriftFile) { + this.newDriftFile = newDriftFile; + } + + @Override + public String toString() { + return "JPADrift [ id=" + id + ", category=" + category + ", path=" + path + ", changeSet=" + changeSet + "]"; + } + +} 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 new file mode 100644 index 0000000..975d7d1 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftChangeSet.java @@ -0,0 +1,179 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.core.domain.drift; + +import java.io.Serializable; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import org.rhq.core.domain.resource.Resource; + +/** + * The JPA Drift Server plugin (the RHQ default) implementation of DriftChangeSet. + * + * @author Jay Shaughnessy + * @author John Sanda + */ +@Entity +@NamedQueries( { @NamedQuery(name = JPADriftChangeSet.QUERY_DELETE_BY_RESOURCES, query = "" // + + "DELETE FROM JPADriftChangeSet dcs " // + + " WHERE dcs.resource.id IN ( :resourceIds )") }) +@Table(name = "RHQ_DRIFT_CHANGE_SET") +@SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DRIFT_CHANGE_SET_ID_SEQ") +public class JPADriftChangeSet implements Serializable, DriftChangeSet<JPADrift> { + private static final long serialVersionUID = 1L; + + public static final String QUERY_DELETE_BY_RESOURCES = "JPADriftChangeSet.deleteByResources"; + + @Column(name = "ID", nullable = false) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") + @Id + private int id; + + @Column(name = "CTIME", nullable = false) + private Long ctime = -1L; + + // 0..N + @Column(name = "VERSION", nullable = false) + private int version; + + @Column(name = "CATEGORY", nullable = false) + @Enumerated(EnumType.STRING) + private DriftChangeSetCategory category; + + @Column(name = "CONFIG_ID", nullable = false) + private int driftConfigurationId; + + @JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID", nullable = false) + @ManyToOne(optional = false) + private Resource resource; + + @OneToMany(mappedBy = "changeSet", cascade = { CascadeType.ALL }) + private Set<JPADrift> drifts = new LinkedHashSet<JPADrift>(); + + protected JPADriftChangeSet() { + } + + public JPADriftChangeSet(Resource resource, int version, DriftChangeSetCategory category, int configId) { + this.resource = resource; + this.version = version; + this.category = category; + driftConfigurationId = configId; + } + + @Override + public String getId() { + return Integer.toString(id); + } + + @Override + public void setId(String id) { + this.id = Integer.parseInt(id); + } + + @Override + public Long getCtime() { + return ctime; + } + + @PrePersist + void onPersist() { + this.ctime = System.currentTimeMillis(); + } + + @Override + public int getVersion() { + return version; + } + + @Override + public void setVersion(int version) { + this.version = version; + } + + @Override + public DriftChangeSetCategory getCategory() { + return category; + } + + @Override + public void setCategory(DriftChangeSetCategory category) { + this.category = category; + } + + @Override + public int getResourceId() { + return resource.getId(); + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + @Override + public int getDriftConfigurationId() { + return driftConfigurationId; + } + + @Override + public void setDriftConfigurationId(int id) { + driftConfigurationId = id; + } + + @Override + public Set<JPADrift> getDrifts() { + return drifts; + } + + @Override + public void setDrifts(Set<JPADrift> drifts) { + this.drifts = drifts; + } + + @Override + public String toString() { + return "JPADriftChangeSet [id=" + id + ", resource=" + resource + ", version=" + version + "]"; + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java new file mode 100644 index 0000000..3a9c6b9 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFile.java @@ -0,0 +1,75 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.core.domain.drift; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +/** + * The JPA Drift Server plugin (the RHQ default) implementation of DriftFile. Note that JPADriftFile does not + * include the actual bits, and therefore can be used freely client-side (gwt). The bits are stored via the + * JPADriftFileBits class, which is like this one but adds the Blob field. + * + * @author Jay Shaughnessy + * @author John Mazzitelli + * @author John Sanda + */ +@Entity +@Table(name = "RHQ_DRIFT_FILE") +public class JPADriftFile extends AbstractJPADriftFile implements Serializable, DriftFile { + private static final long serialVersionUID = 1L; + + // this is a hash/digest that should uniquely identify the content + @Id + @Column(name = "HASH_ID", nullable = false) + private String hashId; + + protected JPADriftFile() { + super(); + } + + public JPADriftFile(String hashId) { + super(); + this.hashId = hashId; + } + + @Override + public String getHashId() { + return hashId; + } + + @Override + public void setHashId(String hashId) { + this.hashId = hashId; + } + + @Override + public String toString() { + return "JPADriftFile [hashId=" + hashId + ", status=" + status + "]"; + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java new file mode 100644 index 0000000..d326790 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/JPADriftFileBits.java @@ -0,0 +1,94 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.rhq.core.domain.drift; + +import java.io.InputStream; +import java.io.Serializable; +import java.sql.Blob; +import java.sql.SQLException; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; + +/** + * A JPADriftFile represents one unique piece of content used for drift tracking. Note that JPADriftFileBits + * provides access to the bits through java.sql.Blob. This entity can not be used client-side (gwt) whereas its + * sister class, JPADriftFile, can. Both entities share the same table and abstract superclass. See + * RHQDomain.gwt.xml for how to exclude unwanted domain classes from the gwt compile. + * + * @author Jay Shaughnessy + * @author John Mazzitelli + * @author John Sanda + */ +@Entity +@Table(name = "RHQ_DRIFT_FILE") +public class JPADriftFileBits extends AbstractJPADriftFile implements Serializable { + private static final long serialVersionUID = 1L; + + // this is a hash/digest that should uniquely identify the content + @Id + @Column(name = "HASH_ID", nullable = false) + private String hashId; + + protected JPADriftFileBits() { + super(); + } + + public JPADriftFileBits(String hashId) { + super(); + this.hashId = hashId; + } + + public String getHashId() { + return hashId; + } + + public void setHashId(String hashId) { + this.hashId = hashId; + } + + @Lob + @Column(name = "DATA", nullable = true) + private Blob data; + + public Blob getBlob() { + return data; + } + + public InputStream getData() throws SQLException { + return data.getBinaryStream(); + } + + public void setData(Blob blob) { + this.data = blob; + } + + @Override + public String toString() { + return "DriftFileContent [hashId=" + hashId + ", status=" + status + "]"; + } + +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDrift.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDrift.java deleted file mode 100644 index ef48961c..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDrift.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.rhq.core.domain.drift; - -import java.io.Serializable; - -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.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - -/** - * An occurrence of drifty to be reported and managed by the user. - - * @author Jay Shaughnessy - * @author John Sanda - */ -@Entity -@NamedQueries( { @NamedQuery(name = RhqDrift.QUERY_DELETE_BY_RESOURCES, query = "" // - + "DELETE FROM RhqDrift d " // - + " WHERE d.changeSet IN ( SELECT dcs FROM RhqDriftChangeSet dcs WHERE dcs.resource.id IN ( :resourceIds ) ) )") }) -@Table(name = "RHQ_DRIFT") -@SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DRIFT_ID_SEQ") -public class RhqDrift implements Serializable, Drift<RhqDriftChangeSet, RhqDriftFile> { - private static final long serialVersionUID = 1L; - - public static final String QUERY_DELETE_BY_RESOURCES = "RhqDrift.deleteByResources"; - - @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 = "CATEGORY", nullable = false) - @Enumerated(EnumType.STRING) - private DriftCategory category; - - @Column(name = "PATH", nullable = false) - @Enumerated(EnumType.STRING) - private String path; - - @JoinColumn(name = "DRIFT_CHANGE_SET_ID", referencedColumnName = "ID", nullable = false) - @ManyToOne(fetch = FetchType.LAZY, optional = false) - private RhqDriftChangeSet changeSet; - - @JoinColumn(name = "OLD_DRIFT_FILE", referencedColumnName = "HASH_ID", nullable = true) - @ManyToOne(fetch = FetchType.EAGER, optional = true) - private RhqDriftFile oldDriftFile; - - @JoinColumn(name = "NEW_DRIFT_FILE", referencedColumnName = "HASH_ID", nullable = true) - @ManyToOne(fetch = FetchType.EAGER, optional = true) - private RhqDriftFile newDriftFile; - - protected RhqDrift() { - } - - /** - * @param resource - * @param category - * @param oldDriftFile required for FILE_CHANGED and FILE_REMOVED, null for FILE_ADDED - * @param newDriftFile required for FILE_CHANGED and FILE_ADDED, null for FILE_REMOVED - */ - public RhqDrift(RhqDriftChangeSet changeSet, String path, DriftCategory category, RhqDriftFile oldDriftFile, - RhqDriftFile newDriftFile) { - this.changeSet = changeSet; - this.path = path; - this.category = category; - this.oldDriftFile = oldDriftFile; - this.newDriftFile = newDriftFile; - } - - @Override - public String getId() { - return Integer.toString(id); - } - - @Override - public void setId(String id) { - this.id = Integer.parseInt(id); - } - - @Override - public Long getCtime() { - return ctime; - } - - @PrePersist - void onPersist() { - this.ctime = System.currentTimeMillis(); - } - - @Override - public RhqDriftChangeSet getChangeSet() { - return changeSet; - } - - @Override - public void setChangeSet(RhqDriftChangeSet changeSet) { - this.changeSet = changeSet; - } - - @Override - public DriftCategory getCategory() { - return category; - } - - @Override - public void setCategory(DriftCategory category) { - this.category = category; - } - - @Override - public String getPath() { - return path; - } - - @Override - public void setPath(String path) { - this.path = path; - } - - @Override - public RhqDriftFile getOldDriftFile() { - return oldDriftFile; - } - - @Override - public void setOldDriftFile(RhqDriftFile oldDriftFile) { - this.oldDriftFile = oldDriftFile; - } - - @Override - public RhqDriftFile getNewDriftFile() { - return newDriftFile; - } - - @Override - public void setNewDriftFile(RhqDriftFile newDriftFile) { - this.newDriftFile = newDriftFile; - } - - @Override - public String toString() { - return "RhqDrift [ id=" + id + ", category=" + category + ", path=" + path + ", changeSet=" + changeSet + "]"; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftChangeSet.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftChangeSet.java deleted file mode 100644 index 7313282..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftChangeSet.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.rhq.core.domain.drift; - -import java.io.Serializable; -import java.util.LinkedHashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; - -import org.hibernate.annotations.Type; - -import org.rhq.core.domain.resource.Resource; - -/** - * @author Jay Shaughnessy - * @author John Sanda - */ -@Entity -@NamedQueries( { @NamedQuery(name = RhqDriftChangeSet.QUERY_DELETE_BY_RESOURCES, query = "" // - + "DELETE FROM RhqDriftChangeSet dcs " // - + " WHERE dcs.resource.id IN ( :resourceIds )") }) -@Table(name = "RHQ_DRIFT_CHANGE_SET") -@SequenceGenerator(name = "SEQ", sequenceName = "RHQ_DRIFT_CHANGE_SET_ID_SEQ") -public class RhqDriftChangeSet implements Serializable, DriftChangeSet<RhqDrift> { - private static final long serialVersionUID = 1L; - - public static final String QUERY_DELETE_BY_RESOURCES = "RhqDriftChangeSet.deleteByResources"; - - @Column(name = "ID", nullable = false) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ") - @Id - private int id; - - @Column(name = "CTIME", nullable = false) - private Long ctime = -1L; - - // 0..N - @Column(name = "VERSION", nullable = false) - private int version; - - @Column(name = "CATEGORY", nullable = false) - @Enumerated(EnumType.STRING) - private DriftChangeSetCategory category; - - @Column(name = "CONFIG_ID", nullable = false) - private int driftConfigurationId; - - @JoinColumn(name = "RESOURCE_ID", referencedColumnName = "ID", nullable = false) - @ManyToOne(optional = false) - private Resource resource; - - @OneToMany(mappedBy = "changeSet", cascade = { CascadeType.ALL }) - private Set<RhqDrift> drifts = new LinkedHashSet<RhqDrift>(); - - protected RhqDriftChangeSet() { - } - - public RhqDriftChangeSet(Resource resource, int version, DriftChangeSetCategory category, int configId) { - this.resource = resource; - this.version = version; - this.category = category; - driftConfigurationId = configId; - } - - @Override - public String getId() { - return Integer.toString(id); - } - - @Override - public void setId(String id) { - this.id = Integer.parseInt(id); - } - - @Override - public Long getCtime() { - return ctime; - } - - @PrePersist - void onPersist() { - this.ctime = System.currentTimeMillis(); - } - - @Override - public int getVersion() { - return version; - } - - @Override - public void setVersion(int version) { - this.version = version; - } - - @Override - public DriftChangeSetCategory getCategory() { - return category; - } - - @Override - public void setCategory(DriftChangeSetCategory category) { - this.category = category; - } - - @Override - public int getResourceId() { - return resource.getId(); - } - - public Resource getResource() { - return resource; - } - - public void setResource(Resource resource) { - this.resource = resource; - } - - @Override - public int getDriftConfigurationId() { - return driftConfigurationId; - } - - @Override - public void setDriftConfigurationId(int id) { - driftConfigurationId = id; - } - - @Override - public Set<RhqDrift> getDrifts() { - return drifts; - } - - @Override - public void setDrifts(Set<RhqDrift> drifts) { - this.drifts = drifts; - } - - @Override - public String toString() { - return "RhqDriftChangeSet [id=" + id + ", resource=" + resource + ", version=" + version + "]"; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftFile.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftFile.java deleted file mode 100644 index c9c0b59..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/RhqDriftFile.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 2005-2011 Red Hat, Inc. - * All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License, version 2, as - * published by the Free Software Foundation, and/or the GNU Lesser - * General Public License, version 2.1, also as published by the Free - * Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License and the GNU Lesser General Public License - * for more details. - * - * You should have received a copy of the GNU General Public License - * and the GNU Lesser General Public License along with this program; - * if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.rhq.core.domain.drift; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -/** - * A RhqDriftFile represents one unique piece of content used for drift tracking. Note that RhqDriftFile does not - * include the actual bits, and therefore can be used freely client-side (gwt). The bits are stored via the - * DriftFileBits class, which is like this one but adds the Blob field. - * - * @author Jay Shaughnessy - * @author John Mazzitelli - * @author John Sanda - */ -@Entity -@Table(name = "RHQ_DRIFT_FILE") -public class RhqDriftFile extends AbstractDriftFile implements DriftFile { - private static final long serialVersionUID = 1L; - - // this is a hash/digest that should uniquely identify the content - @Id - @Column(name = "HASH_ID", nullable = false) - private String hashId; - - protected RhqDriftFile() { - super(); - } - - public RhqDriftFile(String hashId) { - super(); - this.hashId = hashId; - } - - @Override - public String getHashId() { - return hashId; - } - - @Override - public void setHashId(String hashId) { - this.hashId = hashId; - } - - @Override - public String toString() { - return "RhqDriftFile [hashId=" + hashId + ", status=" + status + "]"; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java deleted file mode 100644 index 91e5f50..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.rhq.core.domain.drift; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.TreeMap; - -import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED; - -public class Snapshot implements Serializable { - - private static final long serialVersionUID = 1L; - - private int version; - - private Map<String, Drift> entries = new TreeMap<String, Drift>(); - - public int getVersion() { - return version; - } - - public Collection<Drift> getEntries() { - return entries.values(); - } - - public <D extends Drift> Snapshot add(DriftChangeSet<D> changeSet) { - for (Drift entry : changeSet.getDrifts()) { - entries.remove(entry.getPath()); - if (entry.getCategory() != FILE_REMOVED) { - entries.put(entry.getPath(), entry); - } - } - version = changeSet.getVersion(); - return this; - } - - public DiffReport diff(Snapshot right) { - Snapshot left = this; - DiffReport<Drift> diff = new DiffReport<Drift>(); - - for (Map.Entry<String, Drift> entry : left.entries.entrySet()) { - if (!right.entries.containsKey(entry.getKey())) { - diff.elementNotInRight(entry.getValue()); - } - } - - for (Map.Entry<String, Drift> entry : right.entries.entrySet()) { - if (!left.entries.containsKey(entry.getKey())) { - diff.elementNotInLeft(entry.getValue()); - } - } - - for (Map.Entry<String, Drift> entry : left.entries.entrySet()) { - Drift rightDrift = right.entries.get(entry.getKey()); - if (rightDrift != null) { - DriftFile leftFile = entry.getValue().getNewDriftFile(); - DriftFile rightFile = rightDrift.getNewDriftFile(); - - if (!leftFile.getHashId().equals(rightFile.getHashId())) { - diff.elementInConflict(entry.getValue()); - } - } - } - - return diff; - } - -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftFileDTO.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftFileDTO.java index 97fa7ef..4f6e57e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftFileDTO.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftFileDTO.java @@ -1,9 +1,13 @@ package org.rhq.core.domain.drift.dto;
+import java.io.Serializable; + import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus;
-public class DriftFileDTO implements DriftFile { +public class DriftFileDTO implements Serializable, DriftFile { + + private static final long serialVersionUID = 1L;
private String hash;
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftFileTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftFileTest.java index 05757a7..6641004 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftFileTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/DriftFileTest.java @@ -1,5 +1,7 @@ package org.rhq.core.domain.drift;
+import static org.apache.commons.io.IOUtils.toInputStream; + import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; @@ -21,8 +23,6 @@ import org.testng.annotations.Test; import org.rhq.core.domain.test.AbstractEJB3Test; import org.rhq.core.util.MessageDigestGenerator;
-import static org.apache.commons.io.IOUtils.toInputStream; - public class DriftFileTest extends AbstractEJB3Test {
static private final MessageDigestGenerator digestGen = new MessageDigestGenerator(MessageDigestGenerator.SHA_256); @@ -36,12 +36,12 @@ public class DriftFileTest extends AbstractEJB3Test { executeInTransaction(new TransactionCallback() { @Override public void execute() throws Exception { - getEntityManager().createQuery("delete from RhqDriftFile").executeUpdate(); + getEntityManager().createQuery("delete from JPADriftFile").executeUpdate(); } }); }
- // Note, this test is more of a general Blob handling test. A real RhqDriftFile never has its content updated. + // Note, this test is more of a general Blob handling test. A real JPADriftFile never has its content updated. // But this is a useful test to just ensure Blob handling is working as expected. @Test(groups = { "integration.ejb3", "driftFile" }) public void updateDriftFileData() throws Exception { @@ -49,7 +49,7 @@ public class DriftFileTest extends AbstractEJB3Test { String hashId = digestGen.calcDigestString(content);
// Create the initial driftFile - final DriftFileBits df1 = new DriftFileBits(); + final JPADriftFileBits df1 = new JPADriftFileBits(); df1.setHashId(hashId); df1.setDataSize((long) content.length()); df1.setData(Hibernate.createBlob(toInputStream(content), content.length())); @@ -66,7 +66,7 @@ public class DriftFileTest extends AbstractEJB3Test { executeInTransaction(new TransactionCallback() { @Override public void execute() { - DriftFileBits df2 = getEntityManager().find(DriftFileBits.class, df1.getHashId()); + JPADriftFileBits df2 = getEntityManager().find(JPADriftFileBits.class, df1.getHashId()); df2.setData(Hibernate.createBlob(toInputStream(newContent), newContent.length())); getEntityManager().merge(df2); } @@ -77,7 +77,7 @@ public class DriftFileTest extends AbstractEJB3Test { @Override public void execute() { try { - DriftFileBits df3 = getEntityManager().find(DriftFileBits.class, df1.getHashId()); + JPADriftFileBits df3 = getEntityManager().find(JPADriftFileBits.class, df1.getHashId()); String expected = newContent; String actual = IOUtils.toString(df3.getData());
@@ -101,7 +101,7 @@ public class DriftFileTest extends AbstractEJB3Test {
for (int i = 0; i < numDriftFiles; ++i) { File dataFile = createDataFile("test_data.txt", 1, (char) ('a' + i)); - final DriftFileBits driftFile = new DriftFileBits(); + final JPADriftFileBits driftFile = new JPADriftFileBits(); driftFile.setDataSize(dataFile.length()); driftFile.setHashId(digestGen.calcDigestString(dataFile)); driftFile.setData(Hibernate.createBlob(new BufferedInputStream(new FileInputStream(dataFile)))); @@ -117,12 +117,12 @@ public class DriftFileTest extends AbstractEJB3Test { }
final List<Blob> blobs = new ArrayList<Blob>(); - final List<DriftFileBits> driftFiles = new ArrayList<DriftFileBits>(); + final List<JPADriftFileBits> driftFiles = new ArrayList<JPADriftFileBits>(); for (final String hashId : driftFileHashIds) { executeInTransaction(new TransactionCallback() { @Override public void execute() { - DriftFileBits driftFileBits = getEntityManager().find(DriftFileBits.class, hashId); + JPADriftFileBits driftFileBits = getEntityManager().find(JPADriftFileBits.class, hashId); blobs.add(driftFileBits.getBlob()); driftFiles.add(driftFileBits); } @@ -141,7 +141,7 @@ public class DriftFileTest extends AbstractEJB3Test {
for (int i = 0; i < numDriftFiles; ++i) { File dataFile = createDataFile("test_data.txt", 10, 'X'); - final DriftFileBits driftFile = new DriftFileBits(); + final JPADriftFileBits driftFile = new JPADriftFileBits(); final int driftFileNum = i; driftFile.setDataSize(dataFile.length()); driftFile.setHashId(digestGen.calcDigestString(dataFile)); @@ -159,18 +159,18 @@ public class DriftFileTest extends AbstractEJB3Test { } catch (Exception e) { // expected for file 2 or higher if (driftFileNum == 0) { - fail("Should not be able to store RhqDriftFile with same hashId more than once."); + fail("Should not be able to store JPADriftFile with same hashId more than once."); } } }
final List<Blob> blobs = new ArrayList<Blob>(); - final List<DriftFileBits> driftFiles = new ArrayList<DriftFileBits>(); + final List<JPADriftFileBits> driftFiles = new ArrayList<JPADriftFileBits>(); for (final String hashId : driftFileHashIds) { executeInTransaction(new TransactionCallback() { @Override public void execute() { - DriftFileBits driftFileBits = getEntityManager().find(DriftFileBits.class, hashId); + JPADriftFileBits driftFileBits = getEntityManager().find(JPADriftFileBits.class, hashId); blobs.add(driftFileBits.getBlob()); driftFiles.add(driftFileBits); } diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java index 93653b3..4237f3a 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java @@ -1,10 +1,5 @@ package org.rhq.core.domain.drift;
-import java.util.HashSet; -import java.util.Set; - -import org.testng.annotations.Test; - import static java.util.Arrays.asList; import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED; import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED; @@ -15,19 +10,26 @@ import static org.rhq.core.domain.drift.DriftFileStatus.LOADED; import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder; import static org.testng.Assert.assertEquals;
+import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +import org.testng.annotations.Test; + +@SuppressWarnings("unchecked") public class SnapshotTest {
@Test public void addChangeSetWithAddedFile() { int configId = 1;
- FakeDriftChangeSet changeSet = new FakeDriftChangeSet(0, COVERAGE, configId) - .add(new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt")); + FakeDriftChangeSet changeSet = new FakeDriftChangeSet(0, COVERAGE, configId).add(new FakeDrift(FILE_ADDED, + null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"));
- Snapshot snapshot = new Snapshot().add(changeSet); + DriftSnapshot snapshot = new DriftSnapshot().add(changeSet);
- assertCollectionMatchesNoOrder(changeSet.getDrifts(), snapshot.getEntries(), "Failed to build " + - "a snapshot that contains a single change set"); + assertCollectionMatchesNoOrder(changeSet.getDrifts(), snapshot.getEntries(), "Failed to build " + + "a snapshot that contains a single change set"); assertEquals(snapshot.getVersion(), changeSet.getVersion(), "Snapshot version is wrong"); }
@@ -35,16 +37,20 @@ public class SnapshotTest { public void addChangeSetsWithAddedFiles() { int configId = 1;
- Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); + Drift<?, ?> entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1);
- Drift entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("4a5b6c", 1024, LOADED), "/drift/2.txt"); + Drift<?, ?> entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("4a5b6c", 1024, LOADED), "/drift/2.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(1, DRIFT, configId).add(entry2);
- Snapshot snapshot = new Snapshot().add(changeSet1).add(changeSet2); + DriftSnapshot snapshot = new DriftSnapshot().add(changeSet1).add(changeSet2);
- assertCollectionMatchesNoOrder(asSet(entry1, entry2), snapshot.getEntries(), "Failed to build snapshot " + - "with two change sets and file added in second change set"); + // not sure but asSet with one arg was not working for me, so create Set manually + Set set = new HashSet<Drift<?, ?>>(); + set.add(entry1); + set.add(entry2); + assertCollectionMatchesNoOrder(set, snapshot.getEntries(), "Failed to build snapshot " + + "with two change sets and file added in second change set"); assertEquals(snapshot.getVersion(), changeSet2.getVersion(), "Snapshot version is wrong"); }
@@ -52,35 +58,38 @@ public class SnapshotTest { public void replaceFileWithChangedVersion() { int configId = 1;
- Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); + Drift<?, ?> entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1);
- Drift entry2 = new FakeDrift(FILE_CHANGED, new FakeDriftFile("a1b2c3", 1024, LOADED), - new FakeDriftFile("4d5e6f", 1024, LOADED), "/drift/1.txt"); + Drift<?, ?> entry2 = new FakeDrift(FILE_CHANGED, new FakeDriftFile("a1b2c3", 1024, LOADED), new FakeDriftFile( + "4d5e6f", 1024, LOADED), "/drift/1.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(1, DRIFT, configId).add(entry2);
- Snapshot snapshot = new Snapshot().add(changeSet1).add(changeSet2); + DriftSnapshot snapshot = new DriftSnapshot().add(changeSet1).add(changeSet2);
- assertCollectionMatchesNoOrder(asSet(entry2), snapshot.getEntries(), - "Failed to build snapshot with file changed"); + // not sure but asSet with one arg was not working for me, so create Set manually + Set set = new HashSet<Drift<?, ?>>(); + set.add(entry2); + assertCollectionMatchesNoOrder(set, snapshot.getEntries(), "Failed to build snapshot with file changed"); }
@Test public void deleteFileThatHasBeenRemoved() { int configId = 1;
- Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); - Drift entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("d1f2a3", 1024, LOADED), "/drift/2.txt"); + Drift<?, ?> entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); + Drift<?, ?> entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("d1f2a3", 1024, LOADED), "/drift/2.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1).add(entry2);
Drift entry3 = new FakeDrift(FILE_REMOVED, new FakeDriftFile("a1b2c3", 1024, LOADED), null, "/drift/1.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(1, DRIFT, configId).add(entry3);
- Snapshot snapshot = new Snapshot().add(changeSet1).add(changeSet2); + DriftSnapshot snapshot = new DriftSnapshot().add(changeSet1).add(changeSet2);
- assertCollectionMatchesNoOrder(asSet(entry2), snapshot.getEntries(), - "Failed to build snapshot with a file " + - "removed."); + // not sure but asSet with one arg was not working for me, so create Set manually + Set set = new HashSet<Drift<?, ?>>(); + set.add(entry2); + assertCollectionMatchesNoOrder(set, snapshot.getEntries(), "Failed to build snapshot with a file " + "removed."); }
@Test @@ -89,17 +98,16 @@ public class SnapshotTest {
Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1); - Snapshot right = new Snapshot().add(changeSet1); + DriftSnapshot right = new DriftSnapshot().add(changeSet1);
Drift entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a3b6c9", 1024, LOADED), "/drift/2.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1).add(entry2); - Snapshot left = new Snapshot().add(changeSet1).add(changeSet2); + DriftSnapshot left = new DriftSnapshot().add(changeSet1).add(changeSet2);
- DiffReport diff = left.diff(right); + DriftDiffReport diff = left.diff(right);
- assertCollectionMatchesNoOrder(asList(entry2), diff.getElementsNotInRight(), - "Diff report does not contain " + - "elements that are in the left but not in the right."); + assertCollectionMatchesNoOrder(asList(entry2), diff.getElementsNotInRight(), "Diff report does not contain " + + "elements that are in the left but not in the right."); }
@Test @@ -108,17 +116,16 @@ public class SnapshotTest {
Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drift/1.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1); - Snapshot right = new Snapshot().add(changeSet1); + DriftSnapshot right = new DriftSnapshot().add(changeSet1);
Drift entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a3b6c9", 1024, LOADED), "/drift/2.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry2); - Snapshot left = new Snapshot().add(changeSet2); + DriftSnapshot left = new DriftSnapshot().add(changeSet2);
- DiffReport diff = left.diff(right); + DriftDiffReport diff = left.diff(right);
- assertCollectionMatchesNoOrder(asList(entry1), diff.getElementsNotInLeft(), - "Diff report does not contain " + - "elements that are in the left but not in the right"); + assertCollectionMatchesNoOrder(asList(entry1), diff.getElementsNotInLeft(), "Diff report does not contain " + + "elements that are in the left but not in the right"); }
@Test @@ -127,17 +134,16 @@ public class SnapshotTest {
Drift entry1 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("a1b2c3", 1024, LOADED), "/drfit/1.txt"); FakeDriftChangeSet changeSet1 = new FakeDriftChangeSet(0, COVERAGE, configId).add(entry1); - Snapshot right = new Snapshot().add(changeSet1); + DriftSnapshot right = new DriftSnapshot().add(changeSet1);
Drift entry2 = new FakeDrift(FILE_ADDED, null, new FakeDriftFile("c3b2a1", 1024, LOADED), "/drfit/1.txt"); FakeDriftChangeSet changeSet2 = new FakeDriftChangeSet(1, DRIFT, configId).add(entry2); - Snapshot left = new Snapshot().add(changeSet2); + DriftSnapshot left = new DriftSnapshot().add(changeSet2);
- DiffReport diff = left.diff(right); + DriftDiffReport diff = left.diff(right);
- assertCollectionMatchesNoOrder(asList(entry2), diff.getElementsInConflict(), - "Diff report does not contain " + - "element that are in both left and right and are in conflict"); + assertCollectionMatchesNoOrder(asList(entry2), diff.getElementsInConflict(), "Diff report does not contain " + + "element that are in both left and right and are in conflict"); }
<E> Set<E> asSet(E... elements) { @@ -318,13 +324,14 @@ public class SnapshotTest {
@Override public String toString() { - return "Drift[category: " + category.code() + ", oldFile: " + oldFile + ", newFile: " + newFile + - ", path: " + path + "]"; + return "Drift[category: " + category.code() + ", oldFile: " + oldFile + ", newFile: " + newFile + + ", path: " + path + "]"; } }
- static class FakeDriftFile implements DriftFile { + static class FakeDriftFile implements Serializable, DriftFile {
+ private static final long serialVersionUID = 1L; private String hash; private long size; private DriftFileStatus status; 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 6f53c6e..73bb8b2 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 @@ -1,5 +1,7 @@ package org.rhq.core.pc.drift;
+import static org.rhq.core.util.file.FileUtil.copyFile; + import java.io.File; import java.io.IOException; import java.util.List; @@ -13,8 +15,6 @@ import org.rhq.common.drift.FileEntry; import org.rhq.common.drift.Headers; import org.rhq.core.domain.drift.DriftFile;
-import static org.rhq.core.util.file.FileUtil.copyFile; - public class DriftFilesSender implements Runnable {
private Log log = LogFactory.getLog(DriftFilesSender.class); @@ -23,7 +23,7 @@ public class DriftFilesSender implements Runnable {
private Headers headers;
- private List<DriftFile> driftFiles; + private List<? extends DriftFile> driftFiles;
private ChangeSetManager changeSetMgr;
@@ -37,7 +37,7 @@ public class DriftFilesSender implements Runnable { this.headers = headers; }
- public void setDriftFiles(List<DriftFile> driftFiles) { + public void setDriftFiles(List<? extends DriftFile> driftFiles) { this.driftFiles = driftFiles; }
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 879ceca..d22563c 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 @@ -1,5 +1,7 @@ package org.rhq.core.pc.drift;
+import static org.rhq.core.util.ZipUtil.zipFileOrDirectory; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -31,8 +33,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.core.util.ZipUtil.zipFileOrDirectory; - public class DriftManager extends AgentService implements DriftAgentService, DriftClient, ContainerService {
private final Log log = LogFactory.getLog(DriftManager.class); @@ -109,8 +109,7 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri }
@Override - public void sendChangeSetToServer(int resourceId, DriftConfiguration driftConfiguration, - DriftChangeSetCategory type) { + public void sendChangeSetToServer(int resourceId, DriftConfiguration driftConfiguration, DriftChangeSetCategory type) { try { File changeSetFile = changeSetMgr.findChangeSet(resourceId, driftConfiguration.getName(), type); if (changeSetFile == null) { @@ -214,7 +213,7 @@ public class DriftManager extends AgentService implements DriftAgentService, Dri }
@Override - public boolean requestDriftFiles(int resourceId, Headers headers, List<DriftFile> driftFiles) { + public boolean requestDriftFiles(int resourceId, Headers headers, List<? extends DriftFile> driftFiles) { DriftFilesSender sender = new DriftFilesSender(); sender.setResourceId(resourceId); sender.setDriftClient(this); 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 b2cd6c2..c1f4559 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 @@ -9,7 +9,7 @@ import org.testng.annotations.Test;
import org.rhq.common.drift.Headers; import org.rhq.core.domain.drift.DriftFile; -import org.rhq.core.domain.drift.RhqDriftFile; +import org.rhq.core.domain.drift.JPADriftFile;
import static org.apache.commons.io.FileUtils.touch; import static org.apache.commons.io.IOUtils.writeLines; @@ -160,7 +160,7 @@ public class DriftFilesSenderTest extends DriftTest { List<DriftFile> driftFiles(String... hashes) { List<DriftFile> files = new ArrayList<DriftFile>(); for (String hash : hashes) { - files.add(new RhqDriftFile(hash)); + files.add(new JPADriftFile(hash)); } return files; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/AbstractRecentDriftsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/AbstractRecentDriftsPortlet.java index b182d08..94cec23 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/AbstractRecentDriftsPortlet.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/drift/AbstractRecentDriftsPortlet.java @@ -23,7 +23,7 @@ import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.criteria.DriftJPACriteria; +import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.dashboard.DashboardPortlet; import org.rhq.core.domain.drift.DriftCategory; import org.rhq.core.domain.drift.DriftComposite; @@ -349,14 +349,15 @@ public abstract class AbstractRecentDriftsPortlet extends DriftHistoryView imple * the portlet. This sets the counter appropriately and stops further queries to the server. */ @Override - protected int getTotalRows(final PageList<DriftComposite> result, final DSResponse response, final DSRequest request) { + protected int getTotalRows(final PageList<DriftComposite> result, final DSResponse response, + final DSRequest request) {
return result.size(); }
@Override - protected DriftJPACriteria getFetchCriteria(DSRequest request) { - DriftJPACriteria criteria = new DriftJPACriteria(); + protected GenericDriftCriteria getFetchCriteria(DSRequest request) { + GenericDriftCriteria criteria = new GenericDriftCriteria();
// result count String currentSetting = this.configuration.getSimpleValue(Constant.RESULT_COUNT, 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 afb6345..2151eee 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 @@ -32,10 +32,8 @@ import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.tree.TreeNode;
import org.rhq.core.domain.criteria.BaseCriteria; -import org.rhq.core.domain.criteria.BasicDriftChangeSetCriteria; -import org.rhq.core.domain.criteria.BasicDriftCriteria; -import org.rhq.core.domain.criteria.DriftChangeSetCriteria; -import org.rhq.core.domain.criteria.DriftCriteria; +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.util.PageList; @@ -94,34 +92,35 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc // There is no parent - we are at the root of the tree. // Get the top nodes (the change sets) but to be as fast as possible don't load their drifts. // We will lazily load drifts when the these changeset tree nodes are opened - DriftChangeSetCriteria criteria = getDriftChangeSetCriteria(request); - - driftService.findDriftChangeSetsByCriteria(criteria, new AsyncCallback<PageList<DriftChangeSet>>() { - public void onSuccess(PageList<DriftChangeSet> result) { - response.setData(buildRecords(result)); - response.setTotalRows(result.getTotalSize()); - processResponse(request.getRequestId(), response); - } - - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadFailure(), caught); - response.setStatus(DSResponse.STATUS_FAILURE); - processResponse(request.getRequestId(), response); - } - }); + GenericDriftChangeSetCriteria criteria = getDriftChangeSetCriteria(request); + + driftService.findDriftChangeSetsByCriteria(criteria, + new AsyncCallback<PageList<? extends DriftChangeSet>>() { + public void onSuccess(PageList<? extends DriftChangeSet> result) { + response.setData(buildRecords(result)); + response.setTotalRows(result.getTotalSize()); + processResponse(request.getRequestId(), response); + } + + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadFailure(), caught); + response.setStatus(DSResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + }); } else { String changesetId = parentId; - DriftCriteria criteria = new BasicDriftCriteria(); + GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.addFilterChangeSetId(changesetId);
- driftService.findDriftsByCriteria(criteria, new AsyncCallback<PageList<Drift>>() { + driftService.findDriftsByCriteria(criteria, new AsyncCallback<PageList<? extends Drift>>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError(MSG.view_drift_changeset_tree_loadFailure(), caught); response.setStatus(DSResponse.STATUS_FAILURE); processResponse(request.getRequestId(), response); }
- public void onSuccess(PageList<Drift> result) { + public void onSuccess(PageList<? extends Drift> result) { response.setData(buildRecords(result)); response.setTotalRows(result.getTotalSize()); processResponse(request.getRequestId(), response); @@ -176,8 +175,8 @@ public abstract class AbstractDriftChangeSetsTreeDataSource extends RPCDataSourc * * @return the criteria to use when querying for change setss */ - protected DriftChangeSetCriteria getDriftChangeSetCriteria(final DSRequest request) { - BasicDriftChangeSetCriteria criteria = new BasicDriftChangeSetCriteria(); + protected GenericDriftChangeSetCriteria getDriftChangeSetCriteria(final DSRequest request) { + GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria(); criteria.addSortVersion(PageOrdering.DESC); criteria.setPageControl(getPageControl(request)); return criteria; 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 8a6c448..5fd4e3e 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 @@ -37,8 +37,7 @@ 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.BasicDriftCriteria; -import org.rhq.core.domain.criteria.DriftCriteria; +import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.drift.DriftCategory; import org.rhq.core.domain.drift.DriftComposite; @@ -61,7 +60,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility; * @author Jay Shaughnessy * @author John Mazzitelli */ -public class DriftDataSource extends RPCDataSource<DriftComposite, DriftCriteria> { +public class DriftDataSource extends RPCDataSource<DriftComposite, GenericDriftCriteria> {
public static final String CATEGORY_ICON_NEW = ImageManager.getDriftCategoryIcon(null); public static final String CATEGORY_ICON_ADD = ImageManager.getDriftCategoryIcon(DriftCategory.FILE_ADDED); @@ -172,7 +171,7 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, DriftCriteria }
@Override - protected void executeFetch(final DSRequest request, final DSResponse response, final DriftCriteria criteria) { + protected void executeFetch(final DSRequest request, final DSResponse response, final GenericDriftCriteria criteria) { if (criteria == null) { // the user selected no categories in the filter - it makes sense from the UI perspective to show 0 rows response.setTotalRows(0); @@ -259,14 +258,14 @@ public class DriftDataSource extends RPCDataSource<DriftComposite, DriftCriteria }
@Override - protected DriftCriteria getFetchCriteria(DSRequest request) { + protected GenericDriftCriteria getFetchCriteria(DSRequest request) { 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 }
- BasicDriftCriteria criteria = new BasicDriftCriteria(); + GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.fetchChangeSet(true); criteria.addFilterCategories(categoriesFilter);
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 c51806a..3ad61c3 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 @@ -29,7 +29,7 @@ import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.StaticTextItem;
-import org.rhq.core.domain.criteria.BasicDriftCriteria; +import org.rhq.core.domain.criteria.GenericDriftCriteria; import org.rhq.core.domain.drift.Drift; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.CoreGUI; @@ -60,27 +60,28 @@ public class DriftDetailsView extends LocatableVLayout { }
private void show(String driftId) { - BasicDriftCriteria criteria = new BasicDriftCriteria(); + GenericDriftCriteria criteria = new GenericDriftCriteria(); criteria.addFilterId(driftId); criteria.fetchChangeSet(true); - GWTServiceLookup.getDriftService().findDriftsByCriteria(criteria, new AsyncCallback<PageList<Drift>>() { - @Override - public void onSuccess(PageList<Drift> result) { - if (result.getTotalSize() != 1) { - CoreGUI.getMessageCenter().notify( - new Message("Got [" + result.getTotalSize() - + "] results. Should have been 1. The details shown here might not be correct.", - Severity.Warning)); + GWTServiceLookup.getDriftService().findDriftsByCriteria(criteria, + new AsyncCallback<PageList<? extends Drift>>() { + @Override + public void onSuccess(PageList<? extends Drift> result) { + if (result.getTotalSize() != 1) { + CoreGUI.getMessageCenter().notify( + new Message("Got [" + result.getTotalSize() + + "] results. Should have been 1. The details shown here might not be correct.", + Severity.Warning)); + } + Drift drift = result.get(0); + show(drift); } - Drift drift = result.get(0); - show(drift); - } - - @Override - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_load(), caught); - } - }); + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError(MSG.view_drift_failure_load(), caught); + } + }); }
private void show(Drift drift) { 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 cf42485..01bb14a 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 @@ -53,7 +53,7 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/** - * A view that displays a paginated table of {@link org.rhq.core.domain.drift.RhqDrift}s, along with the + * A view that displays a paginated table of {@link org.rhq.core.domain.drift.JPADrift}s, along with the * ability to filter those drifts, sort those drifts, double-click a row to view full details a drift, and perform * various actions on the the drifts: delete selected, delete all from source, etc. * This view full respects the user's authorization, and will not allow acttions on the drifts unless the user is 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 f5341e2..f0f6049 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 @@ -22,7 +22,7 @@ package org.rhq.enterprise.gui.coregui.client.drift; import com.smartgwt.client.data.DSRequest;
import org.rhq.core.domain.common.EntityContext; -import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
/** * @author John Mazzitelli @@ -42,8 +42,8 @@ public class ResourceDriftChangeSetsTreeDataSource extends AbstractDriftChangeSe }
@Override - protected DriftChangeSetCriteria getDriftChangeSetCriteria(final DSRequest request) { - DriftChangeSetCriteria criteria = super.getDriftChangeSetCriteria(request); + protected GenericDriftChangeSetCriteria getDriftChangeSetCriteria(final DSRequest request) { + GenericDriftChangeSetCriteria criteria = super.getDriftChangeSetCriteria(request); criteria.addFilterResourceId(this.context.resourceId); return criteria; } 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 cc7c6f0..3618885 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,14 +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.DriftChangeSetCriteria; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; -import org.rhq.core.domain.criteria.DriftCriteria; +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.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList;
/** @@ -105,7 +104,8 @@ public interface DriftGWTService extends RemoteService { * * @return all drift changesets that matches the specified criteria */ - PageList<DriftChangeSet> findDriftChangeSetsByCriteria(DriftChangeSetCriteria criteria) throws RuntimeException; + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) + throws RuntimeException;
/** * Find all drifts that match the specified criteria. @@ -114,11 +114,11 @@ public interface DriftGWTService extends RemoteService { * * @return all drifts that match the specified criteria */ - PageList<Drift> findDriftsByCriteria(DriftCriteria criteria) throws RuntimeException; + PageList<? extends Drift<?, ?>> findDriftsByCriteria(GenericDriftCriteria criteria) throws RuntimeException;
- PageList<DriftComposite> findDriftCompositesByCriteria(DriftCriteria criteria); + PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria);
- Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria);
/** * Get the specified drift configuration for the specified context. 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 cb44a90..264ed26 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.DriftChangeSetCriteria; -import org.rhq.core.domain.criteria.DriftCriteria; +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.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.gwt.DriftGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; @@ -94,9 +94,10 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public PageList<DriftChangeSet> findDriftChangeSetsByCriteria(DriftChangeSetCriteria criteria) { + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(GenericDriftChangeSetCriteria criteria) { try { - PageList<DriftChangeSet> results = driftServer.findDriftChangeSetsByCriteria(getSessionSubject(), criteria); + PageList<? extends DriftChangeSet<?>> results = driftServer.findDriftChangeSetsByCriteria( + getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftChangeSetsByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); @@ -104,9 +105,9 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public PageList<Drift> findDriftsByCriteria(DriftCriteria criteria) throws RuntimeException { + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(GenericDriftCriteria criteria) throws RuntimeException { try { - PageList<Drift> results = driftServer.findDriftsByCriteria(getSessionSubject(), criteria); + PageList<? extends Drift<?, ?>> results = driftServer.findDriftsByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftsByCriteria"); } catch (Throwable t) { throw getExceptionToThrowToClient(t); @@ -114,7 +115,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public PageList<DriftComposite> findDriftCompositesByCriteria(DriftCriteria criteria) { + public PageList<DriftComposite> findDriftCompositesByCriteria(GenericDriftCriteria criteria) { try { PageList<DriftComposite> results = driftServer.findDriftCompositesByCriteria(getSessionSubject(), criteria); return SerialUtility.prepare(results, "DriftService.findDriftCompositesByCriteria"); @@ -124,7 +125,7 @@ public class DriftGWTServiceImpl extends AbstractGWTServiceImpl implements Drift }
@Override - public Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, GenericDriftChangeSetCriteria criteria) { try { return driftServer.createSnapshot(subject, criteria); } catch (Throwable t) { diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml index 19f5453..e7840c1 100644 --- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/core/RHQDomain.gwt.xml @@ -32,7 +32,7 @@ <source path="client"/> <source path="domain"> <!-- Exclude any domain classes that can not be used client-side due to use of unsupported class use --> - <exclude name="**/DriftFileBits.*"/> + <exclude name="**/JPADriftFileBits.*"/> </source>
<!--<generate-with class="org.rhq.core.rebind.RecordBuilderGenerator"> 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 0479c4a..419ad99 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 @@ -19,6 +19,8 @@ */ package org.rhq.enterprise.server.drift;
+import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; @@ -59,19 +61,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.configuration.Configuration; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; -import org.rhq.core.domain.criteria.DriftJPACriteria; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +import org.rhq.core.domain.criteria.DriftCriteria; +import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; +import org.rhq.core.domain.criteria.JPADriftCriteria; import org.rhq.core.domain.drift.Drift; +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.DriftFile; -import org.rhq.core.domain.drift.DriftFileBits; import org.rhq.core.domain.drift.DriftFileStatus; -import org.rhq.core.domain.drift.RhqDrift; -import org.rhq.core.domain.drift.RhqDriftChangeSet; -import org.rhq.core.domain.drift.RhqDriftFile; -import org.rhq.core.domain.drift.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.JPADriftChangeSet; +import org.rhq.core.domain.drift.JPADriftFile; +import org.rhq.core.domain.drift.JPADriftFileBits; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.ZipUtil; @@ -83,8 +88,12 @@ import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner;
-import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; - +/** + * The SLSB implementation for Drift Management. + * + * @author Jay Shaughnessy + @ @author John Sanda + */ @Stateless public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { private final Log log = LogFactory.getLog(this.getClass()); @@ -151,8 +160,8 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
@Override public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception { - List<? extends DriftFile> emptyDriftFiles = new ArrayList<RhqDriftFile>(); - RhqDriftChangeSet driftChangeSet = null; + List<JPADriftFile> emptyDriftFiles = new ArrayList<JPADriftFile>(); + JPADriftChangeSet driftChangeSet = null;
try { ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader( @@ -163,13 +172,13 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { int version = getChangeSetVersion(resource, config);
if (config == null) { - log.error("Unable to locate " + config.getClass().getSimpleName() + "[id: " + - config.getId() + ", name: " + config.getName() + "]. Change set cannot be saved."); + log.error("Unable to locate DriftConfiguration for Resource [" + resource + + "]. Change set cannot be saved."); return false; }
DriftChangeSetCategory category = reader.getHeaders().getType(); - driftChangeSet = new RhqDriftChangeSet(resource, version, category, config.getId()); + driftChangeSet = new JPADriftChangeSet(resource, version, category, config.getId()); entityManager.persist(driftChangeSet);
for (DirectoryEntry dir = reader.readDirectoryEntry(); null != dir; dir = reader @@ -177,10 +186,10 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
for (Iterator<FileEntry> i = dir.iterator(); i.hasNext();) { FileEntry entry = i.next(); - RhqDriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), - (List<RhqDriftFile>) emptyDriftFiles); - RhqDriftFile newDriftFile = getDriftFile(entry.getNewSHA(), - (List<RhqDriftFile>) emptyDriftFiles); + JPADriftFile oldDriftFile = getDriftFile(entry.getOldSHA(), + (List<JPADriftFile>) emptyDriftFiles); + JPADriftFile newDriftFile = getDriftFile(entry.getNewSHA(), + (List<JPADriftFile>) emptyDriftFiles);
// TODO Figure out an efficient way to save coverage change sets. // The initial/coverage change set could contain hundreds or even thousands @@ -191,21 +200,20 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { // use a path with only forward slashing to ensure consistent paths across reports String path = new File(dir.getDirectory(), entry.getFile()).getPath(); path = FileUtil.useForwardSlash(path); - RhqDrift drift = new RhqDrift(driftChangeSet, path, entry.getType(), oldDriftFile, + JPADrift drift = new JPADrift(driftChangeSet, path, entry.getType(), oldDriftFile, newDriftFile); entityManager.persist(drift);
} } - // send a message to the agent requesting the empty RhqDriftFile content + // send a message to the agent requesting the empty JPADriftFile content if (!emptyDriftFiles.isEmpty()) {
AgentClient agentClient = agentManager.getAgentClient(subjectManager.getOverlord(), resourceId); DriftAgentService service = agentClient.getDriftAgentService(); try { - if (service.requestDriftFiles(resourceId, reader.getHeaders(), - (List<DriftFile>) emptyDriftFiles)) { + if (service.requestDriftFiles(resourceId, reader.getHeaders(), emptyDriftFiles)) { for (DriftFile driftFile : emptyDriftFiles) { driftFile.setStatus(DriftFileStatus.REQUESTED); } @@ -247,10 +255,11 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { * @return The next change set version number */ int getChangeSetVersion(Resource r, DriftConfiguration c) { - DriftChangeSetJPACriteria criteria = new DriftChangeSetJPACriteria(); + JPADriftChangeSetCriteria criteria = new JPADriftChangeSetCriteria(); criteria.addFilterResourceId(r.getId()); criteria.addFilterDriftConfigurationId(c.getId()); - List<RhqDriftChangeSet> changeSets = findDriftChangeSetsByCriteria(subjectManager.getOverlord(), criteria); + List<? extends DriftChangeSet<?>> changeSets = findDriftChangeSetsByCriteria(subjectManager.getOverlord(), + criteria);
return changeSets.size(); } @@ -268,17 +277,17 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { private abstract class ChangeSetFileVisitor implements ZipUtil.ZipEntryVisitor { }
- private RhqDriftFile getDriftFile(String sha256, List<RhqDriftFile> emptyDriftFiles) { - RhqDriftFile result = null; + private JPADriftFile getDriftFile(String sha256, List<JPADriftFile> emptyDriftFiles) { + JPADriftFile result = null;
if (null == sha256 || "0".equals(sha256)) { return result; }
- result = entityManager.find(RhqDriftFile.class, sha256); - // if the RhqDriftFile is not yet in the db, then it needs to be fetched from the agent + result = entityManager.find(JPADriftFile.class, sha256); + // if the JPADriftFile is not yet in the db, then it needs to be fetched from the agent if (null == result) { - result = persistDriftFile(new RhqDriftFile(sha256)); + result = persistDriftFile(new JPADriftFile(sha256)); emptyDriftFiles.add(result); }
@@ -286,7 +295,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public RhqDriftFile persistDriftFile(RhqDriftFile driftFile) { + public JPADriftFile persistDriftFile(JPADriftFile driftFile) {
entityManager.persist(driftFile); return driftFile; @@ -294,11 +303,11 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
@Override @TransactionAttribute(REQUIRES_NEW) - public void persistDriftFileData(RhqDriftFile driftFile, InputStream data) throws Exception { + public void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception {
- DriftFileBits df = entityManager.find(DriftFileBits.class, driftFile.getHashId()); + JPADriftFileBits df = entityManager.find(JPADriftFileBits.class, driftFile.getHashId()); if (null == df) { - throw new IllegalArgumentException("RhqDriftFile not found [" + driftFile.getHashId() + "]"); + throw new IllegalArgumentException("JPADriftFile not found [" + driftFile.getHashId() + "]"); } df.setData(Hibernate.createBlob(new BufferedInputStream(data))); df.setStatus(DriftFileStatus.LOADED); @@ -321,7 +330,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
ZipUtil.unzipFile(filesZip, dir); for (File file : dir.listFiles()) { - RhqDriftFile driftFile = new RhqDriftFile(file.getName()); + JPADriftFile driftFile = new JPADriftFile(file.getName()); try { driftManager.persistDriftFileData(driftFile, new FileInputStream(file)); } catch (Exception e) { @@ -334,15 +343,17 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { } boolean deleted = dir.delete(); if (!deleted) { - LogFactory.getLog(getClass()).info("Unable to delete " + dir.getAbsolutePath() + ". This directory and " + - "its contents are no longer needed. It can be deleted."); + LogFactory.getLog(getClass()).info( + "Unable to delete " + dir.getAbsolutePath() + ". This directory and " + + "its contents are no longer needed. It can be deleted."); }
-// DriftFileVisitor dfVisitor = new DriftFileVisitor(driftManager); -// ZipUtil.walkZipFile(filesZip, dfVisitor); + // DriftFileVisitor dfVisitor = new DriftFileVisitor(driftManager); + // ZipUtil.walkZipFile(filesZip, dfVisitor);
}
+ /* TODO: dead code ? private static class DriftFileVisitor implements ZipUtil.ZipEntryVisitor {
private DriftManagerLocal driftManager; @@ -353,7 +364,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote {
public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception { String sha256 = entry.getName(); - RhqDriftFile driftFile = new RhqDriftFile(sha256); + JPADriftFile driftFile = new JPADriftFile(sha256);
// TODO use server plugin try { @@ -365,6 +376,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { return true; } } + */
@Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @@ -372,7 +384,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { int result = 0;
for (String driftId : driftIds) { - Drift doomed = entityManager.find(RhqDrift.class, driftId); + Drift<?, ?> doomed = entityManager.find(JPADrift.class, driftId); if (null != doomed) { entityManager.remove(doomed); ++result; @@ -397,7 +409,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { @Override public int deleteDriftsByContext(Subject subject, EntityContext entityContext) throws RuntimeException { int result = 0; - DriftJPACriteria criteria = new DriftJPACriteria(); + JPADriftCriteria criteria = new JPADriftCriteria();
switch (entityContext.getType()) { case Resource: @@ -412,11 +424,11 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { throw new IllegalArgumentException("Entity Context Type not supported [" + entityContext + "]"); }
- List<RhqDrift> drifts = driftManager.findDriftsByCriteria(subject, criteria); + List<? extends Drift<?, ?>> drifts = driftManager.findDriftsByCriteria(subject, criteria); if (!drifts.isEmpty()) { String[] driftIds = new String[drifts.size()]; int i = 0; - for (Drift drift : drifts) { + for (Drift<?, ?> drift : drifts) { driftIds[i++] = drift.getId(); }
@@ -498,33 +510,47 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { } }
+ // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl @Override - public PageList<RhqDriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetJPACriteria criteria) { + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) { + + JPADriftChangeSetCriteria jpaCriteria = (criteria instanceof JPADriftChangeSetCriteria) ? (JPADriftChangeSetCriteria) criteria + : new JPADriftChangeSetCriteria(criteria); + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); + CriteriaQueryRunner<JPADriftChangeSet> queryRunner = new CriteriaQueryRunner<JPADriftChangeSet>(jpaCriteria, + generator, entityManager); + PageList<JPADriftChangeSet> result = queryRunner.execute();
- CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - CriteriaQueryRunner<RhqDriftChangeSet> queryRunner = new CriteriaQueryRunner<RhqDriftChangeSet>(criteria, generator, - entityManager); - PageList<RhqDriftChangeSet> result = queryRunner.execute(); return result; }
+ // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl @Override - public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftJPACriteria criteria) { - // - PageList<RhqDrift> drifts = findDriftsByCriteria(subject, criteria); + public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { + + PageList<? extends Drift<?, ?>> drifts = findDriftsByCriteria(subject, criteria); PageList<DriftComposite> composites = new PageList<DriftComposite>(); - for (RhqDrift drift : drifts) { - composites.add(new DriftComposite(drift, drift.getChangeSet().getResource())); + for (Drift<?, ?> drift : drifts) { + JPADrift d = (JPADrift) drift; + composites.add(new DriftComposite(drift, d.getChangeSet().getResource())); } return composites; }
+ // TODO, this code could move to a separate SLSB supporting only the JPA Drift impl @Override - public PageList<RhqDrift> findDriftsByCriteria(Subject subject, DriftJPACriteria criteria) { + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + + JPADriftCriteria jpaCriteria = (criteria instanceof JPADriftCriteria) ? (JPADriftCriteria) criteria + : new JPADriftCriteria(criteria); + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, jpaCriteria); + CriteriaQueryRunner<JPADrift> queryRunner = new CriteriaQueryRunner<JPADrift>(jpaCriteria, generator, + entityManager); + PageList<JPADrift> result = queryRunner.execute();
- CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - CriteriaQueryRunner<RhqDrift> queryRunner = new CriteriaQueryRunner<RhqDrift>(criteria, generator, entityManager); - PageList<RhqDrift> result = queryRunner.execute(); return result; }
@@ -555,7 +581,7 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
if (null == result) { - throw new IllegalArgumentException("RhqDrift Configuration Id [" + driftConfigId + throw new IllegalArgumentException("JPADrift Configuration Id [" + driftConfigId + "] not found for entityContext [" + entityContext + "]"); }
@@ -563,8 +589,8 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public RhqDriftFile getDriftFile(Subject subject, String sha256) { - RhqDriftFile result = entityManager.find(RhqDriftFile.class, sha256); + public JPADriftFile getDriftFile(Subject subject, String sha256) { + JPADriftFile result = entityManager.find(JPADriftFile.class, sha256); return result; }
@@ -599,12 +625,12 @@ public class DriftManagerBean implements DriftManagerLocal, DriftManagerRemote { }
@Override - public Snapshot createSnapshot(Subject subject, DriftChangeSetJPACriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { // TODO security checks - Snapshot snapshot = new Snapshot(); - PageList<RhqDriftChangeSet> changeSets = findDriftChangeSetsByCriteria(subject, criteria); + DriftSnapshot snapshot = new DriftSnapshot(); + PageList<? extends DriftChangeSet<?>> changeSets = findDriftChangeSetsByCriteria(subject, criteria);
- for (RhqDriftChangeSet changeSet : changeSets) { + for (DriftChangeSet<?> changeSet : changeSets) { snapshot.add(changeSet); }
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 6939c7c..70843d4 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,14 +26,14 @@ import javax.ejb.Local;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.common.EntityContext; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; -import org.rhq.core.domain.criteria.DriftJPACriteria; +import org.rhq.core.domain.criteria.DriftChangeSetCriteria; +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.DriftComposite; import org.rhq.core.domain.drift.DriftConfiguration; -import org.rhq.core.domain.drift.RhqDrift; -import org.rhq.core.domain.drift.RhqDriftChangeSet; -import org.rhq.core.domain.drift.RhqDriftFile; -import org.rhq.core.domain.drift.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; +import org.rhq.core.domain.drift.JPADriftFile; import org.rhq.core.domain.util.PageList;
@Local @@ -105,12 +105,12 @@ public interface DriftManagerLocal extends DriftManagerRemote { void deleteDriftConfiguration(Subject subject, EntityContext entityContext, String driftConfigName);
/** - * Simple get method for a RhqDriftFile. Does not return the content. + * Simple get method for a JPADriftFile. Does not return the content. * @param subject * @param sha256 - * @return The RhqDriftFile sans content. + * @return The JPADriftFile sans content. */ - RhqDriftFile getDriftFile(Subject subject, String sha256); + JPADriftFile getDriftFile(Subject subject, String sha256);
/** * Standard criteria based fetch method @@ -118,9 +118,9 @@ public interface DriftManagerLocal extends DriftManagerRemote { * @param criteria * @return The DriftChangeSets matching the criteria */ - PageList<RhqDriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetJPACriteria criteria); + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria);
- PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftJPACriteria criteria); + PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria);
/** * Standard criteria based fetch method @@ -128,7 +128,7 @@ public interface DriftManagerLocal extends DriftManagerRemote { * @param criteria * @return The Drifts matching the criteria */ - PageList<RhqDrift> findDriftsByCriteria(Subject subject, DriftJPACriteria criteria); + PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria);
/** * Get the specified drift configuration for the specified context. @@ -178,7 +178,7 @@ public interface DriftManagerLocal extends DriftManagerRemote { * @return * @throws Exception */ - RhqDriftFile persistDriftFile(RhqDriftFile driftFile) throws Exception; + JPADriftFile persistDriftFile(JPADriftFile driftFile) throws Exception;
/** * SUPPORTS DRIFT RHQ SERVER PLUGIN @@ -186,8 +186,8 @@ public interface DriftManagerLocal extends DriftManagerRemote { * @param data * @throws Exception */ - void persistDriftFileData(RhqDriftFile driftFile, InputStream data) throws Exception; + void persistDriftFileData(JPADriftFile driftFile, InputStream data) throws Exception;
- Snapshot createSnapshot(Subject subject, DriftChangeSetJPACriteria criteria); + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria);
} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java index f66c3ab..9bad08f 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerBean.java @@ -1,5 +1,7 @@ package org.rhq.enterprise.server.drift;
+import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; + import java.io.File; import java.util.Iterator;
@@ -24,7 +26,7 @@ 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.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.RHQConstants; @@ -37,8 +39,6 @@ import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginManager; import org.rhq.enterprise.server.util.LookupUtil;
-import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; - @Stateless public class DriftServerBean implements DriftServerLocal, DriftServerRemote {
@@ -62,14 +62,15 @@ public class DriftServerBean implements DriftServerLocal, DriftServerRemote {
@Override @TransactionAttribute(NOT_SUPPORTED) - public PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) { DriftServerPluginFacet driftServerPlugin = getServerPlugin(); return driftServerPlugin.findDriftChangeSetsByCriteria(subject, criteria); }
@Override @TransactionAttribute(NOT_SUPPORTED) - public PageList<Drift> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { DriftServerPluginFacet driftServerPlugin = getServerPlugin(); return driftServerPlugin.findDriftsByCriteria(subject, criteria); } @@ -97,7 +98,7 @@ public class DriftServerBean implements DriftServerLocal, DriftServerRemote {
@Override @TransactionAttribute(NOT_SUPPORTED) - public Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { DriftServerPluginFacet driftServerPlugin = getServerPlugin(); return driftServerPlugin.createSnapshot(subject, criteria); } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java index eda3a4f..3c9da33 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerLocal.java @@ -12,7 +12,7 @@ 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.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList;
@Local @@ -28,12 +28,12 @@ public interface DriftServerLocal {
void detectDrift(Subject subject, EntityContext context, DriftConfiguration driftConfig);
- PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria);
- PageList<Drift> findDriftsByCriteria(Subject subject, DriftCriteria criteria); + PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria);
PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria);
- Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria);
} diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java index a3dc30b..33f1aa7 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/drift/DriftServerRemote.java @@ -5,14 +5,14 @@ import javax.ejb.Remote; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; import org.rhq.core.domain.drift.DriftChangeSet; -import org.rhq.core.domain.drift.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList;
@Remote public interface DriftServerRemote {
- PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria);
- Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria);
} 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 5a57837..5130a5a 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 @@ -23,12 +23,11 @@ import java.io.File;
import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; 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.DriftComposite; -import org.rhq.core.domain.drift.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent;
@@ -40,9 +39,9 @@ import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent; */ public interface DriftServerPluginFacet extends ServerPluginComponent {
- PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria); + PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria);
- PageList<Drift> findDriftsByCriteria(Subject subject, DriftCriteria criteria); + PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria);
PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria);
@@ -50,5 +49,5 @@ public interface DriftServerPluginFacet extends ServerPluginComponent {
void saveChangeSetFiles(File changeSetFilesZip) throws Exception;
- Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); + DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria); } 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 53ec93e..f0b1308 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 @@ -69,8 +69,8 @@ import org.rhq.core.domain.content.PackageInstallationStep; import org.rhq.core.domain.content.ResourceRepo; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.criteria.ResourceTypeCriteria; -import org.rhq.core.domain.drift.RhqDrift; -import org.rhq.core.domain.drift.RhqDriftChangeSet; +import org.rhq.core.domain.drift.JPADrift; +import org.rhq.core.domain.drift.JPADriftChangeSet; import org.rhq.core.domain.event.Event; import org.rhq.core.domain.event.EventSource; import org.rhq.core.domain.measurement.Availability; @@ -503,8 +503,8 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage AlertDampeningEvent.QUERY_DELETE_BY_RESOURCES, // alert- AlertNotification.QUERY_DELETE_BY_RESOURCES, // related AlertDefinition.QUERY_DELETE_BY_RESOURCES, // deletes - RhqDrift.QUERY_DELETE_BY_RESOURCES, // drift before changeset - RhqDriftChangeSet.QUERY_DELETE_BY_RESOURCES }; + JPADrift.QUERY_DELETE_BY_RESOURCES, // drift before changeset + JPADriftChangeSet.QUERY_DELETE_BY_RESOURCES };
List<Integer> resourceIds = new ArrayList<Integer>(); resourceIds.add(resourceId); 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 68482bc..6520ce9 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 @@ -41,17 +41,16 @@ import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertyMap; import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; -import org.rhq.core.domain.criteria.DriftJPACriteria; +import org.rhq.core.domain.criteria.JPADriftChangeSetCriteria; 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.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus; -import org.rhq.core.domain.drift.RhqDrift; -import org.rhq.core.domain.drift.RhqDriftChangeSet; -import org.rhq.core.domain.drift.RhqDriftFile; +import org.rhq.core.domain.drift.JPADriftFile; +import org.rhq.core.domain.drift.DriftConfigurationDefinition.BaseDirValueContext; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; @@ -69,11 +68,12 @@ import org.rhq.enterprise.server.util.LookupUtil; @Test(groups = "drift-manager") public class DriftManagerBeanTest extends AbstractEJB3Test {
- private static final boolean ENABLE_TESTS = false; + private static final boolean ENABLE_TESTS = true;
private DriftManagerLocal driftManager; private Subject overlord; private Resource newResource; + @SuppressWarnings("unused") private DriftServerService driftServerService;
/** @@ -120,16 +120,16 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { assertTrue(changeset1.exists()); driftManager.storeChangeSet(newResource.getId(), changeset1);
- DriftChangeSetJPACriteria c = new DriftChangeSetJPACriteria(); + JPADriftChangeSetCriteria c = new JPADriftChangeSetCriteria(); c.addFilterResourceId(newResource.getId()); c.fetchDrifts(true); - List<RhqDriftChangeSet> changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); + List<? extends DriftChangeSet<?>> changeSets = driftManager.findDriftChangeSetsByCriteria(overlord, c); assertEquals(1, changeSets.size()); - RhqDriftChangeSet changeSet = changeSets.get(0); + DriftChangeSet<?> changeSet = changeSets.get(0); assertEquals(0, changeSet.getVersion()); assertEquals("Expected to find one entry in change set", 1, changeSet.getDrifts().size());
- RhqDriftFile driftFile = driftManager.getDriftFile(overlord, "aaaaa"); + JPADriftFile driftFile = driftManager.getDriftFile(overlord, "aaaaa"); assertNotNull(driftFile); assertEquals(DriftFileStatus.REQUESTED, driftFile.getStatus());
@@ -146,7 +146,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { changeSet = changeSets.get(1); assertEquals(1, changeSet.getVersion()); assertEquals(1, changeSet.getDrifts().size()); - RhqDrift drift = changeSet.getDrifts().iterator().next(); + Drift<?, ?> drift = changeSet.getDrifts().iterator().next(); assertEquals("dir/filename.ext", drift.getPath()); assertEquals("aaaaa", drift.getOldDriftFile().getHashId()); assertEquals("bbbbb", drift.getNewDriftFile().getHashId()); @@ -255,7 +255,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { try { // wipe out any test DriftFiles (the test files have sha256 0,1,...) for (int i = 0, numDeleted = 1; (numDeleted > 0); ++i) { - numDeleted = getEntityManager().createQuery("delete from RhqDriftFile where hash_id = '" + i + "'") + numDeleted = getEntityManager().createQuery("delete from JPADriftFile where hash_id = '" + i + "'") .executeUpdate(); } } catch (Exception e) { @@ -298,7 +298,6 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { driftConfigs.add(test1Config.getConfiguration()); driftConfigs.add(test2Config.getConfiguration());
- resource = new Resource("reskey" + System.currentTimeMillis(), "resname", resourceType); resource.setUuid("" + new Random().nextInt()); resource.setAgent(agent); @@ -366,7 +365,7 @@ public class DriftManagerBeanTest extends AbstractEJB3Test { private class TestConfigService implements DriftAgentService {
@Override - public boolean requestDriftFiles(int resourceId, Headers headers, List<DriftFile> driftFiles) { + public boolean requestDriftFiles(int resourceId, Headers headers, List<? extends DriftFile> driftFiles) { return true; }
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 8d39917..2c31e18 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 @@ -331,7 +331,7 @@ public class TestAgentClient implements AgentClient, BundleAgentService, DriftAg }
@Override - public boolean requestDriftFiles(int resourceId, Headers headers, List<DriftFile> driftFiles) { + public boolean requestDriftFiles(int resourceId, Headers headers, List<? extends DriftFile> driftFiles) { return false; }
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 d1115ba..d58c3f1 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 @@ -1,11 +1,12 @@ package org.rhq.enterprise.server.plugins.drift.mongodb;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; + import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipEntry; @@ -16,8 +17,6 @@ import com.google.code.morphia.Morphia; import com.google.code.morphia.query.Query; import com.mongodb.Mongo;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.bson.types.ObjectId;
import org.rhq.common.drift.ChangeSetReader; @@ -32,7 +31,7 @@ import org.rhq.core.domain.criteria.ResourceCriteria; 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.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.drift.dto.DriftChangeSetDTO; import org.rhq.core.domain.drift.dto.DriftDTO; import org.rhq.core.domain.drift.dto.DriftFileDTO; @@ -47,11 +46,9 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile; import org.rhq.enterprise.server.resource.ResourceManagerLocal;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager; - public class MongoDBDriftServer implements DriftServerPluginFacet {
- private final Log log = LogFactory.getLog(MongoDBDriftServer.class); + //private final Log log = LogFactory.getLog(MongoDBDriftServer.class);
private Mongo connection;
@@ -64,10 +61,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { @Override public void initialize(ServerPluginContext context) throws Exception { connection = new Mongo("localhost"); - morphia = new Morphia() - .map(MongoDBChangeSet.class) - .map(MongoDBChangeSetEntry.class) - .map(MongoDBFile.class); + morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class); ds = morphia.createDatastore(connection, "rhq"); }
@@ -124,11 +118,12 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override - public PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { - Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class) - .filter("resourceId =", criteria.getFilterResourceId()); + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) { + Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class).filter("resourceId =", + criteria.getFilterResourceId());
- PageList results = new PageList<DriftChangeSetDTO>(); + PageList<DriftChangeSetDTO> results = new PageList<DriftChangeSetDTO>(); for (MongoDBChangeSet changeSet : query) { DriftChangeSetDTO changeSetDTO = toDTO(changeSet); Set<DriftDTO> entries = new HashSet<DriftDTO>(); @@ -144,7 +139,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override - public PageList<Drift> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class); boolean changeSetIdFiltered = false;
@@ -161,7 +156,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { query.filter("id = ", new ObjectId(criteria.getFilterChangeSetId())); }
- PageList results = new PageList<DriftDTO>(); + PageList<DriftDTO> results = new PageList<DriftDTO>();
for (MongoDBChangeSet changeSet : query) { DriftChangeSetDTO changeSetDTO = toDTO(changeSet); @@ -170,14 +165,13 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { } }
- return (PageList<Drift>) results; + return results; }
@Override public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { - Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class) - .filter("files.category in ", criteria.getFilterCategories()) - .filter("resourceId in", criteria.getFilterResourceIds()); + Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class).filter("files.category in ", + criteria.getFilterCategories()).filter("resourceId in", criteria.getFilterResourceIds());
PageList<DriftComposite> results = new PageList<DriftComposite>(); Map<Integer, Resource> resources = loadResourceMap(subject, criteria.getFilterResourceIds()); @@ -193,13 +187,13 @@ public class MongoDBDriftServer implements DriftServerPluginFacet { }
@Override - public Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { return null; }
- Map<Integer, Resource> loadResourceMap(Subject subject, List<Integer> resourceIds) { + Map<Integer, Resource> loadResourceMap(Subject subject, Integer[] resourceIds) { ResourceCriteria criteria = new ResourceCriteria(); - criteria.addFilterIds(resourceIds.toArray(new Integer[resourceIds.size()])); + criteria.addFilterIds(resourceIds);
ResourceManagerLocal resourceMgr = getResourceManager(); PageList<Resource> resources = resourceMgr.findResourcesByCriteria(subject, criteria); diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java index ea0c509..6a40465 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java +++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java @@ -1,5 +1,7 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.entities;
+import java.io.Serializable; + import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Id;
@@ -7,14 +9,17 @@ import org.rhq.core.domain.drift.DriftFile; import org.rhq.core.domain.drift.DriftFileStatus;
@Entity -public class MongoDBFile implements DriftFile { +public class MongoDBFile implements Serializable, DriftFile { + + private static final long serialVersionUID = 1L;
+ @SuppressWarnings("unused") @Id private String hash;
@Override public String getHashId() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override @@ -24,12 +29,12 @@ public class MongoDBFile implements DriftFile {
@Override public Long getCtime() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override public Long getDataSize() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override @@ -39,7 +44,7 @@ public class MongoDBFile implements DriftFile {
@Override public DriftFileStatus getStatus() { - return null; //To change body of implemented methods use File | Settings | File Templates. + return null; //To change body of implemented methods use File | Settings | File Templates. }
@Override diff --git a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java index c2520d5..7a28b53 100644 --- a/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java +++ b/modules/enterprise/server/plugins/drift-rhq/src/main/java/org/rhq/enterprise/server/plugins/drift/DriftServerPluginComponent.java @@ -19,6 +19,8 @@ */ package org.rhq.enterprise.server.plugins.drift;
+import static org.rhq.enterprise.server.util.LookupUtil.getDriftManager; + import java.io.File;
import org.apache.commons.logging.Log; @@ -27,20 +29,15 @@ import org.apache.commons.logging.LogFactory; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.DriftChangeSetCriteria; import org.rhq.core.domain.criteria.DriftCriteria; -import org.rhq.core.domain.criteria.DriftJPACriteria; -import org.rhq.core.domain.criteria.DriftChangeSetJPACriteria; 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.DriftComposite; -import org.rhq.core.domain.drift.Snapshot; +import org.rhq.core.domain.drift.DriftSnapshot; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.drift.DriftManagerLocal; import org.rhq.enterprise.server.plugin.pc.ServerPluginContext; import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
-import static org.rhq.enterprise.server.util.LookupUtil.getDriftManager; - /** * A drift server-side plugin component that the server uses to process drift files. * @@ -72,21 +69,22 @@ public class DriftServerPluginComponent implements DriftServerPluginFacet { }
@Override - public PageList<DriftChangeSet> findDriftChangeSetsByCriteria(Subject subject, DriftChangeSetCriteria criteria) { - PageList<? extends DriftChangeSet> results = getDriftManager().findDriftChangeSetsByCriteria(subject, - toJPACriteria(criteria)); - return (PageList<DriftChangeSet>) results; + public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject, + DriftChangeSetCriteria criteria) { + PageList<? extends DriftChangeSet<?>> results = getDriftManager().findDriftChangeSetsByCriteria(subject, + criteria); + return results; }
@Override - public PageList<Drift> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { - PageList<? extends Drift> results = getDriftManager().findDriftsByCriteria(subject, toJPACriteria(criteria)); - return (PageList<Drift>) results; + public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) { + PageList<? extends Drift<?, ?>> results = getDriftManager().findDriftsByCriteria(subject, criteria); + return results; }
@Override public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) { - return getDriftManager().findDriftCompositesByCriteria(subject, toJPACriteria(criteria)); + return getDriftManager().findDriftCompositesByCriteria(subject, criteria); }
@Override @@ -102,40 +100,8 @@ public class DriftServerPluginComponent implements DriftServerPluginFacet { }
@Override - public Snapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { + public DriftSnapshot createSnapshot(Subject subject, DriftChangeSetCriteria criteria) { DriftManagerLocal driftMgr = getDriftManager(); - return driftMgr.createSnapshot(subject, toJPACriteria(criteria)); - } - - private DriftChangeSetJPACriteria toJPACriteria(DriftChangeSetCriteria criteria) { - DriftChangeSetJPACriteria jpaCriteria = new DriftChangeSetJPACriteria(); - jpaCriteria.addFilterId(criteria.getFilterId()); - jpaCriteria.addFilterResourceId(criteria.getFilterResourceId()); - jpaCriteria.addFilterDriftConfigurationId(criteria.getFilterDriftConfigurationId()); - jpaCriteria.addFilterCategory(criteria.getFilterCategory()); - jpaCriteria.addFilterCreatedAfter(criteria.getFilterCreatedAfter()); - jpaCriteria.addFilterCreatedBefore(criteria.getFilterCreatedBefore()); - jpaCriteria.addFilterEndVersion(criteria.getFilterEndVersion()); - jpaCriteria.addFilterStartVersion(criteria.getFilterStartVersion()); - jpaCriteria.addFilterVersion(criteria.getFilterVersion()); - jpaCriteria.addSortVersion(criteria.getSortVersion()); - jpaCriteria.fetchDrifts(criteria.isFetchDrifts()); - - return jpaCriteria; - } - - private DriftJPACriteria toJPACriteria(DriftCriteria criteria) { - DriftJPACriteria jpaCriteria = new DriftJPACriteria(); - jpaCriteria.addFilterId(criteria.getFilterId()); - jpaCriteria.addFilterCategories(criteria.getFilterCategories().toArray(new DriftCategory[]{})); - jpaCriteria.addFilterChangeSetId(criteria.getFilterChangeSetId()); - jpaCriteria.addFilterEndTime(criteria.getFilterEndTime()); - jpaCriteria.addFilterPath(criteria.getFilterPath()); - jpaCriteria.addFilterResourceIds(criteria.getFilterResourceIds().toArray(new Integer[]{})); - jpaCriteria.addFilterStartTime(criteria.getFilterStartTime()); - jpaCriteria.fetchChangeSet(criteria.isFetchChangeSet()); - jpaCriteria.addSortCtime(criteria.getSortCtime()); - - return jpaCriteria; + return driftMgr.createSnapshot(subject, criteria); } } diff --git a/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml index 0843ff5..e245d04 100644 --- a/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/drift-rhq/src/main/resources/META-INF/rhq-serverplugin.xml @@ -3,9 +3,9 @@ <drift-plugin version="1.0" apiVersion="1.0" - description="The Drift Management RHQ Persistence Store (the default backend)" - displayName="Drift:RHQ" - name="drift-rhq" + description="The JPA Drift Management Backend (the RHQ default backend)" + displayName="Drift:JPA (RHQ default)" + name="drift-jpa" package="org.rhq.enterprise.server.plugins.drift" xmlns="urn:xmlns:rhq-serverplugin.drift" xmlns:serverplugin="urn:xmlns:rhq-serverplugin" diff --git a/modules/enterprise/server/plugins/validate-all-serverplugins/pom.xml b/modules/enterprise/server/plugins/validate-all-serverplugins/pom.xml index 7f67766..9e221a0 100644 --- a/modules/enterprise/server/plugins/validate-all-serverplugins/pom.xml +++ b/modules/enterprise/server/plugins/validate-all-serverplugins/pom.xml @@ -57,6 +57,7 @@ <pathelement location="../alert-subject/target/alert-subject-${project.version}.jar" /> <pathelement location="../alert-log4j/target/alert-log4j-${project.version}.jar" /> <pathelement location="../cobbler/target/cobbler-${project.version}.jar" /> + <pathelement location="../drift-mongodb/target/drift-mongodb-serverplugin-${project.version}.jar" /> <pathelement location="../drift-rhq/target/rhq-serverplugin-drift-${project.version}.jar" /> <pathelement location="../filetemplate-bundle/target/rhq-serverplugin-filetemplate-bundle-${project.version}.jar" /> <pathelement location="../ant-bundle/target/rhq-serverplugin-ant-bundle-${project.version}.jar" />
commit e618398ee8022f1073713af206a22b09653642e1 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Aug 2 16:36:35 2011 -0400
Add mongodb jar deps and src decls
diff --git a/.classpath b/.classpath index a1e9e14..bdc2f4f 100644 --- a/.classpath +++ b/.classpath @@ -117,8 +117,12 @@ <classpathentry exported="true" kind="var" path="M2_REPO/org/unitils/unitils-testng/3.1/unitils-testng-3.1.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-core-asl/1.7.4/jackson-core-asl-1.7.4.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/org/codehaus/jackson/jackson-mapper-asl/1.7.4/jackson-mapper-asl-1.7.4.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/org/mongodb/mongo-java-driver/2.6.3/mongo-java-driver-2.6.3.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/morphia/morphia/1.00-SNAPSHOT/morphia-1.00-SNAPSHOT.jar"/> <classpathentry exported="true" kind="lib" path="modules/enterprise/remoting/webservices/target/rhq-remoting-webservices-4.1.0-SNAPSHOT/wsconsume-output"/> <classpathentry kind="src" path="modules/common/ant-bundle/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/server/plugins/drift-mongodb/src/main/java"/> + <classpathentry kind="src" path="modules/enterprise/server/plugins/drift-mongodb/src/test/java"/> <classpathentry kind="src" path="modules/common/drift/src/main/java"/> <classpathentry kind="src" path="modules/common/drift/src/test/java"/> <classpathentry kind="src" path="modules/enterprise/server/plugins/drift-rhq/src/main/java"/>
commit 5647a5530d6bbd5e61c2da40e874092886cc3614 Author: John Sanda jsanda@redhat.com Date: Tue Aug 2 17:18:36 2011 -0400
Downgrading morphia dependency from SNAPSHOT to release version
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml index 958d3e0..2cb4bbf 100644 --- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml +++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml @@ -54,7 +54,7 @@ <dependency> <groupId>com.google.code.morphia</groupId> <artifactId>morphia</artifactId> - <version>1.00-SNAPSHOT</version> + <version>0.99</version> </dependency>
<dependency>
rhq-commits@lists.fedorahosted.org