.classpath | 4 modules/cli-tests/pom.xml | 86 modules/common/ant-bundle/pom.xml | 89 - modules/common/filetemplate-bundle/pom.xml | 89 - modules/common/jboss-as/pom.xml | 95 + modules/core/client-api/pom.xml | 86 modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java | 4 modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataManager.java | 5 modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java | 154 + modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeResponse.java | 80 modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java | 12 modules/core/client-api/src/main/resources/rhq-configuration.xsd | 11 modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/MetadataManagerTest.java | 3 modules/core/client-api/src/test/resources/metadata-manager-test-1.xml | 4 modules/core/client-api/src/test/resources/test-custom-jmx.xml | 9 modules/core/dbutils/pom.xml | 87 modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml | 2 modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml | 1 modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml | 1 modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml | 3 modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 15 modules/core/domain/pom.xml | 147 + modules/core/domain/src/main/java/org/rhq/core/RHQDomain.gwt.xml | 18 modules/core/domain/src/main/java/org/rhq/core/client/RHQDomain.java | 31 modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java | 8 modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java | 75 modules/core/domain/src/main/java/org/rhq/core/domain/cloud/PartitionEventType.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/cloud/composite/FailoverListComposite.java | 29 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java | 139 - modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java | 81 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyList.java | 35 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java | 32 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertySimple.java | 73 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java | 54 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java | 43 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java | 1 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyGroupDefinition.java | 2 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupPluginConfigurationUpdate.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupResourceConfigurationUpdate.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java | 9 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java | 15 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java | 10 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/discovery/AvailabilityReport.java | 93 - modules/core/domain/src/main/java/org/rhq/core/domain/discovery/InventoryReportResponse.java | 58 modules/core/domain/src/main/java/org/rhq/core/domain/discovery/ResourceSyncInfo.java | 20 modules/core/domain/src/main/java/org/rhq/core/domain/event/Event.java | 20 modules/core/domain/src/main/java/org/rhq/core/domain/event/EventSource.java | 19 modules/core/domain/src/main/java/org/rhq/core/domain/event/transfer/EventReport.java | 21 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java | 59 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java | 55 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java | 70 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementOOB.java | 13 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java | 90 - modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementSchedule.java | 1 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementUnits.java | 112 - modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java | 72 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeDataValue.java | 32 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementNumericValueAndUnits.java | 50 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementScheduleComposite.java | 4 modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementStringValueAndUnits.java | 51 modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationHistory.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationHistory.java | 12 modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java | 19 modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventoryStatus.java | 22 modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java | 164 - modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceError.java | 40 modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceErrorType.java | 7 modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java | 14 modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceType.java | 99 - modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java | 121 + modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java | 18 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceFacets.java | 5 modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java | 22 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/Group.java | 11 modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java | 9 modules/core/domain/src/main/java/org/rhq/core/domain/util/AuthzConstants.java | 45 modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java | 11 modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.css | 7 modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.html | 10 modules/core/domain/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java | 172 - modules/core/domain/src/main/java/org/rhq/core/server/ExternalizableStrategy.java | 5 modules/core/domain/src/main/java/org/rhq/core/server/PersistenceUtility.java | 42 modules/core/domain/src/test/java/org/rhq/core/domain/configuration/ConfigurationTest.java | 235 -- modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceTest.java | 86 modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/TokenGenerationTest.java | 85 modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java | 49 modules/core/native-system/pom.xml | 92 + modules/core/plugin-api/pom.xml | 90 - modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeContext.java | 89 + modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java | 45 modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/util/ResponseTimeLogParser.java | 7 modules/core/plugin-container/pom.xml | 235 ++ modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java | 2 modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java | 3 modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventManager.java | 9 modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java | 2 modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java | 5 modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java | 474 ++++- modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java | 7 modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java | 15 modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/DiscoverySuspendedException.java | 50 modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java | 267 +++ modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java | 10 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java | 352 +++ modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ForwardingProxy.java | 72 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java | 493 +++++ modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java | 331 +++ modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java | 413 ++++ modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java | 70 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/ResComponent.java | 46 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml | 18 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java | 80 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java | 118 + modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponentInterface.java | 36 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java | 68 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/NothingDiscoveringDiscoveryComponent.java | 42 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml | 39 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml | 32 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml | 31 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml | 32 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml | 31 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml | 25 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml | 28 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml | 25 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml | 45 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml | 43 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/DiscComponent.java | 22 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/ResComponent.java | 21 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml | 18 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/DiscComponent.java | 54 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/ResComponent.java | 21 modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml | 18 modules/core/pom.xml | 12 modules/core/util/pom.xml | 86 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java | 42 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java | 3 modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java | 2 modules/enterprise/agent/src/test/java/org/rhq/enterprise/agent/PluginContainerConditionalRestart.java | 31 modules/enterprise/comm/pom.xml | 86 modules/enterprise/gui/coregui/pom.xml | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/core/RHQDomain.gwt.xml | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/core/client/RHQDomain.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java | 172 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml | 16 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/RefreshableView.java | 32 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/UserSessionManager.java | 22 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java | 98 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java | 26 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationInfo.java | 157 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java | 599 ++++++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java | 19 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemRolesNotificationSenderForm.java | 202 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemUsersNotificationSenderForm.java | 203 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java | 167 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java | 885 +++++++--- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java | 332 +++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupMemberConfiguration.java | 81 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ListGridConfigurationEditor.java | 255 -- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/table/Table.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/GWTServiceLookup.java | 21 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleCompositeDataSource.java | 218 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleDataSource.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java | 24 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/AbstractTwoLevelTabSetView.java | 15 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java | 161 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupDetailView.java | 8 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/ResourceGroupTreeView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java | 231 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java | 26 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java | 36 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/ResourceSearchView.java | 4 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java | 3 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java | 334 ++- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java | 98 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java | 31 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/schedules/SchedulesDataSource.java | 19 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java | 299 +++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java | 327 --- modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java | 100 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java | 1 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java | 23 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ResourceFactoryCreateWizard.java | 109 - modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourcePicker.java | 202 ++ modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourcePicker.java | 57 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourceSelector.java | 47 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java | 14 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBDataSource.java | 2 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java | 84 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java | 41 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java | 5 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java | 45 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/MessageBar.java | 37 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/LocatableIButton.java | 6 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java | 30 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java | 110 + modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java | 12 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java | 20 modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java | 51 modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css | 6 modules/enterprise/gui/installer-war/pom.xml | 86 modules/enterprise/gui/portal-war/pom.xml | 86 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/config/SystemConfigForm.java | 15 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java | 20 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/group/ResourceGroupUIBean.java | 4 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java | 4 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/NewGroupAction.java | 2 modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/portlet/recentlyApproved/ViewAction.java | 3 modules/enterprise/gui/portal-war/src/main/webapp-filtered/WEB-INF/classes/ApplicationResources.properties | 2 modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp | 104 - modules/enterprise/pom.xml | 11 modules/enterprise/remoting/cli/pom.xml | 88 modules/enterprise/remoting/webservices/src/test/java/org/rhq/enterprise/server/ws/WsResourceManagerTest.java | 16 modules/enterprise/server/container/pom.xml | 114 + modules/enterprise/server/jar/pom.xml | 94 + 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/auth/SubjectManagerBean.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java | 4 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java | 111 + modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java | 14 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/jaxb/adapter/ResourceGroupAdapter.java | 1 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java | 11 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerBean.java | 92 - modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java | 30 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerRemote.java | 11 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerBean.java | 8 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java | 2 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java | 3 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/test/DiscoveryTestBean.java | 30 modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/webservices/WebservicesManagerBean.java | 8 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/alert/test/AlertManagerBeanTest.java | 1 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java | 142 - modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java | 130 + modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJobTest.java | 1 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3PerformanceTest.java | 8 modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java | 3 modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml | 41 modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml | 47 modules/enterprise/server/jar/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml | 2 modules/enterprise/server/plugins/alert-mobicents/src/main/resources/META-INF/rhq-serverplugin.xml | 4 modules/enterprise/server/plugins/alert-operations/pom.xml | 87 modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java | 4 modules/enterprise/server/plugins/alert-roles/src/main/java/org/rhq/enterprise/server/plugins/alertRoles/RolesBackingBean.java | 83 modules/enterprise/server/plugins/alert-roles/src/main/resources/META-INF/rhq-serverplugin.xml | 12 modules/enterprise/server/plugins/alert-roles/src/main/resources/roles.xhtml | 22 modules/enterprise/server/plugins/alert-scriptlang/src/main/resources/META-INF/rhq-serverplugin.xml | 2 modules/enterprise/server/plugins/alert-sms/src/main/resources/META-INF/rhq-serverplugin.xml | 4 modules/enterprise/server/plugins/alert-subject/pom.xml | 21 modules/enterprise/server/plugins/alert-subject/src/main/java/org/rhq/enterprise/server/plugins/alertSubject/SubjectsBackingBean.java | 84 modules/enterprise/server/plugins/alert-subject/src/main/resources/META-INF/rhq-serverplugin.xml | 14 modules/enterprise/server/plugins/alert-subject/src/main/resources/subjects.xhtml | 22 modules/enterprise/server/plugins/cobbler/src/main/resources/META-INF/rhq-serverplugin.xml | 2 modules/enterprise/server/plugins/groovy-script/pom.xml | 86 modules/enterprise/server/plugins/groovy-script/src/main/resources/META-INF/rhq-serverplugin.xml | 2 modules/enterprise/server/plugins/jboss-software/pom.xml | 86 modules/enterprise/server/plugins/rhnhosted/pom.xml | 89 - modules/enterprise/server/plugins/url/pom.xml | 87 modules/enterprise/server/xml-schemas/pom.xml | 87 modules/enterprise/server/xml-schemas/src/test/resources/test-serverplugin-generic.xml | 4 modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/reporting/ExcelExporter.java | 7 modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/testng/DatabaseSetupInterceptor.java | 25 modules/helpers/pom.xml | 12 modules/plugins/JBossOSGi/pom.xml | 85 modules/plugins/aliases/pom.xml | 86 modules/plugins/ant-bundle/pom.xml | 85 modules/plugins/apache/pom.xml | 92 - modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java | 152 - modules/plugins/apache/src/main/resources/META-INF/rhq-plugin.xml | 21 modules/plugins/byteman/pom.xml | 86 modules/plugins/cobbler/pom.xml | 87 modules/plugins/cron/pom.xml | 86 modules/plugins/database/pom.xml | 86 modules/plugins/filetemplate-bundle/pom.xml | 86 modules/plugins/grub/pom.xml | 86 modules/plugins/hadoop/pom.xml | 85 modules/plugins/hadoop/src/main/java/org/rhq/plugins/hadoop/HadoopComponent.java | 2 modules/plugins/hibernate/pom.xml | 86 modules/plugins/hosts/pom.xml | 86 modules/plugins/hudson/pom.xml | 2 modules/plugins/iis/pom.xml | 86 modules/plugins/iis/src/main/java/org/rhq/plugins/iis/IISResponseTimeDelegate.java | 7 modules/plugins/irc/pom.xml | 85 modules/plugins/jboss-as-5/pom.xml | 86 modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/AbstractEjbBeanComponent.java | 13 modules/plugins/jboss-as-5/src/main/resources/META-INF/rhq-plugin.xml | 16 modules/plugins/jboss-as/pom.xml | 86 modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB2BeanComponent.java | 13 modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB3BeanComponent.java | 60 modules/plugins/jboss-as/src/main/resources/META-INF/rhq-plugin.xml | 16 modules/plugins/jboss-cache-v3/pom.xml | 86 modules/plugins/jboss-cache/pom.xml | 86 modules/plugins/jboss-cache/src/main/resources/META-INF/rhq-plugin.xml | 10 modules/plugins/jdbctrace/pom.xml | 86 modules/plugins/jira/pom.xml | 86 modules/plugins/jmx/pom.xml | 86 modules/plugins/jmx/src/main/resources/META-INF/rhq-plugin.xml | 5 modules/plugins/kickstart/pom.xml | 86 modules/plugins/lsof/pom.xml | 86 modules/plugins/lsof/src/main/resources/META-INF/rhq-plugin.xml | 4 modules/plugins/mysql/pom.xml | 86 modules/plugins/netservices/pom.xml | 86 modules/plugins/netservices/src/main/resources/META-INF/rhq-plugin.xml | 4 modules/plugins/nss/pom.xml | 85 modules/plugins/onewire/pom.xml | 86 modules/plugins/oracle/pom.xml | 86 modules/plugins/perftest/pom.xml | 2 modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml | 4 modules/plugins/platform/pom.xml | 86 modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml | 8 modules/plugins/pom.xml | 6 modules/plugins/postfix/pom.xml | 86 modules/plugins/postgres/pom.xml | 86 modules/plugins/rhq-agent/pom.xml | 86 modules/plugins/rhq-agent/src/main/resources/META-INF/rhq-plugin.xml | 30 modules/plugins/rhq-server/pom.xml | 86 modules/plugins/samba/pom.xml | 86 modules/plugins/script/pom.xml | 86 modules/plugins/script2/pom.xml | 85 modules/plugins/services/pom.xml | 85 modules/plugins/snmptrapd/pom.xml | 86 modules/plugins/sshd/pom.xml | 86 modules/plugins/sshd/src/main/resources/META-INF/rhq-plugin.xml | 17 modules/plugins/sudoers/pom.xml | 86 modules/plugins/tomcat/pom.xml | 86 modules/plugins/tomcat/src/main/resources/META-INF/rhq-plugin.xml | 3 modules/plugins/twitter/pom.xml | 86 modules/plugins/twitter/src/main/resources/META-INF/rhq-plugin.xml | 5 modules/plugins/virt/pom.xml | 86 modules/test-utils/pom.xml | 6 pom.xml | 17 349 files changed, 16546 insertions(+), 4430 deletions(-)
New commits: commit 1d1565dd1a551ef75491d4e010d2ef6b0fee4fd3 Merge: ad5ba13... b1865ae... Author: Heiko W. Rupp hwr@redhat.com Date: Tue Oct 12 14:25:37 2010 +0200
Merge branch 'master' into perftest
Conflicts: modules/enterprise/server/jar/pom.xml
diff --cc modules/enterprise/server/jar/pom.xml index 1f05256,697056a..2abdae5 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@@ -491,10 -483,10 +491,10 @@@ Build-OS-Version=${os.version </executions> </plugin>
- <plugin> + <plugin> - <artifactId>maven-surefire-plugin</artifactId> + <artifactId>maven-surefire-plugin</artifactId> <!-- Everything but the web service tests, this is the standard test execution --> - <configuration> + <configuration> <excludes> <exclude>com/**/*.java</exclude> </excludes> @@@ -504,9 -496,9 +504,9 @@@ <deploymentDirectory>target/classes</deploymentDirectory> <hibernate.dialect>${rhq.test.ds.hibernate-dialect}</hibernate.dialect> </systemPropertyVariables> - <additionalClasspathElements> + <additionalClasspathElements> <!-- The below is required for tests to run against Oracle. --> - <additionalClasspathElement>${settings.localRepository}/com/oracle/ojdbc5/${ojdbc5.version}/ojdbc5-${ojdbc5.version}.jar</additionalClasspathElement> + <additionalClasspathElement>${settings.localRepository}/com/oracle/ojdbc5/${ojdbc5.version}/ojdbc5-${ojdbc5.version}.jar</additionalClasspathElement> </additionalClasspathElements> </configuration> </plugin> @@@ -700,8 -692,94 +700,94 @@@ </plugins> </build>
- </profile> + </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> - <artifactId>maven-antrun-plugin</artifactId> ++ <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> - <version>1.9.4.1</version> ++ <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> - <executions> - <execution> ++ <executions> ++ <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> - <configuration> - <tasks> ++ <configuration> ++ <tasks> + <!-- prepare directory structure for cobertura--> - <mkdir dir="target/cobertura" /> ++ <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> - <include name="**/*.class" /> ++ <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> - <fileset dir="${project.build.directory}/classes"> ++ <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + <exclude name="**/DynamicConfigurationPropertyLocal.class" /> + <exclude name="**/DynamicConfigurationPropertyBean.class" /> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> - </execution> ++ </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> - <include name="**/*.class" /> ++ <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> - <fileset dir="${basedir}/src/main/java"> ++ <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> - </execution> - </executions> - </plugin> ++ </execution> ++ </executions> ++ </plugin> + </plugins> + </build> + </profile> </profiles> - + </project>
commit ad5ba139f79bd9828817e383dcaa1f8285df6c6b Author: Heiko W. Rupp hwr@redhat.com Date: Tue Oct 12 14:07:49 2010 +0200
Don't fail if the sheet already exists, but just reuse it.
diff --git a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/reporting/ExcelExporter.java b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/reporting/ExcelExporter.java index 6d9c7f6..6662b71 100644 --- a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/reporting/ExcelExporter.java +++ b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/reporting/ExcelExporter.java @@ -115,9 +115,12 @@ public class ExcelExporter implements PerformanceReportExporter { * @param result TestNG results of the test */ private void createDetailsSheet(Workbook wb, Map<String,Long> timings, ITestResult result) { - Sheet sheet = wb.createSheet(result.getName());
- Row row = sheet.createRow(0); + Sheet sheet = wb.getSheet(result.getName()); + if (sheet ==null) + sheet = wb.createSheet(result.getName()); + + Row row = appendRow(sheet); Cell cell = row.createCell(0); cell.setCellStyle(boldText); cell.setCellValue("Class");
commit c8609334f26fa129c1b1a3de0b269cd104efd8a2 Author: Heiko W. Rupp hwr@redhat.com Date: Tue Oct 12 14:07:22 2010 +0200
Be more verbose (for now), clean out subjects after tests and fix alert definition setup.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java index c95f0d4..6bc40b5 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java @@ -26,7 +26,9 @@ import javax.persistence.Query;
import org.rhq.core.domain.alert.AlertCondition; import org.rhq.core.domain.alert.AlertConditionCategory; +import org.rhq.core.domain.alert.AlertDampening; import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.alert.AlertPriority; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.discovery.AvailabilityReport; import org.rhq.core.domain.measurement.Availability; @@ -45,6 +47,7 @@ import org.rhq.helpers.perftest.support.testng.DatabaseSetupInterceptor; import org.rhq.helpers.perftest.support.testng.DatabaseState; import org.rhq.helpers.perftest.support.testng.PerformanceReporting;
+import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @@ -74,13 +77,19 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest {
@BeforeMethod public void beforeMethod() { + Date now = new Date(); + System.out.println(">>>>> beforeMethod (AI Purge Test) === " + now.getTime()); try { this.availabilityManager = LookupUtil.getAvailabilityManager(); this.resourceManager = LookupUtil.getResourceManager(); this.agentManager = LookupUtil.getAgentManager(); this.systemManager = LookupUtil.getSystemManager(); this.alertDefinitionManager = LookupUtil.getAlertDefinitionManager(); - this.overlord = LookupUtil.getSubjectManager().getOverlord(); + /* + * NOTE: do not try to get Subjects in here, as they will only be available after + * this method has finished and the DatabaseSetupInterceptor has initialized the + * database. + */ } catch (Throwable t) { // Catch RuntimeExceptions and Errors and dump their stack trace, because Surefire will completely swallow them // and throw a cryptic NPE (see http://jira.codehaus.org/browse/SUREFIRE-157)! @@ -89,6 +98,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { } }
+ /** * Send availability reports to the server and measure timing. * For each resource, availability alternates for each report. @@ -98,6 +108,10 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { */ @DatabaseState(url = "perftest/AvailabilityInsertPurgeTest-testOne-data.xml.zip", dbVersion="2.94") public void testAlternating() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); + + Date now = new Date(); + System.out.println(">>>>>>> testAlternating (AI Purge Test) === " + now.getTime());
EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT r FROM Resource r"); @@ -172,6 +186,8 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { */ @DatabaseState(url = "perftest/AvailabilityInsertPurgeTest-testOne-data.xml.zip", dbVersion="2.94") public void testRandom() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); +
EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT r FROM Resource r"); @@ -240,6 +256,8 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { */ @DatabaseState(url = "perftest/AvailabilityInsertPurgeTest-testOne-data.xml.zip", dbVersion="2.94") public void testAlwaysUp() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); +
EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT r FROM Resource r"); @@ -311,6 +329,8 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { */ @DatabaseState(url = "perftest/AvailabilityInsertPurgeTest-testOne-data.xml.zip", dbVersion="2.94") public void testAlternatingWithAlert() throws Exception { + Subject overlord = LookupUtil.getSubjectManager().getOverlord(); +
EntityManager em = getEntityManager(); Query q = em.createQuery("SELECT r FROM Resource r"); @@ -335,6 +355,9 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { AlertDefinition def = new AlertDefinition(); def.addCondition(goingDown); def.setName("Test alert definition"); + def.setPriority(AlertPriority.MEDIUM); + def.setAlertDampening(new AlertDampening(AlertDampening.Category.NONE)); + def.setRecoveryId(0); alertDefinitionManager.createAlertDefinition(overlord,def,res.getId());
for (int MULTI : ROUNDS) { diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3PerformanceTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3PerformanceTest.java index 71adcb5..280db19 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3PerformanceTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3PerformanceTest.java @@ -26,8 +26,10 @@ import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod;
+import javax.persistence.EntityManager; import java.lang.reflect.Method; import java.util.Comparator; +import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -96,6 +98,9 @@ public class AbstractEJB3PerformanceTest extends AbstractEJB3Test {
@AfterMethod protected void reportTimings(ITestResult result, Method meth) { + Date now = new Date(); + System.out.println(">>> after " + meth.getName() + " (AbstraceEJB3PerformanceTest) === " + now.getTime()); + printTimings(meth.getName());
Class clazz = meth.getDeclaringClass(); @@ -124,7 +129,8 @@ public class AbstractEJB3PerformanceTest extends AbstractEJB3Test {
@BeforeMethod protected void setupTimings(Method meth) { - System.out.println(">>> " + meth.getName() + " ==="); + Date now = new Date(); + System.out.println(">>> before " + meth.getName() + " (AbstraceEJB3PerformanceTest) === " + now.getTime()); timings = new HashMap<String, Long>(); startTime = new HashMap<String, Long>();
diff --git a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/testng/DatabaseSetupInterceptor.java b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/testng/DatabaseSetupInterceptor.java index ce38a46..57cd217 100644 --- a/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/testng/DatabaseSetupInterceptor.java +++ b/modules/helpers/perftest-support/src/main/java/org/rhq/helpers/perftest/support/testng/DatabaseSetupInterceptor.java @@ -26,6 +26,7 @@ import java.io.InputStream; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; +import java.util.Date;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,18 +55,24 @@ import javax.naming.InitialContext; * </code> * * @author Lukas Krejci + * @author Heiko W. Rupp */ public class DatabaseSetupInterceptor implements IInvokedMethodListener {
private static final Log LOG = LogFactory.getLog(DatabaseSetupInterceptor.class);
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { + + DatabaseState state = getRequiredDatabaseState(method);
if (state == null) { return; }
+ Date now = new Date(); + System.out.println(">> beforeInvocation(DBInterceptor) " + method.getTestMethod().getMethodName() + " == " + now.getTime()); +
try { InputStreamProvider streamProvider = getInputStreamProvider(state.url(), state.storage(), method); @@ -112,7 +119,23 @@ public class DatabaseSetupInterceptor implements IInvokedMethodListener { }
public void afterInvocation(IInvokedMethod method, ITestResult testResult) { - //nothing to do + DatabaseState state = getRequiredDatabaseState(method); + + if (state == null) { + return; + } + + Date now = new Date(); + System.out.println(">> afterInvocation(DBInterceptor) == " + method.getTestMethod().getMethodName() + " === " + now.getTime()); //nothing to do + + try { + IDatabaseConnection connection = new DatabaseDataSourceConnection(new InitialContext(), + "java:/RHQDS"); + connection.getConnection().createStatement().execute("DROP TABLE RHQ_SUBJECT CASCADE"); + } catch (Exception e) { + System.err.println("== drop subject table failed: " + e.getMessage()); + } + }
private static DatabaseState getRequiredDatabaseState(IInvokedMethod method) {
commit b1865aee0517daa6fa7de2b7c7e9ee55710f27e9 Author: John Mazzitelli mazz@redhat.com Date: Tue Oct 12 00:10:57 2010 -0400
get the relative "start search from" drop down menu populated with the resource lineage types
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java index 28d2596..68c07f4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java @@ -41,6 +41,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; @@ -224,14 +225,16 @@ public class NewNotificationEditor extends LocatableDynamicForm { newCanvas = new SystemRolesNotificationSenderForm(newLocatorId, notificationToEdit, sender); } else if ("Resource Operations".equals(sender)) { ResourceType rt; + Resource res = null; if (alertDefinition.getResourceType() != null) { rt = alertDefinition.getResourceType(); } else if (alertDefinition.getResourceGroup() != null) { rt = alertDefinition.getResourceGroup().getResourceType(); } else { - rt = alertDefinition.getResource().getResourceType(); + res = alertDefinition.getResource(); + rt = res.getResourceType(); } - newCanvas = new ResourceOperationNotificationSenderForm(newLocatorId, notificationToEdit, sender, rt); + newCanvas = new ResourceOperationNotificationSenderForm(newLocatorId, notificationToEdit, sender, rt, res); } else { // catch all - all other senders are assumed to just have simple configuration definition // that can be used by our configuration editor UI component to ask for config values. diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java index f60cd9e..2519e6e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java @@ -23,6 +23,7 @@
package org.rhq.enterprise.gui.coregui.client.alert.definitions;
+import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Set; @@ -37,6 +38,7 @@ import com.smartgwt.client.widgets.form.fields.ButtonItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.TextItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; @@ -75,19 +77,23 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio private static final String OPERATION_DEFS_ATTRIBUTE = "operationDefinitions";
private final ResourceType resourceType; // the type representing the current resource or the current type being edited + private final Resource theResource; // if we are editing a resource instance, this is it - otherwise, will be null (for group/template alert defs)
private LocatableDynamicForm dynamicForm; private SelectItem modeSelectItem; private StaticTextItem singleResourceTextItem; private SelectItem ancestorTypeSelectItem; + private SelectItem descendantTypeSelectItem; + private TextItem descendantNameTextItem; private HLayout operationArgumentsCanvasItem; private SelectItem operationSelectItem;
public ResourceOperationNotificationSenderForm(String locatorId, AlertNotification notif, String sender, - ResourceType resourceType) { + ResourceType resourceType, Resource res) {
super(locatorId, notif, sender); this.resourceType = resourceType; + this.theResource = res; }
@Override @@ -156,9 +162,33 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio ancestorTypeSelectItem.setEndRow(true); ancestorTypeSelectItem.setWrapTitle(false); ancestorTypeSelectItem.setRedrawOnChange(true); - ancestorTypeSelectItem.setVisible(false); + ancestorTypeSelectItem.setDefaultToFirstOption(true); + ancestorTypeSelectItem.setHoverWidth(200); + ancestorTypeSelectItem + .setTooltip("Select the top of the type hierarchy from which to search its descedant tree for the Filter By type"); ancestorTypeSelectItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.RELATIVE));
+ descendantTypeSelectItem = new SelectItem("descendantTypeSelectItem", "Then Filter By"); + descendantTypeSelectItem.setStartRow(true); + descendantTypeSelectItem.setEndRow(false); + descendantTypeSelectItem.setWrapTitle(false); + descendantTypeSelectItem.setRedrawOnChange(true); + descendantTypeSelectItem.setDefaultToFirstOption(true); + descendantTypeSelectItem.setHoverWidth(200); + descendantTypeSelectItem + .setTooltip("The resource type to search for under the root type defined in the Start Search From selection."); + descendantTypeSelectItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.RELATIVE)); + + descendantNameTextItem = new TextItem("descendantNameTextItem"); + descendantNameTextItem.setStartRow(false); + descendantNameTextItem.setEndRow(true); + descendantNameTextItem.setShowTitle(false); + descendantNameTextItem.setRequired(false); + descendantNameTextItem + .setTooltip("A specific name to uniquely identify a resource when more than one resource of the selected type might exist. This is optional if there will only ever be one resource of the resource type in the selected type hierarchy."); + descendantNameTextItem.setHoverWidth(200); + descendantNameTextItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.RELATIVE)); + // the mode selector menu
modeSelectItem = new SelectItem("modeSelectItem", "Resource Selection Mode"); @@ -187,8 +217,12 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio break; } case RELATIVE: { - // TODO + ancestorTypeSelectItem.clearValue(); + descendantTypeSelectItem.clearValue(); + descendantNameTextItem.clearValue(); hideOperationDropDownMenu(); + populateRelativeAncestorDropDownMenu(null); + // TODO break; } } @@ -196,7 +230,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio });
dynamicForm.setFields(modeSelectItem, singleResourceTextItem, singleResourceButtonItem, ancestorTypeSelectItem, - operationSelectItem); + descendantTypeSelectItem, descendantNameTextItem, operationSelectItem);
addMember(dynamicForm); addMember(operationArgumentsCanvasItem); @@ -219,7 +253,12 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio break; } case RELATIVE: { + populateRelativeAncestorDropDownMenu(notifInfo.getAncestorTypeId()); // TODO + descendantTypeSelectItem.setValue(notifInfo.getDescendantTypeId()); + if (notifInfo.getDescendantName() != null) { + descendantNameTextItem.setValue(notifInfo.getDescendantName()); + } break; } } @@ -229,6 +268,39 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } }
+ private void populateRelativeAncestorDropDownMenu(final Integer selectedResourceTypeId) { + if (ancestorTypeSelectItem.getValue() == null) { + AsyncCallback<ArrayList<ResourceType>> callback = new AsyncCallback<ArrayList<ResourceType>>() { + @Override + public void onSuccess(ArrayList<ResourceType> results) { + LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(results.size()); + for (ResourceType rt : results) { + map.put(String.valueOf(rt.getId()), rt.getName()); + } + ancestorTypeSelectItem.setValueMap(map); + if (selectedResourceTypeId != null) { + ancestorTypeSelectItem.setValue(selectedResourceTypeId.toString()); + } else { + ancestorTypeSelectItem.setValue(String.valueOf(results.get(0).getId())); + } + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot get type ancestry", caught); + } + }; + + if (this.theResource != null) { + GWTServiceLookup.getResourceTypeGWTService().getResourceTypesForResourceAncestors( + this.theResource.getId(), callback); + } else { + GWTServiceLookup.getResourceTypeGWTService().getAllResourceTypeAncestors(this.resourceType.getId(), + callback); + } + } + } + /** * This assumes the user or our code selected a specific operation from the drop down list. * This will show the operation arguments as appropriate for the selected operation. @@ -439,6 +511,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio // now fill in the configuration object with the information based on what was selected String selectedModeString = modeSelectItem.getValue().toString(); ResourceSelectionMode selectedMode = ResourceSelectionMode.valueOf(selectedModeString); + cleanConfiguration(); // erase anything previously in here Configuration config = getConfiguration(); config.put(new PropertySimple(ResourceOperationNotificationInfo.Constants.SELECTION_MODE .getPropertyName(), selectedMode)); @@ -454,7 +527,18 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio break; } case RELATIVE: { - // TODO + config.put(new PropertySimple(ResourceOperationNotificationInfo.Constants.RELATIVE_ANCESTOR_TYPE_ID + .getPropertyName(), ancestorTypeSelectItem.getValue())); + config.put(new PropertySimple( + ResourceOperationNotificationInfo.Constants.RELATIVE_DESCENDANT_TYPE_ID.getPropertyName(), + descendantTypeSelectItem.getValue())); + // descendant name is optional - only populate a non-null property + Object descandentNameString = descendantNameTextItem.getValue(); + if (descandentNameString != null && descandentNameString.toString().trim().length() > 0) { + config.put(new PropertySimple( + ResourceOperationNotificationInfo.Constants.RELATIVE_DESCENDANT_NAME.getPropertyName(), + descandentNameString)); + } break; } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java index 89255e4..2b2bd45 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceTypeGWTService.java @@ -1,20 +1,22 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
-import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.RawConfiguration; -import org.rhq.core.domain.criteria.ResourceTypeCriteria; -import org.rhq.core.domain.resource.ResourceType; -import org.rhq.core.domain.util.PageList; +import java.util.ArrayList;
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
+import org.rhq.core.domain.criteria.ResourceTypeCriteria; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.util.PageList; + @RemoteServiceRelativePath("ResourceTypeGWTService") public interface ResourceTypeGWTService extends RemoteService {
PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria);
- RawConfiguration dummy(RawConfiguration config); + ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId);
+ ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId);
+ ArrayList<ResourceType> getResourceTypeDescendantsWithOperations(int resourceTypeId); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java index 4d6706c..e99d65d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceTypeGWTServiceImpl.java @@ -1,12 +1,16 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
-import org.rhq.core.domain.configuration.RawConfiguration; +import java.util.ArrayList; +import java.util.List; + import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ResourceTypeGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; +import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
@@ -14,6 +18,7 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement
private static final long serialVersionUID = 1L;
+ @Override public PageList<ResourceType> findResourceTypesByCriteria(ResourceTypeCriteria criteria) { try { ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); @@ -25,8 +30,46 @@ public class ResourceTypeGWTServiceImpl extends AbstractGWTServiceImpl implement } }
- public RawConfiguration dummy(RawConfiguration config) { - com.allen_sauer.gwt.log.client.Log.info(config.getPath()); - return new RawConfiguration(); + /** + * Given a resource ID, this gets all resource types for all ancestors in that resource's lineage. + */ + @Override + public ArrayList<ResourceType> getResourceTypesForResourceAncestors(int resourceId) { + try { + ResourceManagerLocal manager = LookupUtil.getResourceManager(); + List<ResourceLineageComposite> lineage = manager.getResourceLineage(getSessionSubject(), resourceId); + ArrayList<ResourceType> types = new ArrayList<ResourceType>(lineage.size()); + for (ResourceLineageComposite composite : lineage) { + types.add(composite.getResource().getResourceType()); + } + return SerialUtility.prepare(types, "ResourceTypes.getResourceTypesForResourceAncestors"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + @Override + public ArrayList<ResourceType> getAllResourceTypeAncestors(int resourceTypeId) { + try { + ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); + List<ResourceType> list = typeManager.getAllResourceTypeAncestors(getSessionSubject(), resourceTypeId); + return SerialUtility + .prepare(new ArrayList<ResourceType>(list), "ResourceTypes.getAllResourceTypeAncestors"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + @Override + public ArrayList<ResourceType> getResourceTypeDescendantsWithOperations(int resourceTypeId) { + try { + ResourceTypeManagerLocal typeManager = LookupUtil.getResourceTypeManager(); + List<ResourceType> list = typeManager.getResourceTypeDescendantsWithOperations(getSessionSubject(), + resourceTypeId); + return SerialUtility.prepare(new ArrayList<ResourceType>(list), + "ResourceTypes.getResourceTypeDescendantsWithOperations"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } } \ No newline at end of file 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 379c69d..0c7198a 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 @@ -798,6 +798,25 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage return result; }
+ public List<ResourceLineageComposite> getResourceLineage(Subject subject, int resourceId) { + boolean isInventoryManager = authorizationManager.isInventoryManager(subject); + + // get the raw resource lineage up to the platform. We'll check the auth below + List<Resource> rawLineage = getResourceLineage(resourceId); + + // record which of the raw ancestry is locked from view + List<ResourceLineageComposite> resourceLineage = new ArrayList<ResourceLineageComposite>(rawLineage.size()); + for (Resource resource : rawLineage) { + boolean isLocked = false; + if (!isInventoryManager) { + isLocked = !authorizationManager.canViewResource(subject, resource.getId()); + } + resourceLineage.add(new ResourceLineageComposite(resource, isLocked)); + } + + return resourceLineage; + } + @NotNull public Resource getRootResourceForResource(int resourceId) { Query q = entityManager.createNamedQuery(Resource.QUERY_FIND_ROOT_PLATFORM_OF_RESOURCE); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java index a94bcc4..0dccf06 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java @@ -156,6 +156,15 @@ public interface ResourceManagerLocal { List<Resource> getResourceLineage(int resourceId);
/** + * Returns the direct lineage of a resource up to the top most resource in the hierarchy. + * Composites are returned that indicate whether the resource is viewable or not by the user. + * + * @param resourceId id of resource + * @return resource lineage + */ + List<ResourceLineageComposite> getResourceLineage(Subject subject, int resourceId); + + /** * Returns the lineage of a resource plus all the siblings of the resources in the lineage. This is * useful for prepopulating all the resources visible in an expanded tree. Composites are returned * that indicate whether the resource is viewable or should be locked in the tree. 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 a2a6ece..9dc348c 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 @@ -415,8 +415,6 @@ public class ResourceTypeManagerBean implements ResourceTypeManagerLocal, Resour @SuppressWarnings("unchecked") public PageList<ResourceType> findResourceTypesByCriteria(Subject subject, ResourceTypeCriteria criteria) { CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; - CriteriaQueryRunner<ResourceType> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); return queryRunner.execute(); } @@ -428,12 +426,6 @@ public class ResourceTypeManagerBean implements ResourceTypeManagerLocal, Resour return results; }
- public List<ResourceType> getResourceTypeAncestorsWithOperations(Subject subject, int resourceTypeId) { - List<ResourceType> types = getAllResourceTypeAncestors(subject, resourceTypeId); - List<ResourceType> results = excludeThoseWithoutOperations(types); - return results; - } - public List<ResourceType> getResourceTypeDescendantsWithOperations(Subject subject, int resourceTypeId) { List<ResourceType> types = getAllResourceTypeDescendants(subject, resourceTypeId); List<ResourceType> results = excludeThoseWithoutOperations(types); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java index 709f9f0..6cd3639 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceTypeManagerLocal.java @@ -133,8 +133,6 @@ public interface ResourceTypeManagerLocal {
ResourceType getResourceTypeByNameAndPlugin(Subject subject, String name, String plugin);
- List<ResourceType> getResourceTypeAncestorsWithOperations(Subject subject, int resourceTypeId); - List<ResourceType> getResourceTypeDescendantsWithOperations(Subject subject, int resourceTypeId);
List<ResourceType> getAllResourceTypeAncestors(Subject subject, int resourceTypeId); diff --git a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java index 1552256..2d85548 100644 --- a/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java +++ b/modules/enterprise/server/plugins/alert-operations/src/main/java/org/rhq/enterprise/server/plugins/alertOperations/OperationsBackingBean.java @@ -109,7 +109,9 @@ public class OperationsBackingBean extends CustomAlertSenderBackingBean { }
if (ancestors == null) { // if not in the resource content or fallback if resource ancestry loading bombs - ancestors = LookupUtil.getResourceTypeManager().getResourceTypeAncestorsWithOperations(getOverlord(), + // mazz was here - I replaced getResourceTypeAcestorsWithOperations - this entire backing bean + // will be deleted soon, so we don't care - i just needed to get this to compile again + ancestors = LookupUtil.getResourceTypeManager().getAllResourceTypeAncestors(getOverlord(), contextType.getId()); } load(ancestorTypeOptions, ancestors);
commit 1f713565d0b0e03aa9347138bab1ec08fb8602a6 Author: John Mazzitelli mazz@redhat.com Date: Mon Oct 11 13:46:14 2010 -0400
properly validate the specific resource picker form item
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java index 3fda778..f60cd9e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java @@ -317,6 +317,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio hideOperationArguments(); selectOperation(Integer.valueOf(operationSelectItem.getValue().toString())); } + singleResourceTextItem.validate(); // makes sure a resource with ops is selected otherwise a validation error shows operationSelectItem.show(); markForRedraw(); } else { @@ -373,6 +374,8 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio operationSelectItem.setValueMap(valueMap); operationSelectItem.hide(); hideOperationArguments(); + + singleResourceTextItem.validate(); // makes sure a resource with ops is selected otherwise a validation error shows }
private void hideOperationArguments() { @@ -485,18 +488,26 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio }
private class ResourceIdValidator extends CustomValidator { - private final StaticTextItem idTextItem; + private final FormItem idItem;
- public ResourceIdValidator(StaticTextItem idTextItem) { - this.idTextItem = idTextItem; + public ResourceIdValidator(FormItem idItem) { + this.idItem = idItem; }
+ @SuppressWarnings("unchecked") @Override protected boolean condition(Object value) { - Integer id = Integer.valueOf(idTextItem.getAttributeAsInt(RESOURCE_ID_ATTRIBUTE)); + Integer id = Integer.valueOf(idItem.getAttributeAsInt(RESOURCE_ID_ATTRIBUTE)); boolean valid = (id != null && id.intValue() != 0); if (!valid) { setErrorMessage("Please pick a resource"); + } else { + LinkedHashMap<Integer, OperationDefinition> ops = (LinkedHashMap<Integer, OperationDefinition>) operationSelectItem + .getAttributeAsObject(OPERATION_DEFS_ATTRIBUTE); + if (ops == null || ops.isEmpty()) { + valid = false; + setErrorMessage("Please pick a resource that has one or more operations"); + } } return valid; }
commit 9fbab172a12b874d13ba56d21c1dcf8d4fff834c Author: John Mazzitelli mazz@redhat.com Date: Mon Oct 11 13:45:47 2010 -0400
disable row selections if the disable override is set
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 c573007..fe69ec7 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 @@ -195,7 +195,7 @@ public class Table extends LocatableHLayout implements RefreshableView { listGrid.setHeight100(); listGrid.setAlternateRecordStyles(true); listGrid.setResizeFieldsInRealTime(false); - listGrid.setSelectionType(SelectionStyle.SIMPLE); + listGrid.setSelectionType(getDefaultSelectionStyle());
if (flexRowDisplay) { listGrid.setAutoFitData(Autofit.HORIZONTAL); @@ -224,6 +224,10 @@ public class Table extends LocatableHLayout implements RefreshableView { contents.addMember(listGrid); }
+ protected SelectionStyle getDefaultSelectionStyle() { + return SelectionStyle.SIMPLE; + } + @Override protected void onDraw() { try { @@ -539,6 +543,12 @@ public class Table extends LocatableHLayout implements RefreshableView {
protected void refreshTableInfo() { if (showFooter) { + if (this.tableActionDisableOverride) { + this.listGrid.setSelectionType(SelectionStyle.NONE); + } else { + this.listGrid.setSelectionType(getDefaultSelectionStyle()); + } + int count = this.listGrid.getSelection().length; for (TableActionInfo tableAction : tableActions) { if (tableAction.actionButton != null) { // if null, we haven't initialized our buttons yet, so skip this
commit b2952714eca5432433a41ef8b934a5663008fbf8 Author: John Mazzitelli mazz@redhat.com Date: Mon Oct 11 12:54:07 2010 -0400
saves resource operation notif defs for SELF and SPECIFIC.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java index 0dabe26..5b68ee4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java @@ -87,6 +87,10 @@ public abstract class AbstractNotificationSenderForm extends LocatableVLayout { this.configuration = configuration; }
+ public void cleanConfiguration() { + this.configuration.getMap().clear(); + } + /** * The {@link AlertNotification#getExtraConfiguration()} for the new alert definition notification. * @@ -100,5 +104,11 @@ public abstract class AbstractNotificationSenderForm extends LocatableVLayout { this.extraConfiguration = extraConfiguration; }
+ public void cleanExtraConfiguration() { + if (this.extraConfiguration != null) { + this.extraConfiguration.getMap().clear(); + } + } + public abstract boolean validate(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java index cd50d2c..3fda778 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java @@ -28,12 +28,12 @@ import java.util.LinkedHashMap; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.Label; 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.CanvasItem; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; @@ -41,9 +41,12 @@ import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.form.fields.events.ClickEvent; import com.smartgwt.client.widgets.form.fields.events.ClickHandler; +import com.smartgwt.client.widgets.form.validator.CustomValidator; +import com.smartgwt.client.widgets.layout.HLayout;
import org.rhq.core.domain.alert.notification.AlertNotification; import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.criteria.ResourceTypeCriteria; @@ -58,6 +61,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.SingleResourcePicker; import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourcePicker.OkHandler; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
/** * This notification form will be used for the Resource Operation sender. This form lets @@ -73,9 +77,10 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio private final ResourceType resourceType; // the type representing the current resource or the current type being edited
private LocatableDynamicForm dynamicForm; + private SelectItem modeSelectItem; private StaticTextItem singleResourceTextItem; private SelectItem ancestorTypeSelectItem; - private CanvasItem operationArgumentsCanvasItem; + private HLayout operationArgumentsCanvasItem; private SelectItem operationSelectItem;
public ResourceOperationNotificationSenderForm(String locatorId, AlertNotification notif, String sender, @@ -92,14 +97,10 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio dynamicForm = new LocatableDynamicForm(extendLocatorId("resOpForm")); dynamicForm.setNumCols(3);
- operationArgumentsCanvasItem = new CanvasItem(); - operationArgumentsCanvasItem.setStartRow(true); - operationArgumentsCanvasItem.setEndRow(true); - operationArgumentsCanvasItem.setShowTitle(false); - operationArgumentsCanvasItem.setColSpan(3); - operationArgumentsCanvasItem.setCanvas(new Label()); - operationArgumentsCanvasItem.setWidth("*"); - operationArgumentsCanvasItem.setVisible(false); + operationArgumentsCanvasItem = new LocatableHLayout(extendLocatorId("opArgLayout")); + operationArgumentsCanvasItem.setOverflow(Overflow.VISIBLE); + operationArgumentsCanvasItem.setHeight(400); + operationArgumentsCanvasItem.setWidth(500);
operationSelectItem = new SelectItem("operationSelectItem", "Operation"); operationSelectItem.setStartRow(true); @@ -124,6 +125,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio singleResourceTextItem.setValue("Pick a resource..."); singleResourceTextItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.SPECIFIC)); singleResourceTextItem.setAttribute(RESOURCE_ID_ATTRIBUTE, 0); // we hide the resource ID in this attribute + singleResourceTextItem.setValidators(new ResourceIdValidator(singleResourceTextItem));
ButtonItem singleResourceButtonItem = new ButtonItem("singleResourceButtonItem", "Pick"); singleResourceButtonItem.setStartRow(false); @@ -159,7 +161,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio
// the mode selector menu
- SelectItem modeSelectItem = new SelectItem("modeSelectItem", "Resource Selection Mode"); + modeSelectItem = new SelectItem("modeSelectItem", "Resource Selection Mode"); modeSelectItem.setStartRow(true); modeSelectItem.setEndRow(true); modeSelectItem.setWrapTitle(false); @@ -194,9 +196,10 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio });
dynamicForm.setFields(modeSelectItem, singleResourceTextItem, singleResourceButtonItem, ancestorTypeSelectItem, - operationSelectItem, operationArgumentsCanvasItem); + operationSelectItem);
addMember(dynamicForm); + addMember(operationArgumentsCanvasItem);
// prepopulate the form ResourceOperationNotificationInfo notifInfo; @@ -222,7 +225,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } } else { modeSelectItem.setValue(ResourceSelectionMode.SELF.name()); - setOperationDropDownMenuValues(resourceType.getId(), null, getExtraConfiguration()); + setOperationDropDownMenuValues(resourceType.getId(), null, null); } }
@@ -255,16 +258,16 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio ConfigurationDefinition paramDef = def.getParametersConfigurationDefinition(); if (paramDef != null) { Configuration extraConfig = getExtraConfiguration(); - if (extraConfig != null) { - extraConfig.getMap().clear(); // changing the op, the old props are no longer valid - } else { + if (extraConfig == null) { extraConfig = new Configuration(); setExtraConfiguration(extraConfig); + } else { + cleanExtraConfiguration(); } showOperationArguments(paramDef, extraConfig); } else { - setExtraConfiguration(null); - hideOperationArguments(); + cleanExtraConfiguration(); + showOperationArguments(null, null); } } else { hideOperationDropDownMenu(); @@ -306,7 +309,7 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio } operationSelectItem.setAttribute(OPERATION_DEFS_ATTRIBUTE, (Object) opDefs); operationSelectItem.setValueMap(valueMap); - if (opId != null && opId > 0 && valueMap.containsKey(opId)) { + if (opId != null && opId > 0 && opDefs.containsKey(opId)) { operationSelectItem.setValue(String.valueOf(opId)); showOperationArguments(opDefs.get(opId).getParametersConfigurationDefinition(), args); } else { @@ -373,39 +376,95 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio }
private void hideOperationArguments() { - Canvas canvas = operationArgumentsCanvasItem.getCanvas(); - if (canvas != null) { - canvas.destroy(); + Canvas[] canvii = operationArgumentsCanvasItem.getMembers(); + if (canvii != null) { + for (Canvas canvas : canvii) { + canvas.destroy(); + } } - - operationArgumentsCanvasItem.setCanvas(new Label("")); - operationArgumentsCanvasItem.hide(); markForRedraw(); }
private void showOperationArguments(ConfigurationDefinition def, Configuration config) { - Canvas canvas = operationArgumentsCanvasItem.getCanvas(); - if (canvas != null) { - canvas.destroy(); + Canvas[] canvii = operationArgumentsCanvasItem.getMembers(); + if (canvii != null) { + for (Canvas canvas : canvii) { + canvas.destroy(); + } }
if (def != null) { - canvas = new ConfigurationEditor(extendLocatorId("opArgs"), def, config); + ConfigurationEditor configEditor = new ConfigurationEditor(extendLocatorId("opArgs"), def, config); + operationArgumentsCanvasItem.addMember(configEditor); } else { Label l = new Label("This operation does not take any parameters"); l.setWrap(false); - canvas = l; + operationArgumentsCanvasItem.addMember(l); }
- operationArgumentsCanvasItem.setCanvas(canvas); - operationArgumentsCanvasItem.show(); markForRedraw(); }
+ private ConfigurationEditor getConfigurationEditor() { + Canvas[] canvii = operationArgumentsCanvasItem.getMembers(); + if (canvii != null) { + for (Canvas canvas : canvii) { + if (canvas instanceof ConfigurationEditor) { + return (ConfigurationEditor) canvas; + } + } + } + return null; + } + @Override public boolean validate() { try { - return true; + if (dynamicForm.validate(false)) { + // let's make sure the args can be validated successfully. + // If there is no config editor, there are no parameters for this operation + ConfigurationEditor configEditor = getConfigurationEditor(); + if (configEditor != null) { + if (!configEditor.validate()) { + return false; + } + // nothing else to store - our config editor directly edited our extraConfig already + } else { + setExtraConfiguration(null); + } + + // now fill in the configuration object with the information based on what was selected + String selectedModeString = modeSelectItem.getValue().toString(); + ResourceSelectionMode selectedMode = ResourceSelectionMode.valueOf(selectedModeString); + Configuration config = getConfiguration(); + config.put(new PropertySimple(ResourceOperationNotificationInfo.Constants.SELECTION_MODE + .getPropertyName(), selectedMode)); + switch (selectedMode) { + case SELF: { + // nothing extra needs to be done + break; + } + case SPECIFIC: { + int resourceId = singleResourceTextItem.getAttributeAsInt(RESOURCE_ID_ATTRIBUTE); + config.put(new PropertySimple(ResourceOperationNotificationInfo.Constants.SPECIFIC_RESOURCE_ID + .getPropertyName(), resourceId)); + break; + } + case RELATIVE: { + // TODO + break; + } + } + + // indicate which operation is to be invoked by storing the op ID in the config + String operationId = operationSelectItem.getValue().toString(); + config.put(new PropertySimple(ResourceOperationNotificationInfo.Constants.OPERATION_ID + .getPropertyName(), operationId)); + + return true; + } else { + return false; + } } catch (Exception e) { CoreGUI.getErrorHandler().handleError("Cannot save the notification configuration", e); return false; @@ -424,4 +483,22 @@ public class ResourceOperationNotificationSenderForm extends AbstractNotificatio return mode.name().equals(modeTypeString); } } + + private class ResourceIdValidator extends CustomValidator { + private final StaticTextItem idTextItem; + + public ResourceIdValidator(StaticTextItem idTextItem) { + this.idTextItem = idTextItem; + } + + @Override + protected boolean condition(Object value) { + Integer id = Integer.valueOf(idTextItem.getAttributeAsInt(RESOURCE_ID_ATTRIBUTE)); + boolean valid = (id != null && id.intValue() != 0); + if (!valid) { + setErrorMessage("Please pick a resource"); + } + return valid; + } + } }
commit fb9f00c1a46cde26b4845a1c9e2c5cc8b55958cc Merge: faaf03d... 769d8fe... Author: John Sanda jsanda@redhat.com Date: Sun Oct 10 13:17:46 2010 -0400
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 769d8fe3e1c2edfce9f0f41a25a50ecc77c302ba Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 11:51:59 2010 -0400
add children/descendent availability columns to the group inventory view
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java index 583fe36..cae33a9 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/composite/ResourceGroupComposite.java @@ -61,6 +61,15 @@ public class ResourceGroupComposite implements Serializable { public ResourceGroupComposite() { }
+ public ResourceGroupComposite(Long explicitUp, Long explicitDown, Long implicitUp, Long implicitDown, + ResourceGroup resourceGroup) { + this(explicitUp + explicitDown, // + (double) explicitUp / (explicitUp + explicitDown), // + implicitUp + implicitDown, // + (double) implicitUp / (implicitUp + implicitDown), // + resourceGroup, null); + } + public ResourceGroupComposite(Long explicitCount, Double explicitAvailability, Long implicitCount, Double implicitAvailability, ResourceGroup resourceGroup) { this(explicitCount, explicitAvailability, implicitCount, implicitAvailability, resourceGroup, null); 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 new file mode 100644 index 0000000..0da1963 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupCompositeDataSource.java @@ -0,0 +1,161 @@ +/* + * 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.inventory.groups; + +import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.CATEGORY; +import static org.rhq.enterprise.gui.coregui.client.inventory.groups.ResourceGroupDataSourceField.NAME; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.fields.DataSourceTextField; +import com.smartgwt.client.rpc.RPCResponse; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.criteria.ResourceGroupCriteria; +import org.rhq.core.domain.resource.ResourceType; +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.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.ResourceGroupGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * @author Joseph Marques + */ +public class ResourceGroupCompositeDataSource extends RPCDataSource<ResourceGroupComposite> { + + ResourceGroupGWTServiceAsync groupService = GWTServiceLookup.getResourceGroupService(); + + private static ResourceGroupCompositeDataSource INSTANCE; + + public static ResourceGroupCompositeDataSource getInstance() { + if (INSTANCE == null) { + INSTANCE = new ResourceGroupCompositeDataSource(); + } + return INSTANCE; + } + + public ResourceGroupCompositeDataSource() { + super(); + + DataSourceTextField nameDataField = new DataSourceTextField("name", "Name", 200); + nameDataField.setCanEdit(false); + + DataSourceTextField descriptionDataField = new DataSourceTextField("description", "Description"); + descriptionDataField.setCanEdit(false); + + DataSourceTextField typeNameDataField = new DataSourceTextField("typeName", "Type"); + DataSourceTextField pluginNameDataField = new DataSourceTextField("pluginName", "Plugin"); + DataSourceTextField categoryDataField = new DataSourceTextField("category", "Category"); + + setFields(nameDataField, descriptionDataField, typeNameDataField, pluginNameDataField, categoryDataField); + } + + public void executeFetch(final DSRequest request, final DSResponse response) { + ResourceGroupCriteria criteria = getFetchCriteria(request); + + groupService.findResourceGroupCompositesByCriteria(criteria, + new AsyncCallback<PageList<ResourceGroupComposite>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch group composite data", caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + + public void onSuccess(PageList<ResourceGroupComposite> result) { + response.setData(buildRecords(result)); + response.setTotalRows(result.getTotalSize()); // for paging to work we have to specify size of full result set + processResponse(request.getRequestId(), response); + } + }); + } + + protected ResourceGroupCriteria getFetchCriteria(final DSRequest request) { + ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.setPageControl(getPageControl(request)); + + criteria.addFilterName(getFilter(request, NAME.propertyName(), String.class)); + criteria.addFilterGroupCategory(getFilter(request, CATEGORY.propertyName(), GroupCategory.class)); + criteria.addFilterDownMemberCount(getFilter(request, "downMemberCount", Integer.class)); + criteria.addFilterExplicitResourceIds(getFilter(request, "explicitResourceId", Integer.class)); + criteria.addFilterGroupDefinitionId(getFilter(request, "groupDefinitionId", Integer.class)); + + return criteria; + } + + @Override + public ResourceGroupComposite copyValues(ListGridRecord from) { + Integer idAttrib = from.getAttributeAsInt("id"); + String nameAttrib = from.getAttribute("name"); + String descriptionAttrib = from.getAttribute("description"); + String typeNameAttrib = from.getAttribute("typeName"); + String pluginNameAttrib = from.getAttribute("pluginName"); + ResourceType rt = null; + + ResourceGroup rg = new ResourceGroup(nameAttrib); + rg.setId(idAttrib); + rg.setDescription(descriptionAttrib); + if (null != typeNameAttrib) { + rt = new ResourceType(); + rt.setName(typeNameAttrib); + rt.setPlugin(pluginNameAttrib); + rg.setResourceType(rt); + } + + Long explicitUp = Long.valueOf(from.getAttribute("explicitUp")); + Long explicitDown = Long.valueOf(from.getAttribute("explicitDown")); + Long implicitUp = Long.valueOf(from.getAttribute("implicitUp")); + Long implicitDown = Long.valueOf(from.getAttribute("implicitDown")); + + ResourceGroupComposite composite = new ResourceGroupComposite(explicitUp, explicitDown, implicitUp, + implicitDown, rg); + + return composite; + } + + @Override + public ListGridRecord copyValues(ResourceGroupComposite from) { + ListGridRecord record = new ListGridRecord(); + record.setAttribute("group", from); + record.setAttribute("id", from.getResourceGroup().getId()); + record.setAttribute("name", from.getResourceGroup().getName()); + record.setAttribute("description", from.getResourceGroup().getDescription()); + record.setAttribute("category", from.getResourceGroup().getGroupCategory().toString()); + + record.setAttribute("explicitUp", String.valueOf(from.getExplicitUp())); + record.setAttribute("explicitDown", String.valueOf(from.getExplicitDown())); + record.setAttribute("implicitUp", String.valueOf(from.getImplicitUp())); + record.setAttribute("implicitDown", String.valueOf(from.getImplicitDown())); + + record.setAttribute("availabilityChildren", from.getExplicitFormatted()); + record.setAttribute("availabilityDescendents", from.getImplicitFormatted()); + + if (from.getResourceGroup().getResourceType() != null) { + record.setAttribute("resourceType", from.getResourceGroup().getResourceType()); + record.setAttribute("typeName", from.getResourceGroup().getResourceType().getName()); + record.setAttribute("pluginName", from.getResourceGroup().getResourceType().getPlugin()); + } + + return record; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java index 6c64b16..6aa4e65 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java @@ -21,8 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -38,6 +36,7 @@ import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class ResourceGroupListView extends Table {
@@ -58,15 +57,13 @@ public class ResourceGroupListView extends Table { addHeaderIcon(headerIcon); }
- final ResourceGroupsDataSource datasource = ResourceGroupsDataSource.getInstance(); + final ResourceGroupCompositeDataSource datasource = ResourceGroupCompositeDataSource.getInstance(); setDataSource(datasource); }
@Override protected void configureTable() { - ListGridField idField = new ListGridField("id", "Id", 55); - idField.setType(ListGridFieldType.INTEGER); - ListGridField nameField = new ListGridField("name", "Name", 250); + ListGridField nameField = new ListGridField("name", "Name", 300); nameField.setCellFormatter(new CellFormatter() { public String format(Object o, ListGridRecord listGridRecord, int i, int i1) { return "<a href="#ResourceGroup/" + listGridRecord.getAttribute("id") + "">" + o + "</a>"; @@ -76,13 +73,18 @@ public class ResourceGroupListView extends Table { ListGridField descriptionField = new ListGridField("description", "Description"); ListGridField typeNameField = new ListGridField("typeName", "Type", 130); ListGridField pluginNameField = new ListGridField("pluginName", "Plugin", 100); - ListGridField categoryField = new ListGridField("category", "Category", 60); + ListGridField categoryField = new ListGridField("category", "Category", 100);
- ListGridField availabilityField = new ListGridField("currentAvailability", "Availability", 55); + ListGridField availabilityChildrenField = new ListGridField("availabilityChildren", "Children", 100); + availabilityChildrenField.setWrap(false); + availabilityChildrenField.setAlign(Alignment.CENTER);
- availabilityField.setAlign(Alignment.CENTER); - getListGrid().setFields(idField, nameField, descriptionField, typeNameField, pluginNameField, categoryField, - availabilityField); + ListGridField availabilityDescendentsField = new ListGridField("availabilityDescendents", "Descendents", 100); + availabilityDescendentsField.setWrap(false); + availabilityDescendentsField.setAlign(Alignment.CENTER); + + getListGrid().setFields(nameField, descriptionField, typeNameField, pluginNameField, categoryField, + availabilityChildrenField, availabilityDescendentsField);
addTableAction(extendLocatorId("Delete"), "Delete", Table.SelectionEnablement.ANY, "Delete the selected resource groups?", new TableAction() {
commit 3124bc9233f13c9c3f239f0eb6ced1af86d1c26b Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 11:51:12 2010 -0400
move listGrid.setSelectType(SelectionType.SIMPLE) to the Table component
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java index d97ccf9..e14f383 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundlesListView.java @@ -21,7 +21,6 @@ package org.rhq.enterprise.gui.coregui.client.bundle.list; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.bundle.Bundle; @@ -55,7 +54,6 @@ public class BundlesListView extends Table {
@Override protected void configureTable() { - getListGrid().getField("id").setWidth("60"); getListGrid().getField("link").setWidth("25%"); getListGrid().getField("link").setType(ListGridFieldType.LINK); @@ -71,9 +69,6 @@ public class BundlesListView extends Table { getListGrid().getField("latestVersion").setWidth("25%"); getListGrid().getField("versionsCount").setWidth("*");
- getListGrid().setSelectionType(SelectionStyle.SIMPLE); - // getListGrid().setSelectionAppearance(SelectionAppearance.CHECKBOX); - addTableAction(extendLocatorId("New"), "New", Table.SelectionEnablement.ALWAYS, null, new TableAction() { public void executeAction(ListGridRecord[] selection) { new BundleCreateWizard().startBundleWizard(); 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 917946a..c573007 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 @@ -25,6 +25,7 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.SortSpecifier; import com.smartgwt.client.types.Autofit; import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; @@ -194,6 +195,7 @@ public class Table extends LocatableHLayout implements RefreshableView { listGrid.setHeight100(); listGrid.setAlternateRecordStyles(true); listGrid.setResizeFieldsInRealTime(false); + listGrid.setSelectionType(SelectionStyle.SIMPLE);
if (flexRowDisplay) { listGrid.setAutoFitData(Autofit.HORIZONTAL); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java index 7053f7c..6c64b16 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/ResourceGroupListView.java @@ -64,13 +64,6 @@ public class ResourceGroupListView extends Table {
@Override protected void configureTable() { - - // setHeaderIcon("?_24.png"); - - getListGrid().setSelectionType(SelectionStyle.SIMPLE); - //table.getListGrid().setSelectionAppearance(SelectionAppearance.CHECKBOX); - getListGrid().setResizeFieldsInRealTime(true); - ListGridField idField = new ListGridField("id", "Id", 55); idField.setType(ListGridFieldType.INTEGER); ListGridField nameField = new ListGridField("name", "Name", 250); 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 6382fcb..eb7175b 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 @@ -33,7 +33,6 @@ import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.SortSpecifier; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; @@ -104,9 +103,6 @@ public class ResourceSearchView extends Table {
@Override protected void configureTable() { - - getListGrid().setSelectionType(SelectionStyle.SIMPLE); - ListGridField idField = new ListGridField("id", "Id", 55); idField.setType(ListGridFieldType.INTEGER); ListGridField iconField = new ListGridField("icon", "", 40);
commit 4423882e067f922081b793c11a99e2a1b6fd3e59 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 11 10:04:08 2010 -0400
Add some null protection
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java index 37ec2c9..6359a23 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java @@ -515,7 +515,7 @@ public class SubjectManagerBean implements SubjectManagerLocal, SubjectManagerRe
// one more thing, delete any owned groups List<ResourceGroup> ownedGroups = doomedSubject.getOwnedGroups(); - if (!ownedGroups.isEmpty()) { + if (null != ownedGroups && !ownedGroups.isEmpty()) { int size = ownedGroups.size(); int[] ownedGroupIds = new int[size]; for (int i = 0; (i < size); ++i) { 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 6f4d21e..379c69d 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 @@ -402,7 +402,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage
// one more thing, delete any autogroup backing groups List<ResourceGroup> backingGroups = attachedResource.getAutoGroupBackingGroups(); - if (!backingGroups.isEmpty()) { + if (null != backingGroups && !backingGroups.isEmpty()) { int size = backingGroups.size(); int[] backingGroupIds = new int[size]; for (int i = 0; (i < size); ++i) {
commit f12e3ffb41ee4cbe8c65983ca485390db199b5db Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 02:28:27 2010 -0400
delete test method for finder method that was removed
diff --git a/modules/enterprise/remoting/webservices/src/test/java/org/rhq/enterprise/server/ws/WsResourceManagerTest.java b/modules/enterprise/remoting/webservices/src/test/java/org/rhq/enterprise/server/ws/WsResourceManagerTest.java index bb79117..42cbb21 100644 --- a/modules/enterprise/remoting/webservices/src/test/java/org/rhq/enterprise/server/ws/WsResourceManagerTest.java +++ b/modules/enterprise/remoting/webservices/src/test/java/org/rhq/enterprise/server/ws/WsResourceManagerTest.java @@ -87,22 +87,6 @@ public class WsResourceManagerTest extends AssertJUnit implements TestProperties
}
- @Test(enabled = TESTS_ENABLED) - public void testResourceComposites() throws java.lang.Exception { - ResourceCategory category = ResourceCategory.SERVER; - - String typeName = "RHQ AGENT"; - int parentResourceId = -1; - String searchString = null; - PageControl pageControl = WS_OBJECT_FACTORY.createPageControl(); - - List<ResourceComposite> resourceComposites = WEBSERVICE_REMOTE.findResourceComposites(subject, category, - typeName, parentResourceId, searchString, pageControl); - assertNotNull("ResourceComposite is null.", resourceComposites); - assertTrue("No resourceComposite types were returned.", resourceComposites.size() > 0); - - } - // function testFindUnfiltered() { @Test(enabled = TESTS_ENABLED) public void testUnfilteredFind() {
commit 388d8209f97e91f044ef2855e5f59def58111ad4 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 01:13:05 2010 -0400
remove unused methods in PersistenceUtility
diff --git a/modules/core/domain/src/main/java/org/rhq/core/server/PersistenceUtility.java b/modules/core/domain/src/main/java/org/rhq/core/server/PersistenceUtility.java index 53e871a..82c315e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/server/PersistenceUtility.java +++ b/modules/core/domain/src/main/java/org/rhq/core/server/PersistenceUtility.java @@ -73,6 +73,7 @@ public class PersistenceUtility { public static final String HIBERNATE_STATISTICS_MBEAN_OBJECTNAME = "Hibernate:type=statistics,application=RHQ";
@SuppressWarnings("unchecked") + // used in hibernate.jsp public static String getDisplayString(Type hibernateType) { if (hibernateType instanceof EntityType) { return hibernateType.getName() + " (enter integer of ID / primary key field)"; @@ -99,6 +100,7 @@ public class PersistenceUtility { }
@SuppressWarnings("unchecked") + // used in hibernate.jsp public static Object cast(String value, Type hibernateType) { if (hibernateType instanceof PrimitiveType) { Class<?> type = ((PrimitiveType) hibernateType).getPrimitiveClass(); @@ -202,33 +204,6 @@ public class PersistenceUtility { return entityManager.createQuery(query.toString()); }
- public static Query createNonNamedQueryWithOrderBy(EntityManager entityManager, String queryText, - PageControl pageControl) { - Query query; - - if (pageControl.getPrimarySortColumn() != null) { - query = createNonNamedQueryWithOrderBy(entityManager, queryText, pageControl.getOrderingFieldsAsArray()); - } else { - StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[1]; - LOG.warn("Queries should really supply default sort columns. Caller did not: " + caller); - - // Use the standard named query if no sorting is specified - query = entityManager.createQuery(queryText); - } - - setDataPage(query, pageControl); - - return query; - } - - public static Query createNonNamedQueryWithOrderBy(EntityManager entityManager, String queryText, - OrderingField... orderByFields) { - - StringBuilder query = new StringBuilder(queryText); - buildOrderBy(query, orderByFields); - return entityManager.createQuery(query.toString()); - } - private static StringBuilder buildOrderBy(StringBuilder query, OrderingField... orderByFields) { boolean first = true; for (OrderingField orderingField : orderByFields) { @@ -342,8 +317,7 @@ public class PersistenceUtility { if (pageControl.getPrimarySortColumn() != null) { PageOrdering order = (pageControl.getPrimarySortOrder() == null) ? PageOrdering.ASC : pageControl .getPrimarySortOrder(); - filter = buildOrderBy(new StringBuilder(), new OrderingField(pageControl.getPrimarySortColumn(), order)) - .toString(); + filter = getOrderByFragment(new OrderingField(pageControl.getPrimarySortColumn(), order)); }
org.hibernate.Query query = getHibernateSession(entityManager).createFilter(collection, filter); @@ -422,12 +396,6 @@ public class PersistenceUtility { return hibernateStatistics; }
- public static String getQueryDefinitionFromNamedQuery(EntityManager entityManager, String queryName) { - - NamedQueryDefinition ndc = getNamedQueryDefinition(entityManager, queryName); - return ndc.getQueryString(); - } - private static NamedQueryDefinition getNamedQueryDefinition(EntityManager entityManager, String queryName) { SessionFactoryImplementor sessionFactory = getHibernateSessionFactoryImplementor(entityManager); NamedQueryDefinition namedQueryDefinition = sessionFactory.getNamedQuery(queryName); @@ -462,7 +430,7 @@ public class PersistenceUtility { queryWithPagingSorting.append("SELECT innerResults.*, ROWNUM rnum FROM ( "); queryWithPagingSorting.append(query); // for oracle, order by occurs at the end of the original query, whether grouped or not - buildOrderBy(queryWithPagingSorting, pageControl.getOrderingFieldsAsArray()); + queryWithPagingSorting.append(getOrderByFragment(pageControl.getOrderingFieldsAsArray())); queryWithPagingSorting.append(" ) innerResults ");
// for oracle, paginate high off of the inner projection @@ -584,7 +552,7 @@ public class PersistenceUtility { queryWithPagingSorting.append(query);
// for postgres, first order by - buildOrderBy(queryWithPagingSorting, pageControl.getOrderingFieldsAsArray()); + queryWithPagingSorting.append(getOrderByFragment(pageControl.getOrderingFieldsAsArray()));
// for postgres, then paginate queryWithPagingSorting.append(" LIMIT ").append(pageControl.getPageSize());
commit 841aef8571e5abe1bfb5dc12c2b5697346929b38 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 00:44:56 2010 -0400
fix todos in MeasurementUnits
* it is possible for MeasurementUnits (especially from different MeasurementUnit.Family's) to have the same displayUnits names * fix enum formatting
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementUnits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementUnits.java index a2ff4db..0c4e682 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementUnits.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementUnits.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.domain.measurement;
import org.rhq.core.domain.measurement.util.MeasurementConversionException; @@ -27,29 +27,48 @@ import org.rhq.core.domain.measurement.util.MeasurementConversionException; /** * Metric data values can be in one of the following known units of measurement. These enum values should correspond to * the "units" attribute enumerated type values as defined in the plugin descriptor's <metric> element. + * + * @author Joseph Marques */ public enum MeasurementUnits { // Simple Metric Types - Absolute and Relative - NONE("", Family.ABSOLUTE, Scale.ONE), PERCENTAGE("%", Family.RELATIVE, Scale.HECTO), + NONE("", Family.ABSOLUTE, Scale.ONE), // + PERCENTAGE("%", Family.RELATIVE, Scale.HECTO), //
// Absolute Sizes in Bytes (utilization) - BYTES("B", Family.BYTES, Scale.ONE), KILOBYTES("KB", Family.BYTES, Scale.KILO), MEGABYTES("MB", Family.BYTES, - Scale.MEGA), GIGABYTES("GB", Family.BYTES, Scale.GIGA), TERABYTES("TB", Family.BYTES, Scale.TERA), PETABYTES( - "PB", Family.BYTES, Scale.PETA), + BYTES("B", Family.BYTES, Scale.ONE), // + KILOBYTES("KB", Family.BYTES, Scale.KILO), // + MEGABYTES("MB", Family.BYTES, Scale.MEGA), // + GIGABYTES("GB", Family.BYTES, Scale.GIGA), // + TERABYTES("TB", Family.BYTES, Scale.TERA), // + PETABYTES("PB", Family.BYTES, Scale.PETA), //
// Absolute Sizes in Bits (throughput) - BITS("b", Family.BITS, Scale.ONE), KILOBITS("Kb", Family.BITS, Scale.KILO), MEGABITS("Mb", Family.BITS, Scale.MEGA), GIGABITS( - "Gb", Family.BITS, Scale.GIGA), TERABITS("Tb", Family.BITS, Scale.TERA), PETABITS("Pb", Family.BITS, Scale.PETA), + BITS("b", Family.BITS, Scale.ONE), // + KILOBITS("Kb", Family.BITS, Scale.KILO), // + MEGABITS("Mb", Family.BITS, Scale.MEGA), // + GIGABITS("Gb", Family.BITS, Scale.GIGA), // + TERABITS("Tb", Family.BITS, Scale.TERA), // + PETABITS("Pb", Family.BITS, Scale.PETA), //
// Absolute Time - no display, only hints to the UI how to display - EPOCH_MILLISECONDS("", Family.DURATION, Scale.MILLI), EPOCH_SECONDS("", Family.DURATION, Scale.SEC), + EPOCH_MILLISECONDS("", Family.DURATION, Scale.MILLI), // + EPOCH_SECONDS("", Family.DURATION, Scale.SEC), //
// Relative Time - JIFFYS("j", Family.TIME, Scale.JIFFY), NANOSECONDS("ns", Family.TIME, Scale.NANO), MICROSECONDS("us", Family.TIME, - Scale.MICRO), MILLISECONDS("ms", Family.TIME, Scale.MILLI), SECONDS("s", Family.TIME, Scale.SEC), MINUTES("m", - Family.TIME, Scale.MIN), HOURS("h", Family.TIME, Scale.HOUR), DAYS("d", Family.TIME, Scale.DAY), - - CELSIUS("C", Family.TEMPERATURE, Scale.ONE), KELVIN("K", Family.TEMPERATURE, Scale.ONE), FAHRENHEIGHT("F", Family.TEMPERATURE, Scale.ONE); + JIFFYS("j", Family.TIME, Scale.JIFFY), // + NANOSECONDS("ns", Family.TIME, Scale.NANO), // + MICROSECONDS("us", Family.TIME, Scale.MICRO), // + MILLISECONDS("ms", Family.TIME, Scale.MILLI), // + SECONDS("s", Family.TIME, Scale.SEC), // + MINUTES("m", Family.TIME, Scale.MIN), // + HOURS("h", Family.TIME, Scale.HOUR), // + DAYS("d", Family.TIME, Scale.DAY), // + + // Temperature + CELSIUS("C", Family.TEMPERATURE, Scale.ONE), // + KELVIN("K", Family.TEMPERATURE, Scale.ONE), // + FAHRENHEIGHT("F", Family.TEMPERATURE, Scale.ONE);
private String displayUnits; private Family family; @@ -60,7 +79,6 @@ public enum MeasurementUnits { throw new RuntimeException("Screen real estate is expensive; displayUnits must be 5 characters or less"); }
- // TODO check for duplicate displayUnits names this.displayUnits = displayUnits; this.family = family; this.scale = scale; @@ -158,14 +176,26 @@ public enum MeasurementUnits {
public enum Scale { // Binary based scaling factors - CENTI(Type.SIZE), ONE(Type.SIZE, CENTI, 100), HECTO(Type.SIZE, ONE, 100), KILO(Type.SIZE, ONE, 1024), MEGA( - Type.SIZE, KILO, 1024), GIGA(Type.SIZE, MEGA, 1024), TERA(Type.SIZE, GIGA, 1024), PETA(Type.SIZE, TERA, - 1024), + CENTI(Type.SIZE), // + ONE(Type.SIZE, CENTI, 100), // + HECTO(Type.SIZE, ONE, 100), // + KILO(Type.SIZE, ONE, 1024), // + MEGA(Type.SIZE, KILO, 1024), // + GIGA(Type.SIZE, MEGA, 1024), // + TERA(Type.SIZE, GIGA, 1024), // + PETA(Type.SIZE, TERA, 1024), //
// Time based scaling factors - JIFFY(Type.TIME), NANO(Type.TIME, JIFFY, 1000), MICRO(Type.TIME, NANO, 1000), MILLI(Type.TIME, MICRO, 1000), SEC( - Type.TIME, MILLI, 1000), MIN(Type.TIME, SEC, 60), HOUR(Type.TIME, MIN, 60), DAY(Type.TIME, HOUR, 24), WEEK( - Type.TIME, DAY, 7), YEAR(Type.TIME, WEEK, 52); + JIFFY(Type.TIME), // + NANO(Type.TIME, JIFFY, 1000), // + MICRO(Type.TIME, NANO, 1000), // + MILLI(Type.TIME, MICRO, 1000), // + SEC(Type.TIME, MILLI, 1000), // + MIN(Type.TIME, SEC, 60), // + HOUR(Type.TIME, MIN, 60), // + DAY(Type.TIME, HOUR, 24), // + WEEK(Type.TIME, DAY, 7), // + YEAR(Type.TIME, WEEK, 52);
enum Type { NONE, SIZE, TIME;
commit b294d0f91fb957dddc9052480f12e2bb6703bdc9 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 00:37:34 2010 -0400
fix todos in ResourceTest
* remove testCompositeLookup - it's not actually testing composites, and the previously commented out portion references methods in PersistenceUtility that no longer exist * remove testPlatformLookup - it has no test harness, it tests nothing * remove testSeucirtyQuery - see AuthorizationManagerBeanTest
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceTest.java index a40a07e..c3b5667 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceTest.java @@ -28,69 +28,18 @@ import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.Query; -import javax.transaction.NotSupportedException; -import javax.transaction.SystemException;
import org.testng.annotations.Test;
-import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.authz.Permission; -import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.measurement.AvailabilityType; 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.test.AbstractEJB3Test;
public class ResourceTest extends AbstractEJB3Test { - // TODO GH: Fixme @Test(groups = "integration.ejb3") - public void testCompositeLookup() throws Exception { - EntityManager em = getEntityManager(); - getTransactionManager().begin(); - try { - Subject s = em.getReference(Subject.class, new Integer(502550)); - // ResourceComposite c = new ResourceComposite(); - System.out.println("HELLOWORLD2"); - - Query query = em.createQuery("SELECT count(res) " + "FROM Resource res " - + " JOIN res.resourceGroups g JOIN g.roles r JOIN r.subjects s " + "WHERE s = :subject " - + " AND (:category = res.resourceType.category OR :category is null) " - + " AND (:resourceType = res.resourceType OR :resourceType is null) " - + " AND (res.inventoryStatus = :inventoryStatus OR :inventoryStatus is null) " - + " AND (res.name LIKE :search OR res.description LIKE :search OR :search is null)) "); - - ResourceType t = em.getReference(ResourceType.class, new Integer(501064)); - - query.setParameter("subject", s); - query.setParameter("category", ResourceCategory.SERVER); - query.setParameter("resourceType", t); - query.setParameter("inventoryStatus", InventoryStatus.COMMITTED); - query.setParameter("search", "%"); - System.out.println("Found stuff"); - for (Object o : query.getResultList()) { - System.out.println(o); - } - - //Permission.CONTROL - /*Query query = em.createQuery("SELECT p FROM Role r LEFT JOIN r.permissions p WHERE p = 3"); - * //org.rhq.core.domain.authz.Permission.CONTROL"); - * for (Object o : query.getResultList()) { System.out.println("[" + o.getClass().getSimpleName() + "]: " + - * o);}*/ - - /*Query query = em.createNamedQuery(Resource.QUERY_FIND_COMPOSITE); - * PersistenceUtility.setNullableParameter(query,"search",null,String.class); - * query.setParameter("subject",s); // query.setParameter("inventoryStatus", null); - * PersistenceUtility.setNullableParameter(query,"inventoryStatus", null, Integer.class); - * List<ResourceComposite> resourceComposites = query.getResultList(); for (ResourceComposite composite : - * resourceComposites) { System.out.println(composite);}*/ - - } finally { - getTransactionManager().rollback(); - } - }
@Test(groups = "integration.ejb3") public void testCreateAlotOfResources() throws Exception { @@ -194,41 +143,6 @@ public class ResourceTest extends AbstractEJB3Test { + "] resources with availabilities"); }
- @SuppressWarnings("unchecked") - @Test(groups = "integration.ejb3") - public void testPlatformLookup() throws Exception { - EntityManager em = getEntityManager(); - getTransactionManager().begin(); - try { - Query query = em.createQuery("SELECT e FROM Resource e WHERE e.resourceType = 0"); // TODO hibernate enum query bug: ResourceCategory.PLATFORM"); - List<Resource> platforms = query.getResultList(); - for (Resource platform : platforms) { - System.out.println("Platform: " + platform); - @SuppressWarnings("unused") - Configuration config = platform.getPluginConfiguration(); - } - } finally { - getTransactionManager().rollback(); - } - } - - @Test(groups = "integration.ejb3") - public void testSecurityQuery() throws SystemException, NotSupportedException { - EntityManager em = getEntityManager(); - getTransactionManager().begin(); - try { - // TODO: Make this test resource, group, authz linkage - Query query = em.createQuery("SELECT r FROM Role r JOIN r.permissions p WHERE p = :perm"); - - //"SELECT res FROM Subject s join s.roles as r join r.permissions p join r.resourceGroups g join g.resources res WHERE p = :perm AND s.id = :sid"); - query.setParameter("perm", Permission.MANAGE_SECURITY); - // query.setParameter("sid", 0); - System.out.println("Admin user count: " + query.getResultList().size()); - } finally { - getTransactionManager().rollback(); - } - } - @Test(groups = "integration.ejb3") public void testMediumPlatformCreate() { int id = 0;
commit af3f28e3bbce631ae88f66da0329107e61d3d9f1 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 11 00:19:01 2010 -0400
fix todos in ResourceType
* remove todo in toString, default impl doesn't need to print parents * remove todo in compareTo, name comparison is a sufficient default impl * implement addFilterParentId to ResourceTypeCriteria ** this new filter will enable implementation of todos in the @NamedQueries section
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java index 93ba523..f7435f3 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceTypeCriteria.java @@ -45,6 +45,7 @@ public class ResourceTypeCriteria extends Criteria { private static final long serialVersionUID = 1L;
private Integer filterId; + private Integer filterParentId; // required overrides private List<Integer> filterIds; // requires overrides
private String filterName; @@ -75,6 +76,12 @@ public class ResourceTypeCriteria extends Criteria { private PageOrdering sortPluginName; // needs overrides
public ResourceTypeCriteria() { + filterOverrides.put("parentId", "" // + + "id IN ( SELECT innerRt.id " // + + " FROM ResourceType innerRt " // + + " JOIN innerRt.parentResourceTypes innerParentRt " // + + " WHERE innerParentRt.id IN ( ? ) )"); + filterOverrides.put("pluginName", "plugin like ?"); filterOverrides.put("ids", "id in ( ? )"); filterOverrides.put("bundleTypeId", "bundleType.id = ?"); @@ -91,6 +98,10 @@ public class ResourceTypeCriteria extends Criteria { this.filterId = filterId; }
+ public void addFilterParentId(Integer filterParentId) { + this.filterParentId = filterParentId; + } + public void addFilterIds(Integer... filterIds) { this.filterIds = Arrays.asList(filterIds); } 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 f7dba02..19cdd11 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 @@ -746,7 +746,6 @@ public class ResourceType implements Serializable, Comparable<ResourceType> {
public int compareTo(ResourceType that) { return this.name.compareTo(that.getName()); - // TODO: Order by category too? }
public String getHelpText() { @@ -804,17 +803,8 @@ public class ResourceType implements Serializable, Comparable<ResourceType> {
@Override public String toString() { - /* TODO GH: Not safe, may not have been loaded (lazy initialization exceptions) - StringBuffer parents = new StringBuffer(); - for (ResourceType parent : parentResourceTypes) - { - if (parents.length() > 0) - parents.append(','); - parents.append(parent.getName()); - }*/ - return "ResourceType[id=" + this.id + ", category=" + this.category + ", name=" + this.name + ", plugin=" - + this.plugin + /*", parents=" + parents +*/"]"; + + this.plugin + "]"; }
}
commit aae28aa1c6d164be4f3ded2e15c17d5c32c4edb5 Author: Joseph Marques joseph@redhat.com Date: Sun Oct 10 23:16:37 2010 -0400
expose internal doc for Criteria as full JavaDoc
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java index 4ad0376..2d8a6b7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/Criteria.java @@ -111,7 +111,7 @@ public abstract class Criteria implements Serializable { this.pageSize = pageSize; }
- /* + /** * If the pageControl is set, then this criteria object will completely ignore any * calls made to setPaging(pageNumber, pageSize) as well as addSortField(fieldName), * which is useful from a server-side calling context where the PageControl object @@ -121,7 +121,7 @@ public abstract class Criteria implements Serializable { this.pageControlOverrides = pageControl; }
- /* + /** * By default, the ordering fields are automatically prepend with the alias of entity that this criteria object * wraps. However, some authors of criteria objects want full control of this alias during sort operations. if * this method returns true, then the alias will not be prepend to the generated "order by" clause, which makes @@ -138,7 +138,7 @@ public abstract class Criteria implements Serializable { this.pageControlOverrides = null; }
- /* + /** * If set to true, then results will come back if they match ANY filter; * Default is 'false', which means results must match all set filters. */ @@ -150,7 +150,7 @@ public abstract class Criteria implements Serializable { return filtersOptional; }
- /* + /** * If set to true, string-based filters will use case-sensitive matching; * Default is 'false', which means results will match case-insensitively */ @@ -162,7 +162,7 @@ public abstract class Criteria implements Serializable { return this.caseSensitive; }
- /* + /** * If set to true, string-based filters will use exact string matches; * Default is 'false', which means we'll fuzzy match */
commit 8e4ecf09283606fbc0420186919f4c145e87e6a2 Author: Joseph Marques joseph@redhat.com Date: Sun Oct 10 23:11:13 2010 -0400
fix todo in TokenGenerationTest
* switched from using Agent.generateRandomToken (which is what was being tested) to using SecureRandom.getInstance("SHA1PRNG"), which resides directly in CoreServerServiceImpl
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/TokenGenerationTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/TokenGenerationTest.java deleted file mode 100644 index 8e75a2c..0000000 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/TokenGenerationTest.java +++ /dev/null @@ -1,85 +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, 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.resource.test; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import org.testng.annotations.Test; -import org.rhq.core.domain.resource.Agent; - -@Test -public class TokenGenerationTest { - /* - TODO: GWT - (This is no longer needed... switched to using SecureRandom generation from the CoreServerServiceImpl) - - public void testUniqueTokenGeneration1() throws Exception { - final Collection<String> tokens = Collections.synchronizedSet(new HashSet<String>()); - final int maxThreads = 20; - final CountDownLatch latch = new CountDownLatch(maxThreads); // will open when all threads are done - - for (int i = 0; i < maxThreads; i++) { - new Thread(new Runnable() { - public void run() { - String token = Agent.generateRandomToken("seed"); // purposefully pass in the same string, see if we can break it - if (!tokens.add(token)) { - System.out.println("DUPLICATE TOKEN=" + token); - } - - latch.countDown(); - } - }).start(); - } - - assert latch.await(120, TimeUnit.SECONDS) : "Did not wait long enough for the threads to finish"; - assert tokens.size() == maxThreads : "One or more generated tokens were duplicated: " + maxThreads + " : " - + tokens.size() + " : " + tokens; - } - - public void testUniqueTokenGeneration2() throws Exception { - final Collection<String> tokens = Collections.synchronizedSet(new HashSet<String>()); - final int maxThreads = 20; - final CountDownLatch latch = new CountDownLatch(maxThreads); // will open when all threads are done - - for (int i = 0; i < maxThreads; i++) { - final String seed = "seed" + i; // pass in a unique seed for each call to generate the token - new Thread(new Runnable() { - public void run() { - String token = Agent.generateRandomToken(seed); - if (!tokens.add(token)) { - System.out.println("DUPLICATE TOKEN=" + token); - } - - latch.countDown(); - } - }).start(); - } - - assert latch.await(120, TimeUnit.SECONDS) : "Did not wait long enough for the threads to finish"; - assert tokens.size() == maxThreads : "One or more generated tokens were duplicated: " + maxThreads + " : " - + tokens.size() + " : " + tokens; - }*/ -} \ No newline at end of file
commit 05c128f449c0f9e00102e4793813a5537a2fe6e0 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 8 03:30:57 2010 -0400
fix todo in EventReport
* remove Log.warn from EventReport and instead print a report of how many events for each EventSource were dropped in the EventManager
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/event/transfer/EventReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/event/transfer/EventReport.java index 50a492b..9b150c8 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/event/transfer/EventReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/event/transfer/EventReport.java @@ -23,13 +23,12 @@ package org.rhq.core.domain.event.transfer;
import java.io.Serializable; +import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.jetbrains.annotations.NotNull;
import org.rhq.core.domain.event.Event; @@ -147,10 +146,12 @@ public class EventReport implements Serializable { * (i.e. the method will do nothing and return immediately). Therefore, it is recommended * you call this method only after the report is done and you are ready to send the * report to the server for further processing. + * + * @return true if some events in teh current report were dropped due to limits */ - public void addLimitWarningEvents() { + public boolean addLimitWarningEvents() { if (this.addedLimitWarningEvents || this.eventsDropped == null) { - return; // we already added them or there is nothing to add + return false; // we already added them or there is nothing to add }
Event warningEvent; @@ -172,9 +173,6 @@ public class EventReport implements Serializable { + this.maxEventsPerReport + "] - dropped [" + droppedCount + "] events"; }
- /* TODO: GWT - LOG.warn(warningMessage + ": source=[" + eventSource + "]"); - */ warningEvent = new Event(eventSource.getEventDefinition().getName(), eventSource.getLocation(), now, EventSeverity.WARN, warningMessage, eventSource); eventSet.add(warningEvent); @@ -182,7 +180,11 @@ public class EventReport implements Serializable { this.addedLimitWarningEvents = true; }
- return; + return this.eventsDropped.size() > 0; + } + + public Map<EventSource, Integer> getDroppedEvents() { + return Collections.unmodifiableMap(eventsDropped); }
public int getMaxEventsPerSource() { @@ -195,6 +197,7 @@ public class EventReport implements Serializable {
@Override public String toString() { - return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1) + "[" + this.events + "]"; + return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".") + 1) + "[" + this.events + + "]"; } } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventManager.java index 98d8573..4ad5c50 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventManager.java @@ -127,7 +127,14 @@ public class EventManager implements ContainerService { * @param report the Event report to be sent (this report should be closed from getting any more events added to it) */ void sendEventReport(EventReport report) { - report.addLimitWarningEvents(); // add any limit warning events if events were dropped + if (report.addLimitWarningEvents()) { // add any limit warning events if events were dropped + Map<EventSource, Integer> droppedEvents = report.getDroppedEvents(); + log.warn("Begin dropped events report"); + for (Map.Entry<EventSource, Integer> next : droppedEvents.entrySet()) { + log.warn("There were " + next.getValue() + " dropped events for source '" + next.getKey() + "'"); + } + log.warn("Finish dropped events report"); + } if (!report.getEvents().isEmpty() && this.pcConfig.getServerServices() != null) { try { this.pcConfig.getServerServices().getEventServerService().mergeEventReport(report);
commit bbb3f3aa541da6c3697afe40da7c58a5d6372d05 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 8 03:30:03 2010 -0400
remove todo from ResourceType
* eliminate ResourceType.findByName query, replaced by criteria-based finder * also, delete unnecessary composite-finder in ResourceManagerBean
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 079b8f5..f7dba02 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 @@ -79,8 +79,6 @@ import org.rhq.core.domain.util.Summary; @Table(name = ResourceType.TABLE_NAME) @SequenceGenerator(name = "SEQ", sequenceName = "RHQ_RESOURCE_TYPE_ID_SEQ") @NamedQueries( { - @NamedQuery(name = ResourceType.QUERY_FIND_BY_NAME, // TODO: QUERY: This breaks rules, names may not be unique between plugins - query = "SELECT rt FROM ResourceType AS rt WHERE LOWER(rt.name) = LOWER(:name)"), @NamedQuery(name = ResourceType.QUERY_FIND_BY_PLUGIN, query = "SELECT rt FROM ResourceType AS rt WHERE rt.plugin = :plugin"), @NamedQuery(name = ResourceType.QUERY_FIND_BY_NAME_AND_PLUGIN, // TODO: QUERY: names are case-sensitive query = "SELECT rt FROM ResourceType AS rt WHERE LOWER(rt.name) = LOWER(:name) AND rt.plugin = :plugin"), @@ -237,7 +235,6 @@ public class ResourceType implements Serializable, Comparable<ResourceType> {
public static final ResourceType ANY_PLATFORM_TYPE = null;
- public static final String QUERY_FIND_BY_NAME = "ResourceType.findByName"; public static final String QUERY_GET_EXPLICIT_RESOURCE_TYPE_COUNTS_BY_GROUP = "ResourceType.getExplicitResourceTypeCountsByGroup"; public static final String QUERY_GET_IMPLICIT_RESOURCE_TYPE_COUNTS_BY_GROUP = "ResourceType.getImplicitResourceTypeCountsByGroup"; public static final String QUERY_FIND_BY_NAME_AND_PLUGIN = "ResourceType.findByNameAndPlugin"; 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 62091bc..6f4d21e 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 @@ -939,28 +939,6 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage return new PageList<Resource>(results, (int) count, pageControl); }
- public PageList<ResourceComposite> findResourceComposites(Subject user, ResourceCategory category, String typeName, - int parentResourceId, String searchString, PageControl pageControl) { - - ResourceType type = null; - Resource parentResource = null; - - if (null != typeName) { - Query query = entityManager.createNamedQuery(ResourceType.QUERY_FIND_BY_NAME); - query.setParameter("name", typeName); - type = (ResourceType) query.getSingleResult(); - // TODO: why is this being fetched after it was just loaded?! - type = entityManager.find(ResourceType.class, type.getId()); - } - if (parentResourceId > 0) { - parentResource = getResourceById(user, parentResourceId); - } - - String typeNameFilter = type == null ? null : type.getName(); - return findResourceComposites(user, category, typeNameFilter, null, parentResource, searchString, false, - pageControl); - } - /** * This finder query can be used to find resources with various combinations of attributes in their composite form. * Except for the user parameter, the other parameters can be left null so that the query will not filter by that diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java index 4414504..a94bcc4 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java @@ -202,14 +202,6 @@ public interface ResourceManagerLocal { PageList<Resource> findResourcesByCategory(Subject user, ResourceCategory category, InventoryStatus inventoryStatus, PageControl pageControl);
- PageList<ResourceComposite> findResourceComposites( // - Subject user, // - ResourceCategory category, // - String typeName, // - int parentResourceId, // - String searchString, // - PageControl pageControl); - /** * @see ResourceManagerRemote#findResourceComposites(Subject, ResourceCategory, String, int, String, PageControl) */ diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerRemote.java index 8f8604d..46b8e08 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerRemote.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerRemote.java @@ -31,8 +31,6 @@ import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.measurement.ResourceAvailability; import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceCategory; -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.server.jaxb.adapter.ResourceListAdapter; @@ -126,15 +124,6 @@ public interface ResourceManagerRemote { @WebParam(name = "resourceIds") int[] resourceIds);
@WebMethod - PageList<ResourceComposite> findResourceComposites( // - @WebParam(name = "subject") Subject subject, // - @WebParam(name = "category") ResourceCategory category, // - @WebParam(name = "typeName") String typeName, // - @WebParam(name = "parentResourceId") int parentResourceId, // - @WebParam(name = "searchString") String searchString, // - @WebParam(name = "pageControl") PageControl pageControl); - - @WebMethod PageList<Resource> findResourcesByCriteria( // @WebParam(name = "subject") Subject subject, // @WebParam(name = "criteria") ResourceCriteria criteria); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/test/DiscoveryTestBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/test/DiscoveryTestBean.java index 709b95a..39f8635 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/test/DiscoveryTestBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/test/DiscoveryTestBean.java @@ -41,6 +41,7 @@ import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Role; +import org.rhq.core.domain.criteria.ResourceTypeCriteria; import org.rhq.core.domain.plugin.Plugin; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.InventoryStatus; @@ -53,6 +54,7 @@ import org.rhq.enterprise.server.RHQConstants; import org.rhq.enterprise.server.auth.SubjectManagerLocal; import org.rhq.enterprise.server.core.CoreServerServiceImpl; import org.rhq.enterprise.server.discovery.DiscoveryServerServiceImpl; +import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal;
/** * An EJB for testing the discovery subsystem - used by TestControl.jsp. @@ -87,6 +89,9 @@ public class DiscoveryTestBean implements DiscoveryTestLocal { @EJB private SubjectManagerLocal subjectManager;
+ @EJB + private ResourceTypeManagerLocal resourceTypeManager; + public void registerTestPluginAndTypeInfo() { //System.out.println("CALLER: " + ctx.getCallerPrincipal() + " (" + ctx.getCallerPrincipal().getName() + ")"); try { @@ -194,16 +199,6 @@ public class DiscoveryTestBean implements DiscoveryTestLocal { } }
- /*private void checkUserCanManageAgent(LatherContext ctx, String user, - * String pword, String operation) throws PermissionException { // TODO: Implement - * check (gh: what is with all the crazy caching?) - */ - /*sessionId = this.getAuthManager().getSessionId(user, pword); - * subject = - * this.sessionManager.getSubject(sessionId);this.getServerManager().checkCreatePlatformPermission(subject);*/ - /* - *}*/ - public void createTestMixedGroup(String groupName) { List<Resource> resources = PersistenceUtility .findByCriteria(entityManager, Resource.class, Restrictions.like("name", "BogusServer 0", @@ -238,18 +233,21 @@ public class DiscoveryTestBean implements DiscoveryTestLocal { }
private ResourceType getTestPlatformType() { - return (ResourceType) entityManager.createNamedQuery(ResourceType.QUERY_FIND_BY_NAME).setParameter("name", - TEST_PLATFORM_TYPE_NAME).getSingleResult(); + ResourceTypeCriteria criteria = new ResourceTypeCriteria(); + criteria.addFilterName(TEST_PLATFORM_TYPE_NAME); + return resourceTypeManager.findResourceTypesByCriteria(subjectManager.getOverlord(), criteria).get(0); }
private ResourceType getTestServerType() { - return (ResourceType) entityManager.createNamedQuery(ResourceType.QUERY_FIND_BY_NAME).setParameter("name", - TEST_SERVER_TYPE_NAME).getSingleResult(); + ResourceTypeCriteria criteria = new ResourceTypeCriteria(); + criteria.addFilterName(TEST_SERVER_TYPE_NAME); + return resourceTypeManager.findResourceTypesByCriteria(subjectManager.getOverlord(), criteria).get(0); }
private ResourceType getTestServiceType() { - return (ResourceType) entityManager.createNamedQuery(ResourceType.QUERY_FIND_BY_NAME).setParameter("name", - TEST_SERVICE_TYPE_NAME).getSingleResult(); + ResourceTypeCriteria criteria = new ResourceTypeCriteria(); + criteria.addFilterName(TEST_SERVICE_TYPE_NAME); + return resourceTypeManager.findResourceTypesByCriteria(subjectManager.getOverlord(), criteria).get(0); }
private Resource createTestPlatform(String address, int servers, int servicesPerServer) { 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 d5f3cce..a91a832 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 @@ -107,10 +107,8 @@ import org.rhq.core.domain.operation.ResourceOperationHistory; import org.rhq.core.domain.resource.CreateResourceHistory; import org.rhq.core.domain.resource.DeleteResourceHistory; 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.resource.composite.ProblemResourceComposite; -import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite; import org.rhq.core.domain.util.PageControl; @@ -812,12 +810,6 @@ public class WebservicesManagerBean implements WebservicesRemote { //RESOURCEFACTORYMANAGER: END ----------------------------------
//RESOURCEMANAGER: BEGIN ---------------------------------- - public PageList<ResourceComposite> findResourceComposites(Subject subject, ResourceCategory category, - String typeName, int parentResourceId, String searchString, PageControl pageControl) { - return resourceManager.findResourceComposites(subject, category, typeName, parentResourceId, searchString, - pageControl); - } - public List<Resource> findResourceLineage(Subject subject, int resourceId) { return resourceManager.findResourceLineage(subject, resourceId); }
commit 9d595a68fc784a7e78ed39b541b65a219ddf3e0c Author: Joseph Marques joseph@redhat.com Date: Fri Oct 8 02:51:38 2010 -0400
fix todos with OperationHistory, ResourceOperationHistory, and OperationSchedule
* remove conditional printing of parameters/results in toString() override * if tests need to see these values, they can still be gotten via getParameters()/getResults()
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationHistory.java index 2556406..84a494a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/OperationHistory.java @@ -364,6 +364,10 @@ public abstract class OperationHistory implements Serializable { return end - start; }
+ /* + * there may be some operations whose parameters are sensitive values, such as passwords - do not show them + * as part of the toString. they can still be gotten by explicitly calling getParameters() + */ @Override public String toString() { StringBuilder buf = new StringBuilder(); @@ -372,14 +376,6 @@ public abstract class OperationHistory implements Serializable { buf.append("], job-group=[" + this.jobGroup); buf.append("], status=[" + this.status); buf.append("], subject-name=[" + this.subjectName); - - // there may be some operations whose parameters are sensitive values, like passwords - // do not show them by default - but allow testers to see them via a system property - /* TODO: GWT - if (Boolean.getBoolean("rhq.test.operation.show-values")) { - buf.append("], parameters=[" + this.parameters); - }*/ - buf.append("], ctime=[" + new java.util.Date(this.createdTime)); buf.append("], mtime=[" + new java.util.Date(this.modifiedTime)); buf.append("], duration-millis=[" + getDuration()); diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationHistory.java index 6b5fab3..4b002b1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/operation/ResourceOperationHistory.java @@ -169,18 +169,14 @@ public class ResourceOperationHistory extends OperationHistory { } }
+ /* + * there may be some operations whose results are sensitive values, such as passwords - do not show them + * as part of the toString. they can still be gotten by explicitly calling getResults() + */ @Override public String toString() { StringBuilder str = new StringBuilder("ResourceOperationHistory: "); str.append("resource=[" + this.resource); - - // there may be some operations whose results are sensitive values, like passwords - // do not show them by default - but allow testers to see them via a system property - /* TODO: GWT - if (Boolean.valueOf(System.getProperty("rhq.test.operation.show-values"))) { - str.append("], results=[" + this.results); - }*/ - str.append("], group-history=[" + this.groupOperationHistory); str.append("], " + super.toString()); str.append("]"); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java index b4db99b..bb5a636 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/operation/OperationSchedule.java @@ -136,6 +136,10 @@ public abstract class OperationSchedule implements Serializable { return new JobId(this.jobName, this.jobGroup); }
+ /* + * there may be some operations whose parameters are sensitive values, such as passwords - do not show them + * as part of the toString. they can still be gotten by explicitly calling getParameters() + */ @Override public String toString() { StringBuilder str = new StringBuilder(); @@ -144,13 +148,6 @@ public abstract class OperationSchedule implements Serializable { str.append("], operation-name=[" + this.operationName); str.append("], subject=[" + this.subject); str.append("], description=[" + this.description); - - // there may be some operations whose parameters are sensitive values, like passwords - // do not show them by default - but allow testers to see them via a system property - if (Boolean.getBoolean("rhq.test.operation.show-values")) { - str.append("], parameters=[" + this.parameters); - } - str.append("]"); return str.toString(); }
commit a6ebf98311e348c732458f491303fd4d4a685550 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 8 02:45:21 2010 -0400
fix todos in ResourceFacets
* although this object is not technically immutable anymore via private final member variables, it is still effectively immutable because there is no way to modify the member variables after object construction. furthermore, this class is accessed through the ResourceFacetsCache, which guarantees correct multi-threaded access.
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 c05d5ef..b72f409 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 @@ -39,10 +39,7 @@ public class ResourceFacets implements Serializable {
public static ResourceFacets NONE = new ResourceFacets(-1, false, false, false, false, false, false, false, false); public static ResourceFacets ALL = new ResourceFacets(-1, true, true, true, true, true, true, true, true); - /* - * immutable private member data makes this object safe to use in a concurrent environment, such as a - * concurrent-access cache of ResourceFacets objects (TODO (ips): make these final again?) - */ + private int resourceTypeId; private boolean measurement; private boolean event;
commit 058831208d21c315516094a7dbba858c50fa38a9 Author: Joseph Marques joseph@redhat.com Date: Fri Oct 8 02:27:10 2010 -0400
remove todos concerning Externalizable from all entities
* for the UI migration to GWT, core/domain was directly exposed as GWT-compilable resources. accordingly, all references to classes that were not GWT-compilable had to be removed. * ExternalizableStrategy and corresponding hooks are being kept, in case they are needed in the future.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java index 4a93c1f..ff8ef88 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java @@ -498,80 +498,5 @@ public class Subject implements Serializable, Recordizable {
return true; } - /* - public void writeExternal(ObjectOutput out) throws IOException { - ExternalizableStrategy.Subsystem strategy = ExternalizableStrategy.getStrategy(); - out.writeChar(strategy.id()); - - if (ExternalizableStrategy.Subsystem.REMOTEAPI == strategy) { - writeExternalRemote(out); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION == strategy) { - EntitySerializer.writeExternalRemote(this, out); - // reflective serialization misses sessionId because it's not a persistence annotated - out.writeInt(this.sessionId == null ? 0 : this.sessionId); - } else { - writeExternalAgent(out); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - char c = in.readChar(); - if (ExternalizableStrategy.Subsystem.REMOTEAPI.id() == c) { - readExternalRemote(in); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION.id() == c) { - EntitySerializer.readExternalRemote(this, in); - // reflective serialization misses sessionId because it's not a persistence annotated - this.sessionId = in.readInt(); - } else { - readExternalAgent(in); - } - } - - public void writeExternalAgent(ObjectOutput out) throws IOException { - out.writeInt(this.id); - out.writeUTF(this.name); - out.writeInt(this.sessionId); - } - - public void readExternalAgent(ObjectInput in) throws IOException, ClassNotFoundException { - this.id = in.readInt(); - this.name = in.readUTF(); - this.sessionId = in.readInt(); - } - - // It is assumed that the object is clean of Hibernate proxies (i.e. HibernateDetachUtility has been run if necessary) - public void writeExternalRemote(ObjectOutput out) throws IOException { - out.writeInt(this.id); - out.writeUTF(this.name); - out.writeUTF((null == firstName) ? "" : firstName); - out.writeUTF((null == lastName) ? "" : lastName); - out.writeUTF((null == emailAddress) ? "" : emailAddress); - out.writeUTF((null == smsAddress) ? "" : smsAddress); - out.writeUTF((null == phoneNumber) ? "" : phoneNumber); - out.writeUTF((null == department) ? "" : department); - out.writeBoolean(factive); - out.writeBoolean(fsystem); - out.writeObject(configuration); - out.writeObject(roles); - // not supplied by remote: subjectNotifications - out.writeInt(this.sessionId == null ? 0 : this.sessionId); - } - - @SuppressWarnings("unchecked") - public void readExternalRemote(ObjectInput in) throws IOException, ClassNotFoundException { - this.id = in.readInt(); - this.name = in.readUTF(); - this.firstName = in.readUTF(); - this.lastName = in.readUTF(); - this.emailAddress = in.readUTF(); - this.smsAddress = in.readUTF(); - this.phoneNumber = in.readUTF(); - this.department = in.readUTF(); - this.factive = in.readBoolean(); - this.fsystem = in.readBoolean(); - this.configuration = (Configuration) in.readObject(); - this.roles = (Set<Role>) in.readObject(); - this.sessionId = in.readInt(); - }*/
} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/composite/FailoverListComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/composite/FailoverListComposite.java index fe4510e..a38bbd4 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/composite/FailoverListComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/composite/FailoverListComposite.java @@ -196,35 +196,6 @@ public class FailoverListComposite implements Iterator<FailoverListComposite.Ser return new FailoverListComposite(servers); }
- /* TODO: GWT - private void writeObject(ObjectOutputStream out) throws IOException { - out.writeInt(size()); - for (ServerEntry entry : servers) { - out.writeUTF(entry.address); - out.writeInt(entry.port); - out.writeInt(entry.securePort); - } - } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - int size = in.readInt(); - - List<ServerEntry> entries = new ArrayList<ServerEntry>(); - for (int i = 0; i < size; i++) { - String address = in.readUTF(); - int port = in.readInt(); - int securePort = in.readInt(); - entries.add(new ServerEntry(address, port, securePort)); - } - - *//* - * no need to wrap 'entries' in a new list before putting them into the immutable wrapper; - * as long as the 'entries' reference does not escape this method, we can be assured that - * 'servers' is correctly immutable. - *//* - servers = Collections.unmodifiableList(entries); - }*/ - @Override public String toString() { StringBuilder sb = new StringBuilder("\nServerList:\n "); diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java index 99488d3..e2754eb 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java @@ -567,92 +567,6 @@ public class Configuration implements Serializable, Cloneable, AbstractPropertyM return builder.append("]").toString(); }
- /* - - public void writeExternal(ObjectOutput out) throws IOException { - ExternalizableStrategy.Subsystem strategy = ExternalizableStrategy.getStrategy(); - out.writeChar(strategy.id()); - - if (isAgentOrRemoteAPISerialization(strategy.id())) { - writeExternalAgentOrRemote(out); - } - else { - EntitySerializer.writeExternalRemote(this, out); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - char c = in.readChar(); - - if (isAgentOrRemoteAPISerialization(c)) { - readExternalAgentOrRemote(in); - } - else { - EntitySerializer.readExternalRemote(this, in); - } - } - - private boolean isAgentOrRemoteAPISerialization(char strategy) { - return strategy == ExternalizableStrategy.Subsystem.AGENT.id() || - strategy == ExternalizableStrategy.Subsystem.REMOTEAPI.id(); - } - - */ - /** - * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) - */ - /* - - public void writeExternalAgentOrRemote(ObjectOutput out) throws IOException { - Configuration copy = deepCopyWithoutProxies(); - - out.writeInt(id); - out.writeObject(createDeepCopyOfMap()); - out.writeObject(createDeepCopyOfRawConfigs()); - out.writeUTF((notes == null) ? "null" : notes); - out.writeLong(version); - out.writeLong(ctime); - out.writeLong(mtime); - } - - private Map<String, Property> createDeepCopyOfMap() { - Map<String, Property> copy = new HashMap<String, Property>(); - for (Map.Entry<String, Property> entry : this.properties.entrySet()) { - Property copiedProperty = entry.getValue().deepCopy(true); - copiedProperty.setConfiguration(this); - copy.put(entry.getKey(), copiedProperty); - } - return copy; - } - - private Set<RawConfiguration> createDeepCopyOfRawConfigs() { - Set<RawConfiguration> copy = new HashSet<RawConfiguration>(); - for (RawConfiguration rawConfig : this.rawConfigurations) { - RawConfiguration copiedRawConfig = rawConfig.deepCopy(true); - copiedRawConfig.setConfiguration(this); - copy.add(copiedRawConfig); - } - return copy; - } - - */ - /** - * @see java.io.Externalizable#readExternal(java.io.ObjectInput) - */ - /* - - @SuppressWarnings("unchecked") - public void readExternalAgentOrRemote(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - properties = (HashMap<String, Property>) in.readObject(); - rawConfigurations = (Set<RawConfiguration>) in.readObject(); - notes = in.readUTF(); - version = in.readLong(); - ctime = in.readLong(); - mtime = in.readLong(); - } - */ - /** * This listener runs after jaxb unmarshalling and reconnects children properties to their parent configurations (as * we don't send them avoiding cyclic references). diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java index 3518159..be176e4 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java @@ -266,72 +266,6 @@ public class Property implements Serializable, DeepCopyable<Property>, Comparabl return null; }
- /* - // It's not clear to me why this class implements Externalizable. It seems to write out every field - // using standard serialization. Also, it's sub-classes seem to write out every field. To be safe I'm leaving - // it as is and also applying the new strategy logic, in case there are (future) differences between agent and - // remoteAPI serialization. - public void writeExternal(ObjectOutput out) throws IOException { - ExternalizableStrategy.Subsystem strategy = ExternalizableStrategy.getStrategy(); - out.writeChar(strategy.id()); - - if (ExternalizableStrategy.Subsystem.REMOTEAPI == strategy) { - writeExternalRemote(out); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION == strategy) { - EntitySerializer.writeExternalRemote(this, out); - } else { - writeExternalAgent(out); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - char c = in.readChar(); - if (ExternalizableStrategy.Subsystem.REMOTEAPI.id() == c) { - readExternalRemote(in); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION.id() == c) { - EntitySerializer.readExternalRemote(this, in); - } else { - readExternalAgent(in); - } - } - - public void writeExternalAgent(ObjectOutput out) throws IOException { - out.writeInt(id); - out.writeObject(configuration); - out.writeUTF(name); - out.writeObject(parentList); - out.writeObject(parentMap); - out.writeObject(errorMessage); - } - - public void readExternalAgent(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - configuration = (Configuration) in.readObject(); - name = in.readUTF(); - parentList = (PropertyList) in.readObject(); - parentMap = (PropertyMap) in.readObject(); - errorMessage = (String) in.readObject(); - } - - // It is assumed that the object is clean of Hibernate proxies (i.e. HibernateDetachUtility has been run if necessary) - public void writeExternalRemote(ObjectOutput out) throws IOException { - out.writeInt(id); - out.writeObject(configuration); - out.writeUTF(name); - out.writeObject(errorMessage); - out.writeObject(parentList); - out.writeObject(parentMap); - } - - public void readExternalRemote(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - configuration = (Configuration) in.readObject(); - name = in.readUTF(); - errorMessage = (String) in.readObject(); - parentList = (PropertyList) in.readObject(); - parentMap = (PropertyMap) in.readObject(); - }*/ - @Override public String toString() { StringBuilder str = new StringBuilder(this.getClass().getName().substring( diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyList.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyList.java index ce51bcc..a5f7e2a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyList.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyList.java @@ -22,9 +22,8 @@ */ package org.rhq.core.domain.configuration;
-import org.hibernate.annotations.Cascade; -import org.hibernate.annotations.CascadeType; -import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; +import java.util.List;
import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -35,8 +34,9 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
-import java.util.ArrayList; -import java.util.List; +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; +import org.jetbrains.annotations.NotNull;
/** * Holds an indexed list of child {@link Property properties}. This can hold any number of properties, including @@ -146,34 +146,15 @@ public class PropertyList extends Property { }
if (!property.getName().equals(this.memberPropertyName)) { - throw new IllegalStateException("All properties in a PropertyList (id=[" + getId() + "], name=[" + getName() - + "]) must have the same name: [" + property.getName() + "] != [" + this.memberPropertyName + "]"); + throw new IllegalStateException("All properties in a PropertyList (id=[" + getId() + "], name=[" + + getName() + "]) must have the same name: [" + property.getName() + "] != [" + this.memberPropertyName + + "]"); }
getList().add(property); property.setParentList(this); }
- /* TODO: GWT - * *//** - * @see org.rhq.core.domain.configuration.Property#writeExternal(java.io.ObjectOutput) - *//* - @Override - public void writeExternal(ObjectOutput out) throws IOException { - super.writeExternal(out); - out.writeObject(HibernateUtil.safeList(list)); - } - - *//** - * @see org.rhq.core.domain.configuration.Property#readExternal(java.io.ObjectInput) - *//* - @Override - @SuppressWarnings("unchecked") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - list = (List<Property>) in.readObject(); - } -*/ /** * NOTE: An PropertyList containing a null list is considered equal to a PropertyList containing an empty list. */ diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java index 90b391c..19e16c0 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java @@ -204,27 +204,6 @@ public class PropertyMap extends Property implements AbstractPropertyMap { return (PropertyMap) get(name); }
- /* TODO: GWT * - - //** - * @see org.rhq.core.domain.configuration.Property#readExternal(java.io.ObjectInput) - *//* - @Override - @SuppressWarnings("unchecked") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - map = (Map<String, Property>) in.readObject(); - } - - //** - * @see org.rhq.core.domain.configuration.Property#writeExternal(java.io.ObjectOutput) - *//* - @Override - public void writeExternal(ObjectOutput out) throws IOException { - super.writeExternal(out); - out.writeObject(HibernateUtil.safeMap(map)); - }*/ - /** * NOTE: An PropertyMap containing a null map is considered equal to a PropertyMap containing an empty map. */ diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertySimple.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertySimple.java index a4c4858..f8d4cea 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertySimple.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertySimple.java @@ -1,28 +1,28 @@ - /* - * 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.domain.configuration;
-import java.io.*; +import java.io.Serializable;
import javax.persistence.Column; import javax.persistence.DiscriminatorValue; @@ -174,8 +174,7 @@ public class PropertySimple extends Property implements Serializable { * * @param value */ - public void setLongValue(@Nullable - Long value) { + public void setLongValue(@Nullable Long value) { this.setValue(value); }
@@ -267,30 +266,6 @@ public class PropertySimple extends Property implements Serializable { this.unmaskedStringValue = unmaskedStringValue; }
-/* *//** - * @see org.rhq.core.domain.configuration.Property#readExternal(java.io.ObjectInput) - *//* - @Override - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - stringValue = (String) in.readObject(); - override = in.readBoolean(); - } - - *//** - * @see org.rhq.core.domain.configuration.Property#writeExternal(java.io.ObjectOutput) - *//* - @Override - public void writeExternal(ObjectOutput out) throws IOException { - super.writeExternal(out); - out.writeObject(stringValue); - if (override == null) { - out.writeBoolean(Boolean.FALSE); - } else { - out.writeBoolean(override); - } - }*/ - @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/AvailabilityReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/AvailabilityReport.java index 15b2613..a0015a6 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/AvailabilityReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/AvailabilityReport.java @@ -1,34 +1,33 @@ - /* - * 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.domain.discovery;
-import java.io.*; +import java.io.Externalizable; +import java.io.Serializable; import java.util.ArrayList; -import java.util.Date; import java.util.List; + import org.rhq.core.domain.measurement.Availability; -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.domain.resource.Resource;
/** * Contains a set of one or more {@link Availability} values used to indicate the statuses of a set of resources. Note @@ -134,46 +133,4 @@ public class AvailabilityReport implements Serializable {
return str.toString(); } - - /* public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(this.agentName); - out.writeBoolean(this.changesOnly); - - out.writeInt(availabilities.size()); - for (Availability availability : availabilities) { - out.writeInt(availability.getResource().getId()); - - if (availability.getAvailabilityType() != null) { - out.writeInt(availability.getAvailabilityType().ordinal()); - } else { - out.writeInt(-1); - } - - out.writeLong(availability.getStartTime().getTime()); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - this.agentName = (String) in.readObject(); - this.changesOnly = in.readBoolean(); - - int count = in.readInt(); - for (int i = 0; i < count; i++) { - int resourceId = in.readInt(); - - AvailabilityType at; - int avail = in.readInt(); - if (avail > -1) { - at = AvailabilityType.values()[avail]; - } else { - at = null; - } - - Date startTime = new Date(in.readLong()); - - Resource r = new Resource(resourceId); - Availability a = new Availability(r, startTime, at); - availabilities.add(a); - } - }*/ } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/ResourceSyncInfo.java b/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/ResourceSyncInfo.java index db3ce89..4bcc267 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/ResourceSyncInfo.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/ResourceSyncInfo.java @@ -22,9 +22,8 @@ */ package org.rhq.core.domain.discovery;
-import java.io.*; +import java.io.Serializable; import java.util.Collection; -import java.util.Set;
import javax.persistence.Column; import javax.persistence.Entity; @@ -104,21 +103,4 @@ public class ResourceSyncInfo implements Serializable { return childSyncInfos; }
- /* TODO: GWT - public void writeExternal(ObjectOutput out) throws IOException { - out.writeInt(id); - out.writeUTF(uuid); - out.writeLong(mtime); - out.writeInt(inventoryStatus.ordinal()); - out.writeObject(HibernateUtil.safeCollection(childSyncInfos)); - } - - @SuppressWarnings("unchecked") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - uuid = in.readUTF(); - mtime = in.readLong(); - inventoryStatus = InventoryStatus.values()[in.readInt()]; - childSyncInfos = (Set<ResourceSyncInfo>) in.readObject(); - }*/ } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/event/EventSource.java b/modules/core/domain/src/main/java/org/rhq/core/domain/event/EventSource.java index d339592..2424edb 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/event/EventSource.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/event/EventSource.java @@ -22,7 +22,7 @@ */ package org.rhq.core.domain.event;
-import java.io.*; +import java.io.Serializable; import java.util.HashSet; import java.util.Set;
@@ -158,23 +158,10 @@ public class EventSource implements Serializable {
@Override public String toString() { - return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1) + "[" + "id=" + this.id + ", " + "eventDefinition.name=" + return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".") + 1) + "[" + "id=" + + this.id + ", " + "eventDefinition.name=" + ((this.eventDefinition != null) ? this.eventDefinition.getName() : "null") + ", " + "resource.name=" + ((this.resource != null) ? this.resource.getName() : "null") + ", " + "location=" + this.location + "]";
} -/* - public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(this.eventDefinition); - out.writeInt((this.resource != null) ? this.resource.getId() : 0); - // this can be null when serializing a containing referencing Event, in which it is lazy loaded - out.writeUTF((null == this.location) ? "" : this.location); - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - this.eventDefinition = (EventDefinition) in.readObject(); - int resourceId = in.readInt(); - this.resource = new Resource(resourceId); - this.location = in.readUTF(); - }*/ } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java index 15cceb5..1933139 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java @@ -136,53 +136,4 @@ public class MeasurementReport implements Serializable { public void incrementCollectionTime(long collectionTime) { this.collectionTime += collectionTime; } - - /* TODO: GWT - public void writeExternal(ObjectOutput out) throws IOException { - out.writeInt(measurementNumericData.size()); - for (MeasurementDataNumeric datum : measurementNumericData) { - out.writeInt(datum.getScheduleId()); - out.writeLong(datum.getTimestamp()); - // We can serialize a null value as Double.NaN, since, semantically, both mean "no data available". - out.writeDouble((datum.getValue() != null) ? datum.getValue() : Double.NaN); - } - - out.writeInt(measurementTraitData.size()); - for (MeasurementDataTrait datum : measurementTraitData) { - out.writeInt(datum.getScheduleId()); - out.writeLong(datum.getTimestamp()); - String value = datum.getValue(); - out.writeUTF((value != null) ? value : ""); - } - - out.writeObject(this.callTimeData); - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - int count = in.readInt(); - for (int i = 0; i < count; i++) { - int scheduleId = in.readInt(); - long timestamp = in.readLong(); - double doubleValue = in.readDouble(); - measurementNumericData.add(new MeasurementDataNumeric(new MeasurementDataPK(timestamp, scheduleId), - doubleValue)); - } - - count = in.readInt(); - for (int i = 0; i < count; i++) { - int scheduleId = in.readInt(); - long timestamp = in.readLong(); - String stringValue = in.readUTF(); - - // This should never be null, but I'm paranoid - if (stringValue == null) { - stringValue = ""; - } - - measurementTraitData - .add(new MeasurementDataTrait(new MeasurementDataPK(timestamp, scheduleId), stringValue)); - } - - this.callTimeData = (Set<CallTimeData>) in.readObject(); - }*/ } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeDataValue.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeDataValue.java index e336ce6..c231bb7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeDataValue.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeDataValue.java @@ -22,7 +22,8 @@ */ package org.rhq.core.domain.measurement.calltime;
-import org.jetbrains.annotations.Nullable; +import java.io.Serializable; +import java.util.Date;
import javax.persistence.Column; import javax.persistence.Entity; @@ -36,8 +37,7 @@ import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table;
-import java.io.Serializable; -import java.util.Date; +import org.jetbrains.annotations.Nullable;
/** * Measurement data for a set of calls to a particular destination over a certain time span. @@ -181,30 +181,12 @@ public class CallTimeDataValue implements Serializable { this.maximum = callTime; } } -/* - public void writeExternal(ObjectOutput out) throws IOException { - out.writeLong(this.beginTime); - out.writeLong(this.endTime); - out.writeDouble(this.minimum); - out.writeDouble(this.maximum); - out.writeDouble(this.total); - out.writeLong(this.count); - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - this.beginTime = in.readLong(); - this.endTime = in.readLong(); - this.minimum = in.readDouble(); - this.maximum = in.readDouble(); - this.total = in.readDouble(); - this.count = in.readLong(); - }*/
@Override public String toString() { - return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".")+1) + "[" + "key=" + this.key + ", " + "beginTime=" - + new Date(this.beginTime) + ", " + "endTime=" - + new Date(this.endTime) + ", " + "minimum=" + this.minimum + ", " + "maximum=" - + this.maximum + ", " + "total=" + this.total + ", " + "count=" + this.count + "]"; + return this.getClass().getName().substring(this.getClass().getName().lastIndexOf(".") + 1) + "[" + "key=" + + this.key + ", " + "beginTime=" + new Date(this.beginTime) + ", " + "endTime=" + new Date(this.endTime) + + ", " + "minimum=" + this.minimum + ", " + "maximum=" + this.maximum + ", " + "total=" + this.total + ", " + + "count=" + this.count + "]"; } } \ No newline at end of file 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 6726bbb..71ccd30 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 @@ -1696,170 +1696,6 @@ public class Resource implements Comparable<Resource>, Serializable { return buffer.toString(); }
- /* public void writeExternal(ObjectOutput out) throws IOException { - ExternalizableStrategy.Subsystem strategy = ExternalizableStrategy.getStrategy(); - out.writeChar(strategy.id()); - - if (ExternalizableStrategy.Subsystem.REMOTEAPI == strategy) { - writeExternalRemote(out); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION == strategy) { - EntitySerializer.writeExternalRemote(this, out); - } else { - writeExternalAgent(out); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - char c = in.readChar(); - if (ExternalizableStrategy.Subsystem.REMOTEAPI.id() == c) { - readExternalRemote(in); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION.id() == c) { - EntitySerializer.readExternalRemote(this, in); - } else { - readExternalAgent(in); - } - } - - public void writeExternalAgent(ObjectOutput out) throws IOException { - // Note that a Resource may have been constructed with id only. Check for uninitialized fields. - out.writeInt(id); - out.writeUTF(uuid); - out.writeUTF((null == resourceKey) ? "" : resourceKey); - out.writeUTF((null == name) ? "" : name); - out.writeInt(inventoryStatus.ordinal()); - out.writeUTF((null == version) ? "" : version); - out.writeUTF((null == description) ? "" : description); - out.writeLong(ctime); - out.writeLong(mtime); - out.writeLong(itime); - - //Subject modifiedBy; - //Subject owner; - //String location; - out.writeObject(parentResource); - - if (null == resourceType) { - out.writeUTF(""); - out.writeUTF(""); - out.writeObject(null); - } else { - out.writeUTF(resourceType.getName()); - out.writeUTF(resourceType.getPlugin()); - out.writeObject(resourceType.getCategory()); - } - - // We make a copy of the childResources Set for two reasons: 1) to avoid calling writeObject() on the Set if it - // happens to be a Hibernate proxy (which would only ever be true on the Server side), and 2) to reduce the - // chances of a ConcurrentModificationException occurring in some other thread that is iterating the original Set. - out.writeObject((null == childResources) ? null : new LinkedHashSet<Resource>(childResources)); - - // Don't write plugin configs out if they are a lazy proxy - if (pluginConfiguration != null && pluginConfiguration.getClass().getName().contains("hibernate")) { - out.writeObject(null); - } else { - out.writeObject(pluginConfiguration); - } - - //Set<MeasurementSchedule> schedules = new LinkedHashSet<MeasurementSchedule>(); - //Agent agent; - //Set<ResourceGroup> resourceGroups = new HashSet<ResourceGroup>(); - } - - @SuppressWarnings("unchecked") - public void readExternalAgent(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - uuid = in.readUTF(); - resourceKey = in.readUTF(); - name = in.readUTF(); - inventoryStatus = InventoryStatus.values()[in.readInt()]; - version = in.readUTF(); - description = in.readUTF(); - ctime = in.readLong(); - mtime = in.readLong(); - itime = in.readLong(); - - //Subject modifiedBy; - //Subject owner; - //String location; - parentResource = (Resource) in.readObject(); - resourceType = new ResourceType(in.readUTF(), in.readUTF(), (ResourceCategory) in.readObject(), - (parentResource != null) ? parentResource.getResourceType() : null); - childResources = (Set<Resource>) in.readObject(); - - pluginConfiguration = (Configuration) in.readObject(); - } - - // It is assumed that the object is clean of Hibernate proxies (i.e. HibernateDetachUtility has been run if necessary) - public void writeExternalRemote(ObjectOutput out) throws IOException { - // Note that a Resource may have been constructed with id only. Check for uninitialized fields. - out.writeInt(id); - out.writeUTF(uuid); - out.writeUTF(resourceKey); - out.writeUTF(name); - out.writeInt(inventoryStatus.ordinal()); - out.writeUTF((null == version) ? "" : version); - out.writeUTF((null == description) ? "" : description); - out.writeLong(ctime); - out.writeLong(mtime); - out.writeLong(itime); - // not supplied by remote: modifiedBy - out.writeUTF((null == location) ? "" : location); - out.writeObject(resourceType); - // making a copy reduces chances of ConcurrentModificationException in a thread iterating the original - out.writeObject((null == childResources) ? null : new LinkedHashSet<Resource>(childResources)); - out.writeObject(parentResource); - out.writeObject(resourceConfiguration); - out.writeObject(pluginConfiguration); - out.writeObject(agent); - // not supplied by remote: alertDefinitions - // not supplied by remote: resourceConfigurationUpdates - // not supplied by remote: pluginConfigurationUpdates - // making a copy reduces chances of ConcurrentModificationException in a thread iterating the original - out.writeObject((null == implicitGroups) ? null : new LinkedHashSet<ResourceGroup>(implicitGroups)); - // making a copy reduces chances of ConcurrentModificationException in a thread iterating the original - out.writeObject((null == explicitGroups) ? null : new LinkedHashSet<ResourceGroup>(explicitGroups)); - // not supplied by remote: contentServiceRequests - // not supplied by remote: createChildResourceRequests - // not supplied by remote: deleteResourceRequests - // not supplied by remote: operationHistories - // not supplied by remote: installedPackages - // not supplied by remote: installedPackageHistory - // not supplied by remote: resourceRepos - // not supplied by remote: schedules - out.writeObject(availability); - out.writeObject(currentAvailability); - out.writeObject(resourceErrors); - // not supplied by remote: eventSources - out.writeObject(productVersion); - } - - @SuppressWarnings("unchecked") - public void readExternalRemote(ObjectInput in) throws IOException, ClassNotFoundException { - id = in.readInt(); - uuid = in.readUTF(); - resourceKey = in.readUTF(); - name = in.readUTF(); - inventoryStatus = InventoryStatus.values()[in.readInt()]; - version = in.readUTF(); - description = in.readUTF(); - ctime = in.readLong(); - mtime = in.readLong(); - itime = in.readLong(); - location = in.readUTF(); - resourceType = (ResourceType) in.readObject(); - childResources = (Set<Resource>) in.readObject(); - parentResource = (Resource) in.readObject(); - resourceConfiguration = (Configuration) in.readObject(); - pluginConfiguration = (Configuration) in.readObject(); - agent = (Agent) in.readObject(); - implicitGroups = (Set<ResourceGroup>) in.readObject(); - explicitGroups = (Set<ResourceGroup>) in.readObject(); - availability = (List<Availability>) in.readObject(); - currentAvailability = (ResourceAvailability) in.readObject(); - resourceErrors = (List<ResourceError>) in.readObject(); - productVersion = (ProductVersion) in.readObject(); - }*/ - public void afterUnmarshal(Object u, Object parent) { this.parentResource = (Resource) parent; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java index b3790fe..2a48bd2 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java @@ -307,15 +307,4 @@ public class ResourceSubCategory implements Comparable<ResourceSubCategory>, Ser return "ResourceSubCategory[id=" + id + ", name=" + name + "]"; }
- // public void writeExternal(ObjectOutput out) throws IOException - // { - // out.writeUTF(name); - // // out.writeUTF(plugin); - // } - - // public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException - // { - // name = in.readUTF(); - // // plugin = in.readUTF(); - // } } \ No newline at end of file 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 a94560d..079b8f5 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 @@ -820,86 +820,4 @@ public class ResourceType implements Serializable, Comparable<ResourceType> { + this.plugin + /*", parents=" + parents +*/"]"; }
- /* - TODO: GWT - public void writeExternal(ObjectOutput out) throws IOException { - ExternalizableStrategy.Subsystem strategy = ExternalizableStrategy.getStrategy(); - out.writeChar(strategy.id()); - - if (ExternalizableStrategy.Subsystem.REMOTEAPI == strategy) { - writeExternalRemote(out); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION == strategy) { - EntitySerializer.writeExternalRemote(this, out); - } else { - writeExternalAgent(out); - } - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - char c = in.readChar(); - if (ExternalizableStrategy.Subsystem.REMOTEAPI.id() == c) { - readExternalRemote(in); - } else if (ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION.id() == c) { - EntitySerializer.readExternalRemote(this, in); - } else { - readExternalAgent(in); - } - } - - public void writeExternalAgent(ObjectOutput out) throws IOException { - out.writeUTF(this.name); - out.writeUTF(this.plugin); - } - - public void readExternalAgent(ObjectInput in) throws IOException, ClassNotFoundException { - this.name = in.readUTF(); - this.plugin = in.readUTF(); - } - - public void writeExternalRemote(ObjectOutput out) throws IOException { - out.writeInt(this.id); - out.writeUTF(this.name); - out.writeUTF((null == this.description) ? "" : this.description); - out.writeObject(this.category); - out.writeObject(this.creationDataType); - out.writeObject(this.createDeletePolicy); - out.writeBoolean(this.supportsManualAdd); - out.writeBoolean(this.singleton); - out.writeUTF(this.plugin); - out.writeLong(this.ctime); - out.writeLong(this.mtime); - out.writeObject(this.subCategory); - out.writeObject(this.bundleType); - out.writeObject((null == childResourceTypes) ? null : new LinkedHashSet<ResourceType>(childResourceTypes)); - out.writeObject((null == parentResourceTypes) ? null : new LinkedHashSet<ResourceType>(parentResourceTypes)); - out.writeObject(pluginConfigurationDefinition); - out.writeObject(resourceConfigurationDefinition); - out.writeObject((null == metricDefinitions) ? null - : new LinkedHashSet<MeasurementDefinition>(metricDefinitions)); - out.writeObject((null == eventDefinitions) ? null : new LinkedHashSet<EventDefinition>(eventDefinitions)); - out.writeObject((null == operationDefinitions) ? null : new LinkedHashSet<OperationDefinition>( - operationDefinitions)); - out.writeObject((null == processScans) ? null : new LinkedHashSet<ProcessScan>(processScans)); - out.writeObject((null == packageTypes) ? null : new LinkedHashSet<PackageType>(packageTypes)); - out.writeObject((null == subCategories) ? null : new LinkedHashSet<ResourceSubCategory>(subCategories)); - out.writeObject((null == resources) ? null : new LinkedHashSet<Resource>(resources)); - out.writeObject((null == productVersions) ? null : new LinkedHashSet<ProductVersion>(productVersions)); - // not supplied by remote: helpText - } - - public void readExternalRemote(ObjectInput in) throws IOException, ClassNotFoundException { - this.id = in.readInt(); - this.name = in.readUTF(); - this.description = in.readUTF(); - this.category = (ResourceCategory) in.readObject(); - this.creationDataType = (ResourceCreationDataType) in.readObject(); - this.createDeletePolicy = (CreateDeletePolicy) in.readObject(); - this.supportsManualAdd = in.readBoolean(); - this.singleton = in.readBoolean(); - this.plugin = in.readUTF(); - this.ctime = in.readLong(); - this.mtime = in.readLong(); - } - */ - } diff --git a/modules/core/domain/src/main/java/org/rhq/core/server/ExternalizableStrategy.java b/modules/core/domain/src/main/java/org/rhq/core/server/ExternalizableStrategy.java index 48214a6..a43fcdc 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/server/ExternalizableStrategy.java +++ b/modules/core/domain/src/main/java/org/rhq/core/server/ExternalizableStrategy.java @@ -33,9 +33,8 @@ package org.rhq.core.server; public class ExternalizableStrategy {
public enum Subsystem { - AGENT((char) 1), // - REMOTEAPI((char) 2), // - REFLECTIVE_SERIALIZATION((char) 3); + AGENT((char) 1), // set bidirectionally for agent<--->server communication + REFLECTIVE_SERIALIZATION((char) 3); // set unidirectionally for both CLI-->server and WS-->server communication
private char id;
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/configuration/ConfigurationTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/configuration/ConfigurationTest.java index 32d0efb..f785e86 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/configuration/ConfigurationTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/configuration/ConfigurationTest.java @@ -34,7 +34,6 @@ import java.util.Set;
import org.testng.annotations.Test;
-import org.rhq.core.server.ExternalizableStrategy; import org.rhq.core.util.MessageDigestGenerator;
/** @@ -444,238 +443,4 @@ public class ConfigurationTest { return copy; }
- @Test - public void agentSerializationShouldCopyId() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertIdFieldSerialized(); - } - - @Test - public void reflectiveSerializationShouldNotCopyId() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertIdFieldSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyId() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertIdFieldSerialized(); - } - - private void assertIdFieldSerialized() throws Exception { - int id = -1; - - Configuration config = new Configuration(); - config.setId(id); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getId(), id, "Failed to properly serialize the id property"); - } - - @Test - public void agentSerializationShouldCopyPropertiesMap() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertPropertiesFieldIsSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyPropertiesMap() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertPropertiesFieldIsSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyPropertiesMap() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertPropertiesFieldIsSerialized(); - } - - private void assertPropertiesFieldIsSerialized() throws Exception { - Configuration config = new Configuration(); - config.put(new PropertySimple("x", "1")); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getMap(), config.getMap(), "Failed to property serialize the map property"); - for (Property property : serializedConfig.getProperties()) { - assertEquals(property.getConfiguration(), serializedConfig, - "Failed to update parent reference of property during serialization"); - } - } - - @Test - public void agentSerializationShouldCopyNotes() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertNotesFieldSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyNotes() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertNotesFieldSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyNotes() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertNotesFieldSerialized(); - } - - private void assertNotesFieldSerialized() throws Exception { - - Configuration config = new Configuration(); - config.setNotes("notes"); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getNotes(), config.getNotes(), "Failed to properly serialize the notes property"); - } - - @Test - public void agentSerializationShouldCopyVersion() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertVersionFieldIsSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyVersion() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertVersionFieldIsSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyVersion() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertVersionFieldIsSerialized(); - } - - private void assertVersionFieldIsSerialized() throws Exception { - Configuration config = new Configuration(); - config.setVersion(1L); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getVersion(), config.getVersion(), - "Failed to properly serialize the version property"); - } - - @Test - public void agentSerializationShouldCopyModifiedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertModifiedTimeIsSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyModifiedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertModifiedTimeIsSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyModifiedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertModifiedTimeIsSerialized(); - } - - private void assertModifiedTimeIsSerialized() throws Exception { - Configuration config = new Configuration(); - updateModifiedTime(config); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getModifiedTime(), config.getModifiedTime(), - "Failed to properly serialize the modifiedTime property"); - } - - @Test - public void agentSerializationShouldCopyCreatedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertCreatedTimeIsSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyCreatedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertCreatedTimeIsSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyCreatedTime() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertCreatedTimeIsSerialized(); - } - - private void assertCreatedTimeIsSerialized() throws Exception { - Configuration config = new Configuration(); - updateCreatedTime(config); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertEquals(serializedConfig.getCreatedTime(), config.getCreatedTime(), - "Failed to properly serialize the createdTime property"); - } - - @Test - public void agentSerializationShouldCopyRawConfigurations() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.AGENT); - - assertRawConfigurationsIsSerialized(); - } - - @Test - public void reflectiveSerializationShouldCopyRawConfigurations() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION); - - assertRawConfigurationsIsSerialized(); - } - - @Test - public void remoteAPISerializationShouldCopyRawConfigurations() throws Exception { - ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REMOTEAPI); - - assertRawConfigurationsIsSerialized(); - } - - private void assertRawConfigurationsIsSerialized() throws Exception { - Configuration config = new Configuration(); - config.addRawConfiguration(createRawConfiguration("/tmp/foo.txt")); - config.addRawConfiguration(createRawConfiguration("/tmp/bar.txt")); - - Configuration serializedConfig = TestUtil.serializeAndDeserialize(config); - - assertRawConfigurationsEquals(serializedConfig.getRawConfigurations(), config.getRawConfigurations(), - "Failed to properly serialize rawConfigurations property"); - for (RawConfiguration rawConfig : serializedConfig.getRawConfigurations()) { - assertEquals(rawConfig.getConfiguration(), serializedConfig, - "Failed to update parent reference of raw config during serialization"); - } - } - - private void updateModifiedTime(Configuration config) { - config.onUpdate(); - } - - private void updateCreatedTime(Configuration config) { - config.onPersist(); - } - }
commit 05c9f66dd64f0f6efd29ddbefbaf3b368cf723e7 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 15:10:29 2010 -0400
fix todos in ResourceSubCategory
* if enterprise wishes to find resources types via query, criteria objects should be used. this need has not arisen since the creation of the ResourceSubCategory.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java index 14fd30f..b3790fe 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceSubCategory.java @@ -119,7 +119,6 @@ public class ResourceSubCategory implements Comparable<ResourceSubCategory>, Ser * * @return the resource types that belong to this subcategory; the Set of types is sorted by name */ - // TODO enterprise may want to do this differently using a query @NotNull public Set<ResourceType> findTaggedResourceTypes() { ResourceType parentResourceType = findParentResourceType(); @@ -139,7 +138,6 @@ public class ResourceSubCategory implements Comparable<ResourceSubCategory>, Ser } }
- // TODO enterprise may want to do this differently using a query @NotNull public ResourceType findParentResourceType() { ResourceSubCategory subCategory = this; @@ -150,7 +148,6 @@ public class ResourceSubCategory implements Comparable<ResourceSubCategory>, Ser return subCategory.getResourceType(); }
- // TODO enterprise may want to do this differently using a query public boolean isCreatable() { for (ResourceType taggedResourceType : findTaggedResourceTypes()) { // if any resourceType is creatable then this subCategory is
commit e5295162b8c842e6955d713a82eb228912788e01 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 11:45:36 2010 -0400
fix todos in MeasurementOOB
* replace todos with ample explanation of the current limitations of the algorithm used to compute "problem" metrics, indicating what the issues are preventing further accuracy as well as how to overcome these limitations in the future.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementOOB.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementOOB.java index 0ec1ce0..c586c87 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementOOB.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementOOB.java @@ -130,6 +130,15 @@ public class MeasurementOOB {
public static final String DELETE_FOR_RESOURCES = "DeleteOOBForResurces";
+ /* + * (Jan 16, 2009) - The new OOB system uses a threshold to determine whether a metric is a "problem" or not. + * The current threshold is a static value - 0.1 - and does not change based on any characteristic + * of the metric data collected. Dynamic metrics, however, can have either naturally narrow or + * naturally wide baseline ranges; this makes the static threshold of 0.1 either too sensitive + * or not sensitive enough, respectively. The next improvement to the baseline system probably + * needs to use a sliding scale for this threshold, to more accurately characterize "problem" + * metrics across varying magnitudes of metric baseline deltas. + */ public static final String INSERT_QUERY = "" // + "INSERT INTO rhq_measurement_oob_tmp (oob_factor, schedule_id, time_stamp ) \n" // + " ( SELECT max(mx*100) as mxdiff, id, ? \n" // ?1 = begin @@ -139,7 +148,7 @@ public class MeasurementOOB { + " AND sc.id = b.schedule_id \n" // + " AND d.value > b.bl_max \n" // + " AND d.time_stamp = ? \n" // ?2 = begin - + " AND (b.bl_max - b.bl_min) > 0.1 \n" // TODO delta depending on max value ? + + " AND (b.bl_max - b.bl_min) > 0.1 \n" // + " AND (d.maxvalue - b.bl_max) >0 \n " // + " AND sc.enabled = %TRUE% \n" // + " AND sc.definition = def.id \n" // @@ -152,7 +161,7 @@ public class MeasurementOOB { + " AND sc.id = b.schedule_id \n" // + " AND d.value < b.bl_max \n" // + " AND d.time_stamp = ? \n" // ?3 = begin - + " AND (b.bl_max - b.bl_min) > 0.1 \n" // TODO delta depending on max value ? + + " AND (b.bl_max - b.bl_min) > 0.1 \n" // + " AND (b.bl_min - d.minvalue) >0 \n" // + " AND sc.enabled = %TRUE% \n" // + " AND sc.definition = def.id \n" //
commit a9c14fc3bd1619a7e45d4d204b04a1bd5e454182 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 11:03:31 2010 -0400
fix todo in PartitionEventType
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/PartitionEventType.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/PartitionEventType.java index c6462f5..2ec71db 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/PartitionEventType.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/PartitionEventType.java @@ -31,7 +31,7 @@ public enum PartitionEventType { AGENT_REGISTRATION(false), // Agent registers with server defined in setup, or previously connected server from server list. AGENT_CONNECT(false), // Agent connects to server on server list AGENT_SHUTDOWN(false), // Agent notifies server of agent shutdown - AGENT_LEAVE(false), // TODO (jshaughn) Not currently used, may work this into the suspect job logic + AGENT_LEAVE(false), // Not currently used - should this be worked into suspect agent logic?
SERVER_DELETION(true), // SERVER_COMPUTE_POWER_CHANGE(true), // Not yet implemented
commit e0412cb2f5c5695bcea883092f4f4cf58c7e9045 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 11:01:35 2010 -0400
fix todo in PageList
* change to throw new IllegalArgumentException instead of Log.warn, forcing callers to deal with invalid PageList state
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java index de663fc..2746172 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/PageList.java @@ -28,9 +28,6 @@ import java.util.Collection;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * Tracks the result set for a paginated data lookup. Includes the data and the total rows that are available. * @@ -64,7 +61,13 @@ public class PageList<E> extends ArrayList<E> implements Serializable { super(collection); this.totalSize = totalSize; if (collection.size() == 0 && totalSize > 0) { - // TODO: GWT LOG.warn("PageList was passed an empty collection but 'totalSize' was " + totalSize + ", " + pageControl); + /* + * this can be seen attempting to navigate to a non-existent page of the result set (e.g. page 10 in a + * collection of 3 items). The mechanism controlling pagination at the user level should be notified of + * this, so it can decide how to gracefully handle this condition. + */ + throw new IllegalArgumentException("PageList was passed an empty collection but 'totalSize' was " + + totalSize + ", " + pageControl); } this.isUnbounded = false; this.pageControl = pageControl;
commit 6d93007453a7cda00ca333df6d52f06132d7ba75 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 10:39:59 2010 -0400
fix todos on Property & PropertyGroupDefinition entities
* Property - remove method no longer used, all callers use setErrorMessage(String) and leverage ThrowableUtil.getStackAsString * PropertyGroupDefinition - fix jdoc and remove unnecessary todo
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java index 67d1df4..3518159 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Property.java @@ -239,21 +239,6 @@ public class Property implements Serializable, DeepCopyable<Property>, Comparabl this.errorMessage = (errorMessage != null) ? errorMessage.trim() : errorMessage; }
- /** - * Convienence method that sets the error message to the given throwable's stack trace dump. If the given throwable - * is <code>null</code>, the error message will be set to <code>null</code> as if passing <code>null</code> to - * {@link #setErrorMessage(String)}. - * - * @param t throwable whose message and stack trace will make up the error message (may be <code>null</code>) - */ - public void setErrorMessageFromThrowable(Throwable t) { - if (t != null) { - setErrorMessage(t.toString()); // TODO: would like this to be the full stack, but GWT doesn't make it easy so just set this to the throwable msg - } else { - setErrorMessage(null); - } - } - @Override public boolean equals(Object obj) { if (this == obj) { diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java index 3e093aa..90b391c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/PropertyMap.java @@ -22,22 +22,21 @@ */ package org.rhq.core.domain.configuration;
-import org.hibernate.annotations.Cascade; -import org.hibernate.annotations.CascadeType; -import org.jetbrains.annotations.NotNull; +import java.util.LinkedHashMap; +import java.util.Map;
import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.MapKey; import javax.persistence.OneToMany; -import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement;
-import java.util.LinkedHashMap; -import java.util.Map; +import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.CascadeType; +import org.jetbrains.annotations.NotNull;
/** * Holds a map of child {@link Property properties}. This can hold any number of properties, including additional lists @@ -205,26 +204,26 @@ public class PropertyMap extends Property implements AbstractPropertyMap { return (PropertyMap) get(name); }
- /* TODO: GWT * + /* TODO: GWT *
- //** - * @see org.rhq.core.domain.configuration.Property#readExternal(java.io.ObjectInput) - *//* - @Override - @SuppressWarnings("unchecked") - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - map = (Map<String, Property>) in.readObject(); - } + //** + * @see org.rhq.core.domain.configuration.Property#readExternal(java.io.ObjectInput) + *//* + @Override + @SuppressWarnings("unchecked") + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + super.readExternal(in); + map = (Map<String, Property>) in.readObject(); + }
- *//** - * @see org.rhq.core.domain.configuration.Property#writeExternal(java.io.ObjectOutput) - *//* - @Override - public void writeExternal(ObjectOutput out) throws IOException { - super.writeExternal(out); - out.writeObject(HibernateUtil.safeMap(map)); - }*/ + //** + * @see org.rhq.core.domain.configuration.Property#writeExternal(java.io.ObjectOutput) + *//* + @Override + public void writeExternal(ObjectOutput out) throws IOException { + super.writeExternal(out); + out.writeObject(HibernateUtil.safeMap(map)); + }*/
/** * NOTE: An PropertyMap containing a null map is considered equal to a PropertyMap containing an empty map. diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyGroupDefinition.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyGroupDefinition.java index daf4ef3..fcd019c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyGroupDefinition.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyGroupDefinition.java @@ -130,7 +130,7 @@ public class PropertyGroupDefinition implements Serializable { }
/** - * Two groups are the same if they are identical or share the same name TODO ??? + * Two groups are the same if they have the identical object references or names. */ @Override public boolean equals(Object o) {
commit 43f68973f1d67d052d2e8b30076a7acf749669d1 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 10:23:39 2010 -0400
fix todos in ResourceError
* remove setDetailFromThrowable and constructor that calls it * update callers using the deleted constructor to call other existing one ** leverage ThrowableUtil.getStackAsString as a replacement for setDetailFromThrowable
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceError.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceError.java index 22f57dc..5738e74 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceError.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceError.java @@ -22,9 +22,7 @@ */ package org.rhq.core.domain.resource;
-import java.io.PrintWriter; import java.io.Serializable; -import java.io.StringWriter; import java.util.Date;
import javax.persistence.Column; @@ -114,24 +112,6 @@ public class ResourceError implements Serializable { setTimeOccurred(timeOccurred); }
- /** - * Constructor for {@link ResourceError} that uses {@link #setDetailFromThrowable(Throwable)} to convert the given - * exception to an error message. - * - * @param resource the resource that is associated with the error that occurred - * @param errorType identifies this kind of error this represents - * @param exception exception whose stack will be used as this object's error message - * @param timeOccurred the epoch time when the error occurred - */ - public ResourceError(@NotNull Resource resource, @NotNull ResourceErrorType errorType, - @NotNull Throwable exception, long timeOccurred) { - setResource(resource); - setErrorType(errorType); - setSummary(exception.getLocalizedMessage()); - setDetailFromThrowable(exception); - setTimeOccurred(timeOccurred); - } - public int getId() { return id; } @@ -176,26 +156,6 @@ public class ResourceError implements Serializable { this.detail = detail; }
- /** - * Convenience method that sets the error message to the given throwable's stack trace. - * - * @param t throwable whose message and stack trace will make up the error message (must not be <code>null</code>) - * - * @throws NullPointerException if <code>t</code> is <code>null</code> - */ - public void setDetailFromThrowable(@NotNull Throwable t) { - //noinspection ConstantConditions - if (t == null) { - throw new IllegalArgumentException("t == null"); - } - - /* TODO: GWT - StringWriter stringWriter = new StringWriter(); - t.printStackTrace(new PrintWriter(stringWriter)); - String stackTrace = stringWriter.toString(); - setDetail(stackTrace);*/ - } - public long getTimeOccurred() { return timeOccurred; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java index b1e39f8..e623cb0 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java @@ -43,6 +43,7 @@ import org.rhq.core.domain.resource.ResourceErrorType; import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState; import org.rhq.core.pc.util.FacetLockType; import org.rhq.core.pluginapi.availability.AvailabilityFacet; +import org.rhq.core.util.exception.ThrowableUtil;
/** * Runs a periodic scan for resource availability. @@ -204,8 +205,8 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo } } } catch (Throwable t) { - ResourceError resourceError = new ResourceError(resource, ResourceErrorType.AVAILABILITY_CHECK, t, - System.currentTimeMillis()); + ResourceError resourceError = new ResourceError(resource, ResourceErrorType.AVAILABILITY_CHECK, t + .getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis()); this.inventoryManager.sendResourceErrorToServer(resourceError); // TODO GH: Put errors in report, rather than sending them to the Server separately. if (log.isDebugEnabled()) { diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 351f751..0259c69 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1597,8 +1597,8 @@ public class InventoryManager extends AgentService implements ContainerService, resource.setConnected(false); // invalid plugin configuration infers the resource component is disconnected // Give the server-side an error message describing the connection failure that can be // displayed on the resource's Inventory page. - ResourceError resourceError = new ResourceError(resource, ResourceErrorType.INVALID_PLUGIN_CONFIGURATION, t, - System.currentTimeMillis()); + ResourceError resourceError = new ResourceError(resource, ResourceErrorType.INVALID_PLUGIN_CONFIGURATION, t + .getLocalizedMessage(), ThrowableUtil.getStackAsString(t), System.currentTimeMillis()); return sendResourceErrorToServer(resourceError); }
commit 8187acfced4dfd6b72a0ef5ab4d7d7f162bba46e Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:34:00 2010 -0400
fix todos on MeasurementNumericValuesAndUnits and MeasurementStringValuesAndUnits
* since toString methods aren't called, todos can be removed
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementNumericValueAndUnits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementNumericValueAndUnits.java index 60e5285..12f9e49 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementNumericValueAndUnits.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementNumericValueAndUnits.java @@ -1,28 +1,28 @@ - /* - * 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.domain.measurement.composite;
- import org.rhq.core.domain.measurement.MeasurementUnits; +import org.rhq.core.domain.measurement.MeasurementUnits;
public class MeasurementNumericValueAndUnits implements MeasurementValueAndUnits { /* @@ -51,9 +51,7 @@ public class MeasurementNumericValueAndUnits implements MeasurementValueAndUnits return units; }
- /** Equivalent to MeasurementConverter.format(value, units, true) */ - @Override public String toString() { - return value + " " + units; // TODO: GWT MeasurementConverter.format(value, units, true); + return value + " " + units; } } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementStringValueAndUnits.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementStringValueAndUnits.java index 41dab1c..75c19b1 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementStringValueAndUnits.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementStringValueAndUnits.java @@ -1,30 +1,30 @@ - /* - * 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.domain.measurement.composite;
- import org.rhq.core.domain.measurement.MeasurementUnits; +import java.io.Serializable;
- import java.io.Serializable; +import org.rhq.core.domain.measurement.MeasurementUnits;
public class MeasurementStringValueAndUnits implements MeasurementValueAndUnits, Serializable {
@@ -47,8 +47,7 @@ public class MeasurementStringValueAndUnits implements MeasurementValueAndUnits, return units; }
- @Override public String toString() { - return value + " " + units; // TODO: GWT MeasurementConverter.format(getValue(), getUnits()); + return value + " " + units; } } \ No newline at end of file
commit 95573c033c4d96af460dac333e3f46022507c2d2 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:22:32 2010 -0400
fix todos on MeasurementSchedule
* system currentlysupports @OneToOne for schedules->baseline, remove unnecessary todo
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementSchedule.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementSchedule.java index b4e08de..62b2bd5 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementSchedule.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementSchedule.java @@ -213,7 +213,6 @@ public class MeasurementSchedule implements Serializable { * calculated for the first time (a merge-persist cascade), or have it updated at some later point in time (a * merge-merge cascade). */ - // TODO should this be @OneToMany or OneToOne // Remove now performed by bulk delete @OneToOne(mappedBy = "schedule", cascade = { CascadeType.MERGE }, fetch = FetchType.LAZY) private MeasurementBaseline baseline;
commit 8827910cf8f3aa5726da1186ad3ef3689c48a2b2 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:20:48 2010 -0400
fix todos on MeasurementReport
* use synchronized modifier on methods that access unprotected collections in a threaded environment
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java index 5514013..15cceb5 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementReport.java @@ -22,14 +22,14 @@ */ package org.rhq.core.domain.measurement;
-import org.rhq.core.domain.measurement.calltime.CallTimeData; - -import org.jetbrains.annotations.NotNull; - import java.io.Serializable; import java.util.LinkedHashSet; import java.util.Set;
+import org.jetbrains.annotations.NotNull; + +import org.rhq.core.domain.measurement.calltime.CallTimeData; + /** * A report of measurement information. When a plugin collects measurement data that is emitted from a monitored * resource, it will store that measurement data in an instance of this type. @@ -42,17 +42,14 @@ import java.util.Set; public class MeasurementReport implements Serializable { private static final long serialVersionUID = 1;
- /* TODO: GWT - private Set<MeasurementDataNumeric> measurementNumericData = Collections.synchronizedSet(new LinkedHashSet<MeasurementDataNumeric>()); - private Set<MeasurementDataTrait> measurementTraitData = Collections.synchronizedSet(new LinkedHashSet<MeasurementDataTrait>()); - private Set<CallTimeData> callTimeData = Collections.synchronizedSet(new LinkedHashSet<CallTimeData>()); - */ - + /* + * instead of using synchronized collection wrappers - which won't GWT-compile - we can use the synchronized + * modifier on the various methods that access these collections + */ private Set<MeasurementDataNumeric> measurementNumericData = new LinkedHashSet<MeasurementDataNumeric>(); private Set<MeasurementDataTrait> measurementTraitData = new LinkedHashSet<MeasurementDataTrait>(); private Set<CallTimeData> callTimeData = new LinkedHashSet<CallTimeData>();
- private long collectionTime;
/** @@ -62,10 +59,8 @@ public class MeasurementReport implements Serializable { * * @param value the measurement data to be added */ - public void addData(MeasurementDataNumeric value) { - if (!measurementNumericData.add(value)) { - // TODO: GWT LOG.info("Measurement collected twice, second value ignored: " + value); - } + public synchronized void addData(MeasurementDataNumeric value) { + measurementNumericData.add(value); // note, duplicates will be silently ignored }
/** @@ -75,10 +70,8 @@ public class MeasurementReport implements Serializable { * * @param value the measurement data to be added */ - public void addData(MeasurementDataTrait value) { - if (!measurementTraitData.add(value)) { - // TODO: GWT LOG.info("Measurement collected twice, second value ignored: " + value); - } + public synchronized void addData(MeasurementDataTrait value) { + measurementTraitData.add(value); // note, duplicates will be silently ignored }
/** @@ -88,7 +81,7 @@ public class MeasurementReport implements Serializable { * * @param data the call-time data to be added */ - public void addData(CallTimeData data) { + public synchronized void addData(CallTimeData data) { this.callTimeData.add(data); }
@@ -98,7 +91,7 @@ public class MeasurementReport implements Serializable { * * @return the list of all the numeric data items in this report */ - public Set<MeasurementDataNumeric> getNumericData() { + public synchronized Set<MeasurementDataNumeric> getNumericData() { return measurementNumericData; }
@@ -108,7 +101,7 @@ public class MeasurementReport implements Serializable { * * @return the list of all the trait data items in this report */ - public Set<MeasurementDataTrait> getTraitData() { + public synchronized Set<MeasurementDataTrait> getTraitData() { return measurementTraitData; }
@@ -119,7 +112,7 @@ public class MeasurementReport implements Serializable { * @return the list of all the call-time data items in this report */ @NotNull - public Set<CallTimeData> getCallTimeData() { + public synchronized Set<CallTimeData> getCallTimeData() { return callTimeData; }
@@ -128,7 +121,7 @@ public class MeasurementReport implements Serializable { * * @return the total number of data items (numeric metrics, traits, or call-time datums) in this report */ - public long getDataCount() { + public synchronized long getDataCount() { return this.measurementNumericData.size() + this.measurementTraitData.size() + this.callTimeData.size(); }
commit 542021e945b78f890ff32815c4b9c0c6401c8b1e Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:08:53 2010 -0400
fix todos in MesaurementDataNumericXX entities
* remove GET_NUM_AGGREGATE_MULTI queries, they are legacy and currently unused
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java index 07f25b0..33cef49 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1D.java @@ -1,28 +1,29 @@ - /* - * 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.domain.measurement;
import java.io.Serializable; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.NamedQueries; @@ -35,19 +36,14 @@ import javax.persistence.Table; * @author Greg Hinkle */ @Entity -@NamedQueries( { - @NamedQuery(name = MeasurementDataNumeric1D.GET_NUM_AGGREGATE, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max) " - + "FROM MeasurementDataNumeric1D nmd " - + "WHERE nmd.id.scheduleId = :schedId AND nmd.id.timestamp BETWEEN :start AND :end"), - @NamedQuery(name = MeasurementDataNumeric1D.GET_NUM_AGGREGATE_MULTI, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max),sum(nmd.value) " // TODO does sum() make any sense ? - + "FROM MeasurementDataNumeric1D nmd " - + "WHERE nmd.schedule IN (:schedules) AND nmd.id.timestamp BETWEEN :start AND :end") }) +@NamedQueries( { @NamedQuery(name = MeasurementDataNumeric1D.GET_NUM_AGGREGATE, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max) " + + "FROM MeasurementDataNumeric1D nmd " + + "WHERE nmd.id.scheduleId = :schedId AND nmd.id.timestamp BETWEEN :start AND :end") }) @Table(name = "RHQ_MEASUREMENT_DATA_NUM_1D") public class MeasurementDataNumeric1D extends MeasurementData implements Serializable { private static final long serialVersionUID = 1L;
public static final String GET_NUM_AGGREGATE = "MeasurementDataNumeric1D.getNumAggregate"; - public static final String GET_NUM_AGGREGATE_MULTI = "MeasurementDataNumeric1D.getNumAggregateMulti";
@Column(precision = 24, scale = 3) private Double value; @@ -77,7 +73,6 @@ public class MeasurementDataNumeric1D extends MeasurementData implements Seriali
@Override public String toString() { - return "MeasurementDataNumeric1D[" + "average=[" + value + "], " - + super.toString() + "]"; + return "MeasurementDataNumeric1D[" + "average=[" + value + "], " + super.toString() + "]"; } } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java index 1746ac1..1b75d3f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric1H.java @@ -1,28 +1,29 @@ - /* - * 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.domain.measurement;
import java.io.Serializable; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.NamedQueries; @@ -35,16 +36,11 @@ import javax.persistence.Table; * @author Greg Hinkle */ @Entity -@NamedQueries( { @NamedQuery(name = MeasurementDataNumeric1H.GET_NUM_AGGREGATE_MULTI, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max),sum(nmd.value) " // TODO does sum() make any sense ? - + "FROM MeasurementDataNumeric1H nmd " - + "WHERE nmd.schedule IN (:schedules) AND nmd.id.timestamp BETWEEN :start AND :end") , - @NamedQuery(name=MeasurementDataNumeric1H.GET_MAX_TIMESTAMP, query = "SELECT max(nmd.id.timestamp) FROM MeasurementDataNumeric1H nmd")}) +@NamedQueries( { @NamedQuery(name = MeasurementDataNumeric1H.GET_MAX_TIMESTAMP, query = "SELECT max(nmd.id.timestamp) FROM MeasurementDataNumeric1H nmd") }) @Table(name = "RHQ_MEASUREMENT_DATA_NUM_1H") public class MeasurementDataNumeric1H extends MeasurementData implements Serializable { private static final long serialVersionUID = 1L;
- public static final String GET_NUM_AGGREGATE_MULTI = "MeasurementDataNumeric1H.getNumAggregateMulti"; - public static final String GET_MAX_TIMESTAMP = "MeasurementDataNumeric1H.getMaxTimestamp";
@Column(precision = 24, scale = 3) @@ -74,7 +70,6 @@ public class MeasurementDataNumeric1H extends MeasurementData implements Seriali
@Override public String toString() { - return "MeasurementDataNumeric1H[" + "average=[" + value + "], " - + super.toString() + "]"; + return "MeasurementDataNumeric1H[" + "average=[" + value + "], " + super.toString() + "]"; } } \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java index 414c46f..366d21f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/MeasurementDataNumeric6H.java @@ -1,34 +1,34 @@ - /* - * 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.domain.measurement;
- import javax.persistence.Column; - import javax.persistence.Entity; - import javax.persistence.NamedQueries; - import javax.persistence.NamedQuery; - import javax.persistence.Table; +import java.io.Serializable;
- import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Table;
/** * Subclass for numerical measurement data @@ -36,19 +36,14 @@ package org.rhq.core.domain.measurement; * @author Greg Hinkle */ @Entity -@NamedQueries( { - @NamedQuery(name = MeasurementDataNumeric6H.GET_NUM_AGGREGATE, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max) " - + "FROM MeasurementDataNumeric6H nmd " - + "WHERE nmd.id.scheduleId = :schedId AND nmd.id.timestamp BETWEEN :start AND :end"), - @NamedQuery(name = MeasurementDataNumeric6H.GET_NUM_AGGREGATE_MULTI, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max),sum(nmd.value) " // TODO does sum() make any sense ? - + "FROM MeasurementDataNumeric6H nmd " - + "WHERE nmd.schedule IN (:schedules) AND nmd.id.timestamp BETWEEN :start AND :end") }) +@NamedQueries( { @NamedQuery(name = MeasurementDataNumeric6H.GET_NUM_AGGREGATE, query = "SELECT min(nmd.min), avg(nmd.value), max(nmd.max) " + + "FROM MeasurementDataNumeric6H nmd " + + "WHERE nmd.id.scheduleId = :schedId AND nmd.id.timestamp BETWEEN :start AND :end") }) @Table(name = "RHQ_MEASUREMENT_DATA_NUM_6H") public class MeasurementDataNumeric6H extends MeasurementData implements Serializable { private static final long serialVersionUID = 1L;
public static final String GET_NUM_AGGREGATE = "MeasurementDataNumeric6H.getNumAggregate"; - public static final String GET_NUM_AGGREGATE_MULTI = "MeasurementDataNumeric6H.getNumAggregateMulti";
@Column(precision = 24, scale = 3) private Double value; @@ -78,7 +73,6 @@ public class MeasurementDataNumeric6H extends MeasurementData implements Seriali
@Override public String toString() { - return "MeasurementDataNumeric6H[" + "average=[" + value + "], " - + super.toString() + "]"; + return "MeasurementDataNumeric6H[" + "average=[" + value + "], " + super.toString() + "]"; } } \ No newline at end of file
commit 27437a39bd9d13b4d3a52e7c17b617088edeaf36 Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:03:25 2010 -0400
fix todos on InventoryStatus
* add necessary jdoc to this enum
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventoryStatus.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventoryStatus.java index b3d01db..16d21ab 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventoryStatus.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/InventoryStatus.java @@ -27,10 +27,30 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlEnum;
/** - * Represents a resource's current inventory status. TODO: Javadoc what the different statuses mean. + * Represents a resource's current inventory status. */ @XmlEnum @XmlAccessorType(XmlAccessType.FIELD) public enum InventoryStatus { + /** + * <ul> + * <li>NEW: Auto-discovered but not yet imported into the inventory.</li> + * + * <li>IGNORED: Auto-discovered but explicitly moved to a state that will suppress it from showing up in future + * discoveries. Resources in this state will not be shown in the inventory browser.</li> + * + * <li>COMMITTED: Resources in this state will be visible in the inventory browser. The act of importing + * resources changes their state from NEW to COMMITTED. Note: resources that are factory-created + * or manually added will also appear in the inventory browser and, thus, will be COMMITTED.</li> + * + * <li>DELETED: Resources can be removed from the remote box, which will flip their status to DELETED to suppress + * them from showing up in the inventory browser.</li> + * + * <li>UNINVENTORIED: Resources can be removed from the inventory. Since this is an expensive operation, these + * resources are temporarily marked as UNINVENTORIED which will suppress them from showing up + * in the inventory browser. Then, in the background, all history will be purged for these + * resources, after which they are removed from the database completely.</li> + * </ul> + */ NEW, IGNORED, COMMITTED, DELETED, UNINVENTORIED } \ No newline at end of file
commit 108c57fd7ac5334f81e79e387b0921d0be9cb56b Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 01:02:47 2010 -0400
fix todos in GroupPluginConfigurationUpdate and GroupResourceConfigurationUpdate
* remove todo but keep statement from ips, which is essentially correct
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupPluginConfigurationUpdate.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupPluginConfigurationUpdate.java index 74e7b85..a7d2f39 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupPluginConfigurationUpdate.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupPluginConfigurationUpdate.java @@ -72,10 +72,13 @@ public class GroupPluginConfigurationUpdate extends AbstractGroupConfigurationUp
public GroupPluginConfigurationUpdate(ResourceGroup group, String subjectName) { super(group, subjectName); - //this.configuration = groupConfiguration.deepCopy(false); - // TODO (ips, 02/13/09): This is a temporary workaround - we don't really need to store a Configuration at all, - // since it can be recalculated from the member configs when needed, but the AbstractConfigurationUpdate - // base class requires the configuration field to be non-null. + /* + * this.configuration = groupConfiguration.deepCopy(false); + * + * (ips, 02/13/09): This is a temporary workaround - we don't really need to store a Configuration at all, + * since it can be recalculated from the member configs when needed, but the AbstractConfigurationUpdate + * base class requires the configuration field to be non-null. + */ this.configuration = new Configuration(); }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupResourceConfigurationUpdate.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupResourceConfigurationUpdate.java index c601196..38a298c 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupResourceConfigurationUpdate.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/group/GroupResourceConfigurationUpdate.java @@ -68,9 +68,13 @@ public class GroupResourceConfigurationUpdate extends AbstractGroupConfiguration
public GroupResourceConfigurationUpdate(ResourceGroup group, String subjectName) { super(group, subjectName); - // TODO (ips, 02/13/09): This is a temporary workaround - we don't really need to store a Configuration at all, - // since it can be recalculated from the member configs when needed, but the AbstractConfigurationUpdate - // base class requires the configuration field to be non-null. + /* + * this.configuration = groupConfiguration.deepCopy(false); + * + * (ips, 02/13/09): This is a temporary workaround - we don't really need to store a Configuration at all, + * since it can be recalculated from the member configs when needed, but the AbstractConfigurationUpdate + * base class requires the configuration field to be non-null. + */ this.configuration = new Configuration(); }
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/InventoryReportResponse.java b/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/InventoryReportResponse.java deleted file mode 100644 index 30b317a..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/discovery/InventoryReportResponse.java +++ /dev/null @@ -1,58 +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, 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.discovery; - -import java.io.Serializable; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * This report is sent in response to an InventoryReport being sent to the server. It tells the agent what the persistent - * resource ids are. TODO GH: This could also be used for a periodic sync when things get out of whack. (The collection, - * transmission and persistence of inventory is not transactional between the server and agent) - * - * @author Greg Hinkle - */ -@Deprecated -public class InventoryReportResponse implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * Maps the agent declared uuid to the resource's true "id" - */ - private Map<String, Integer> uuidToIntegerMapping = new LinkedHashMap<String, Integer>(); - - public Map<String, Integer> getUuidToIntegerMapping() { - return uuidToIntegerMapping; - } - - public void setUuidToIntegerMapping(Map<String, Integer> uuidToIntegerMapping) { - this.uuidToIntegerMapping = uuidToIntegerMapping; - } - - public void addIdMapping(String uuid, Integer persistentId) { - this.uuidToIntegerMapping.put(uuid, persistentId); - } - - -} \ No newline at end of file
commit cc4e3fa86c91942e77e9bef1770000ec99bfd68d Author: Joseph Marques joseph@redhat.com Date: Thu Oct 7 00:05:26 2010 -0400
fix todos in Group
* remove location field - it was only exposed in the struts-based UI, so it hasn't been seen in years anyway * dbsetup and db-upgrade bits * removed or commented out current and legacy uses of it
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 1ce883c..379c31f 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -22,7 +22,7 @@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.99</db.schema.version> + <db.schema.version>2.100</db.schema.version> </properties>
<dependencies> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml index 5d89c2d..48f9f2a 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml @@ -155,7 +155,6 @@ <!-- Max bytes for Oracle Varchar2 to accommodate large cluster keys --> <column name="NAME" required="true" size="4000" type="VARCHAR2"/> <column name="DESCRIPTION" size="100" type="VARCHAR2"/> - <column name="LOCATION" required="false" size="100" type="VARCHAR2"/> <column name="RESOURCE_TYPE_ID" type="INTEGER" references="RHQ_RESOURCE_TYPE"/> <!-- Compatible groups only --> <column name="CTIME" type="LONG"/> 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 d6fe7bc..b462cfa 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3250,6 +3250,10 @@ <schema-alterColumn table="RHQ_ALERT_CONDITION_LOG" column="VALUE" nullable="FALSE" /> </schemaSpec>
+ <schemaSpec version="2.100"> + <!-- location was only exposed in the struts-based UI, so it hasn't been seen in years anyway --> + <schema-deleteColumn table="RHQ_RESOURCE_GROUP" column="LOCATION" /> + </schemaSpec> </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/Group.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/Group.java index 4a15ff4..5cc2714 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/Group.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/Group.java @@ -47,9 +47,6 @@ public abstract class Group implements Serializable { @Column(name = "DESCRIPTION") private String description;
- @Column(name = "LOCATION") - private String location; // TODO (ips): I don't think this field makes sense for groups. - @Column(name = "CTIME") private Long ctime;
@@ -84,14 +81,6 @@ public abstract class Group implements Serializable { this.description = description; }
- public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - public Long getCtime() { return ctime; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java index 2c3f364..2027fd2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/summary/OverviewView.java @@ -164,42 +164,6 @@ public class OverviewView extends LocatableVLayout { } formItems.add(descriptionItem);
- final FormItem locationItem = (dynamic) ? new StaticTextItem() : new TogglableTextItem(); - locationItem.setName("location"); - locationItem.setTitle("Location"); - locationItem.setValue(group.getLocation()); - if (locationItem instanceof TogglableTextItem) { - final TogglableTextItem togglableLocationItem = (TogglableTextItem) locationItem; - togglableLocationItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newLocation) { - final String oldLocation = group.getLocation(); - if (newLocation.equals(oldLocation)) { - return; - } - group.setLocation(newLocation); - OverviewView.this.resourceGroupService.updateResourceGroup(group, false, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - "Failed to change location of Resource group with id " + group.getId() + " from "" - + oldLocation + "" to "" + newLocation + "".", caught); - // We failed to update it on the Server, so change back the ResourceGroup and the form item - // to the original value. - group.setLocation(oldLocation); - locationItem.setValue(oldLocation); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Location of Resource group with id " + group.getId() - + " was changed from "" + oldLocation + "" to "" + newLocation + "".", - Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(locationItem); - StaticTextItem dynamicItem = new StaticTextItem("dynamic", "Dynamic?"); dynamicItem.setValue(dynamic ? "yes" : "no"); formItems.add(dynamicItem); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java index 6b4664a..61c1cc1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/wizard/GroupCreateStep.java @@ -57,12 +57,9 @@ public class GroupCreateStep extends AbstractWizardStep { TextAreaItem description = new AutoFitTextAreaItem("description", "Description"); description.setWidth(300);
- TextItem location = new TextItem("location", "Location"); - location.setWidth(300); - CheckboxItem recursive = new CheckboxItem("recursive", "Recursive");
- form.setFields(name, description, location, recursive); + form.setFields(name, description, recursive); }
return form; @@ -79,7 +76,6 @@ public class GroupCreateStep extends AbstractWizardStep { public ResourceGroup getGroup() { ResourceGroup group = new ResourceGroup(form.getValueAsString("name")); group.setDescription(form.getValueAsString("description")); - group.setLocation(form.getValueAsString("location")); group.setRecursive(form.getValue("recursive") != null ? true : false);
return group; diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/group/ResourceGroupUIBean.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/group/ResourceGroupUIBean.java index cb15696..b2cda55 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/group/ResourceGroupUIBean.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/inventory/group/ResourceGroupUIBean.java @@ -118,10 +118,6 @@ public class ResourceGroupUIBean { return this.resourceGroup.getModifiedBy(); }
- public String getLocation() { - return this.resourceGroup.getLocation(); - } - public Boolean getRecursive() { return this.resourceGroup.isRecursive(); } diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java index 2cca7c0..c222819 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/GroupForm.java @@ -308,7 +308,7 @@ public class GroupForm extends BaseValidatorForm { public void loadResourceGroup(ResourceGroup group) { this.name = group.getName(); this.description = group.getDescription(); - this.location = group.getLocation(); + this.location = ""; this.groupId = group.getId(); }
@@ -321,9 +321,11 @@ public class GroupForm extends BaseValidatorForm { group.setDescription(description); }
+ /* if (location != null) { group.setLocation(location); } + */ }
public boolean isRecursive() { diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/NewGroupAction.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/NewGroupAction.java index f41b148..affa42a 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/NewGroupAction.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/action/resource/group/inventory/NewGroupAction.java @@ -94,7 +94,7 @@ public class NewGroupAction extends BaseAction {
try { newGroup.setDescription(description); - newGroup.setLocation(location); + //newGroup.setLocation(location); newGroup.setRecursive(recursive);
log.trace("creating group [" + newForm.getName() + "]" + " with attributes " + newForm); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/jaxb/adapter/ResourceGroupAdapter.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/jaxb/adapter/ResourceGroupAdapter.java index ca8d4df..a6fedea 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/jaxb/adapter/ResourceGroupAdapter.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/jaxb/adapter/ResourceGroupAdapter.java @@ -94,7 +94,6 @@ public class ResourceGroupAdapter extends XmlAdapter<WsResourceGroupWrapper, Res destination.setGroupDefinition(source.getGroupDefinition()); destination.setId(source.getId()); destination.setImplicitResources(source.getImplicitResources()); - destination.setLocation(source.getLocation()); destination.setModifiedBy(source.getModifiedBy()); destination.setMtime(source.getMtime()); destination.setName(source.getName());
commit 87b5e3d93a98db2380f8057802d801d7c19528e6 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 18:26:51 2010 -0400
fix todos in Event
* remove unused detailExcerpt attribute, and corresponding getter/setter combo * remove "lazify" comment, because composites or alterProjection on criteria can be used instead
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/event/Event.java b/modules/core/domain/src/main/java/org/rhq/core/domain/event/Event.java index 8335fdd..c12ce08 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/event/Event.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/event/Event.java @@ -116,10 +116,7 @@ public class Event implements Serializable { private EventSeverity severity;
@Column(name = "DETAIL", length = 4000, nullable = false) - private String detail; // TODO lazify - - @Transient - private transient String detailExcerpt; + private String detail;
/** The event's type (i.e. the name of its {@link EventDefinition}). */ @Transient @@ -215,21 +212,6 @@ public class Event implements Serializable { return this.detail; }
- public String getDetailExcerpt() { // TODO get from DB - int len = 100; - if (detailExcerpt != null) - return detailExcerpt; - - if (detail.length() < len) - len = detail.length(); - detailExcerpt = detail.substring(0, len); // TODO - return detailExcerpt; - } - - public void setDetailExcerpt(String detailExcerpt) { - this.detailExcerpt = detailExcerpt; - } - @Override public boolean equals(Object obj) { if (this == obj)
commit 7f08c6a478f51c6ba21b60c5505e4d451eac039d Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 18:21:35 2010 -0400
fix todos in CreateResourceHistory
* setErrorMessageFromThrowable has been replaced by ThrowableUtil.getStackAsString * calling contexts have already been updated, see git commit ebf6963
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java index 1e2af92..b4d9ac4 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/CreateResourceHistory.java @@ -22,8 +22,6 @@ */ package org.rhq.core.domain.resource;
-import java.io.ByteArrayOutputStream; -import java.io.PrintStream; import java.io.Serializable; import java.util.Date;
@@ -246,23 +244,6 @@ public class CreateResourceHistory implements Serializable { setStatus(CreateResourceStatus.FAILURE); } } -/*TODO: GWT - *//** - * Convienence method that sets the error message to the given throwable's stack trace dump. If the given throwable - * is <code>null</code>, the error message will be set to <code>null</code> as if passing <code>null</code> to - * {@link #setErrorMessage(String)}. - * - * @param t throwable whose message and stack trace will make up the error message (may be <code>null</code>) - *//* - public void setErrorMessageFromThrowable(Throwable t) { - if (t != null) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - t.printStackTrace(new PrintStream(baos)); - setErrorMessage(baos.toString()); - } else { - setErrorMessage(null); - } - }*/
public String getSubjectName() { return subjectName;
commit 30b522ae0086f454ecbc7a51167a0f27f770f5fd Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 18:10:18 2010 -0400
fix todos in ContentSourceType
* contentSourceApiClass is not a transient property, remove todo about that * update jdoc to point to the ContentProvider interface that the attribute represents
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java index 5a046ab..2c6b41d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/content/ContentSourceType.java @@ -54,7 +54,7 @@ import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; * @author Jason Dobies */ @Entity -@NamedQueries({ +@NamedQueries( { @NamedQuery(name = ContentSourceType.QUERY_FIND_ALL, query = "SELECT cst " + " FROM ContentSourceType cst " + " LEFT JOIN FETCH cst.contentSourceConfigurationDefinition d " + " LEFT JOIN FETCH d.templates "), @NamedQuery(name = ContentSourceType.QUERY_FIND_BY_NAME_WITH_CONFIG_DEF, query = "SELECT cst " @@ -116,7 +116,7 @@ public class ContentSourceType implements Serializable {
public ContentSourceType(String name) { this.name = name; - this.contentSourceApiClass = "undefined"; // TODO: I think we want this @Transient + this.contentSourceApiClass = "undefined"; }
public int getId() { @@ -235,8 +235,9 @@ public class ContentSourceType implements Serializable {
/** * Indicates the Java class that should be instantiated to be the content source and used to connect to the - * underlying external source. This class will be an implementation the content source connector interface (jdob: - * I'll add a javadoc link to it when I write it). + * underlying external source. + * + * This class will be an implementation of {@link org.rhq.enterprise.server.plugin.pc.content.ContentProvider}. */ public String getContentSourceApiClass() { return contentSourceApiClass;
commit 13275de25b4da73c35df6169486703223b618a37 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 17:40:42 2010 -0400
fix todos on ConfigurationDefinition
* if needed, criteria objects can be used for filtering and sorting
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java index 1bbd810..6adee0f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java @@ -56,11 +56,10 @@ import org.jetbrains.annotations.Nullable; /** * The entire definition for a {@link import javax.persistence.CascadeType.Configuration}. This includes mapped property * definitions of arbitrary complexity, made up of {@link PropertyDefinitionSimple}s, {@link PropertyDefinitionList}s, - * and {@link PropertyDefinitionMap}s. TODO GH: Groups aren't required right now... do we want to make them required? + * and {@link PropertyDefinitionMap}s. * * @author Greg Hinkle */ -//@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) @Entity @NamedQueries( { @NamedQuery(name = ConfigurationDefinition.QUERY_FIND_DEPLOYMENT_BY_PACKAGE_TYPE_ID, query = "SELECT cd FROM PackageType pt JOIN pt.deploymentConfigurationDefinition cd " @@ -224,7 +223,6 @@ public class ConfigurationDefinition implements Serializable { groups.add(group); }
- // TODO: Do this sorting at the DB query level instead. Collections.sort(groups, new GroupComparator()); return groups; } @@ -249,7 +247,6 @@ public class ConfigurationDefinition implements Serializable { } }
- // TODO: Do this sorting at the DB query level instead. Collections.sort(propertyDefinitions, new PropertyDefinitionComparator()); return propertyDefinitions; } @@ -276,7 +273,6 @@ public class ConfigurationDefinition implements Serializable { } }
- // TODO: Do this sorting at the DB query level instead. Collections.sort(propertyDefinitions, new PropertyDefinitionComparator()); return propertyDefinitions; }
commit af9b949eb349a6f4118f82a6673f31d8d991a37d Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 17:33:21 2010 -0400
fix todo on BundleResourceDeploymentCriteria
* add more detail to jdoc to explain criteria-based authz
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java index 98f77c1..ea8385a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/BundleResourceDeploymentCriteria.java @@ -85,14 +85,15 @@ public class BundleResourceDeploymentCriteria extends Criteria { this.fetchBundleDeployment = fetchBundleDeployment; }
- // TODO: MANAGE_INVENTORY was too restrictive as a bundle manager could not then - // see his resource deployments. Until we can handle granular authorization checks on - // optionally fetched resource member data, allow a bundle manager to see - // resouce deployments to any platform. /** - * Requires MANAGE_INVENTORY or MANAGE_BUNDLE - * - * @param fetchResource + * By setting this fetch to true, it will cause {@link #isInventoryManagerRequired()} to return true as well. + * + * In practice, however, MANAGE_INVENTORY is too restrictive; a bundle manager who has MANAGE_BUNDLE but not + * MANAGE_INVENTORY would not be able to see any resource deployments. So, until it is possible to handle granular + * authorization checks on optionally fetched criteria data, a bundle manager will be allowed to see resource + * deployments to any platform. + * + * @see org.rhq.enterprise.server.bundle.BundleManagerBean#findBundleResourceDeploymentsByCriteria(org.rhq.core.domain.auth.Subject, BundleResourceDeploymentCriteria) */ public void fetchResource(boolean fetchResource) { this.fetchResource = fetchResource;
commit 379ec9db15f14f8aea55e8c9f7bb5bb4d4348db7 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 15:37:24 2010 -0400
fix todo in Configuration
* clone is now implemented using deepCopy * old impl using streams has been removed
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java index 618ad9c..99488d3 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/Configuration.java @@ -427,10 +427,23 @@ public class Configuration implements Serializable, Cloneable, AbstractPropertyM }
/** + * Clones this object in the same manner as {@link #deepCopy()}. + * + * @return a clone of this configuration + * + * @throws CloneNotSupportedException + * + * @see #deepCopy() + */ + public Configuration clone() { + return deepCopy(); + } + + /** * Makes a fully independent copy of this object and returns it. This means all children N-levels deep in the * hierarchy of this Configuration object are copied. * - * <p>This is the same behavior as that of this object's {@link #clone()} method.</p> + * <p>This is the underlying implementation for the {@link #clone()} method.</p> * * @return a clone of this configuration */ @@ -487,44 +500,6 @@ public class Configuration implements Serializable, Cloneable, AbstractPropertyM }
/** - * Clones this object in the same manner as {@link #deepCopy()}. - * - * @return a clone of this configuration - * - * @throws CloneNotSupportedException - * - * @see #deepCopy() - */ - public Configuration clone() { - return deepCopy(); - - /* TODO: GWT - - // TODO GH: This may be a performance problem when it comes to runtime scans... - // do some profiling - Object obj = null; - try { - // Write the object out to a byte array - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(bos); - out.writeObject(this); - out.flush(); - out.close(); - - // Make an input stream from the byte array and read - // a copy of the object back in. - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); - obj = in.readObject(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException cnfe) { - cnfe.printStackTrace(); - } - - return (Configuration) obj;*/ - } - - /** * NOTE: An Configuration containing a null map is considered equal to a Configuration containing an empty map. */ @Override
commit b1dc47c0efd067037a89bcfb31976e0135348666 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 15:31:43 2010 -0400
type information can generally be accessed by all
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java index 36c62f0..1bbd810 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/ConfigurationDefinition.java @@ -62,7 +62,6 @@ import org.jetbrains.annotations.Nullable; */ //@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) @Entity -// TODO: non-admin version of the below query @NamedQueries( { @NamedQuery(name = ConfigurationDefinition.QUERY_FIND_DEPLOYMENT_BY_PACKAGE_TYPE_ID, query = "SELECT cd FROM PackageType pt JOIN pt.deploymentConfigurationDefinition cd " + "WHERE pt.id = :packageTypeId"),
commit a5d2a351c511b455812b2be26b9d8a395be3f76a Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 15:09:01 2010 -0400
fix todo in CallTimeData
* throw IllegalArgumentException if invalid args passed to addValue * fix calling contexts to use try...catch(IllegalArgumentException) { log } pattern
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java index c8f4837..d53627d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java @@ -115,11 +115,9 @@ public class CallTimeData implements Serializable { }
if (destination.length() > CallTimeDataKey.DESTINATION_MAX_LENGTH) { - /* TODO: GWT - LOG.warn("Call destination is longer than the maximum length (" + CallTimeDataKey.DESTINATION_MAX_LENGTH - + " characters) - truncating it to " + CallTimeDataKey.DESTINATION_MAX_LENGTH + " characters..."); - */ - destination = destination.substring(0, CallTimeDataKey.DESTINATION_MAX_LENGTH); + throw new IllegalArgumentException("Call destination is longer than the maximum length (" + + CallTimeDataKey.DESTINATION_MAX_LENGTH + " characters) - please modify your response time transform " + + "to generate smaller URLs"); }
CallTimeDataValue value = this.values.get(destination); diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/util/ResponseTimeLogParser.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/util/ResponseTimeLogParser.java index a3efb74..6e49ce0 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/util/ResponseTimeLogParser.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/util/ResponseTimeLogParser.java @@ -128,7 +128,12 @@ public class ResponseTimeLogParser { }
String transformedUrl = applyTransforms(url); - callTimeData.addCallData(transformedUrl, new Date(logEntry.getStartTime()), logEntry.getDuration()); + try { + callTimeData.addCallData(transformedUrl, new Date(logEntry.getStartTime()), logEntry.getDuration()); + } catch (IllegalArgumentException iae) { + // if any issue with the data, log them and continue processing the rest of the report + log.error(iae); + } } } catch (FileNotFoundException e) { log.warn("Response-time log file '" + this.logFile + "' does not exist."); diff --git a/modules/plugins/iis/src/main/java/org/rhq/plugins/iis/IISResponseTimeDelegate.java b/modules/plugins/iis/src/main/java/org/rhq/plugins/iis/IISResponseTimeDelegate.java index 3b12499..a9406d9 100644 --- a/modules/plugins/iis/src/main/java/org/rhq/plugins/iis/IISResponseTimeDelegate.java +++ b/modules/plugins/iis/src/main/java/org/rhq/plugins/iis/IISResponseTimeDelegate.java @@ -254,7 +254,12 @@ public class IISResponseTimeDelegate { String transformedUrl = applyTransforms(url); log.info("Original URL: " + url); log.info("Transformed: " + transformedUrl); - callTimeData.addCallData(transformedUrl, new Date(logEntry.getStartTime()), logEntry.getDuration()); + try { + callTimeData.addCallData(transformedUrl, new Date(logEntry.getStartTime()), logEntry.getDuration()); + } catch (IllegalArgumentException iae) { + // if any issue with the data, log them and continue processing the rest of the report + log.error(iae); + } }
log.info("Results...");
commit 0c0c834ead8744fa85fba08b07487306ba7880a3 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 14:28:42 2010 -0400
fix todo in CallTimeData
* throw IllegalArgumentException if invalid args passed to addAggregatedCallData * fix calling contexts to use try...catch(IllegalArgumentException) { log } pattern
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java index a7b3ad3..c8f4837 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/calltime/CallTimeData.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.domain.measurement.calltime;
import java.io.Serializable; @@ -28,8 +28,6 @@ import java.util.Date; import java.util.HashMap; import java.util.Map;
-import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.jetbrains.annotations.NotNull;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest; @@ -63,9 +61,7 @@ public class CallTimeData implements Serializable { * @param beginTime the time when the call was initiated * @param duration the duration of the call, in milliseconds */ - public void addCallData(@NotNull - String destination, @NotNull - Date beginTime, long duration) { + public void addCallData(@NotNull String destination, @NotNull Date beginTime, long duration) { Date endTime = new Date(beginTime.getTime() + duration); CallTimeDataValue value = addValue(beginTime, endTime, destination); value.mergeCallTime(duration); @@ -82,16 +78,12 @@ public class CallTimeData implements Serializable { * @param total ... * @param count ... */ - public void addAggregatedCallData(@NotNull - String destination, @NotNull - Date beginTime, @NotNull - Date endTime, double minimum, double maximum, double total, long count) { + public void addAggregatedCallData(@NotNull String destination, @NotNull Date beginTime, @NotNull Date endTime, + double minimum, double maximum, double total, long count) { if (count == 0) { - /* TODO: GWT - LOG.warn("Plugin attempted to add aggregated call data with a call count of 0 for destination '" - + destination + "' - data will not be added."); - */ - return; + throw new IllegalArgumentException( + "Plugin attempted to add aggregated call data with a call count of 0 for destination '" + destination + + "' - data will not be added."); }
CallTimeDataValue value = addValue(beginTime, endTime, destination); diff --git a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/AbstractEjbBeanComponent.java b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/AbstractEjbBeanComponent.java index c4c51c2..5f63261 100644 --- a/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/AbstractEjbBeanComponent.java +++ b/modules/plugins/jboss-as-5/src/main/java/org/rhq/plugins/jbossas5/AbstractEjbBeanComponent.java @@ -30,10 +30,12 @@ import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.jboss.managed.api.ManagedOperation; import org.jboss.managed.api.ManagedProperty; import org.jboss.metatype.api.values.CompositeValue; import org.jboss.metatype.api.values.SimpleValue; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PropertyList; import org.rhq.core.domain.configuration.PropertyMap; @@ -53,7 +55,7 @@ import org.rhq.core.pluginapi.operation.OperationResult; */ public abstract class AbstractEjbBeanComponent extends ManagedComponentComponent implements OperationFacet { private final Log log = LogFactory.getLog(this.getClass()); - + private static final String VIEW_INVOCATION_STATS_OPERATION_NAME = "viewInvocationStats";
@Override @@ -144,8 +146,13 @@ public abstract class AbstractEjbBeanComponent extends ManagedComponentComponent Date beginDate = new Date(invocationStats.beginTime); Date endDate = new Date(invocationStats.endTime); for (MethodStats methodStats : invocationStats.methodStats) { - callTimeData.addAggregatedCallData(methodStats.name, beginDate, endDate, methodStats.minTime, - methodStats.maxTime, methodStats.totalTime, methodStats.count); + try { + callTimeData.addAggregatedCallData(methodStats.name, beginDate, endDate, methodStats.minTime, + methodStats.maxTime, methodStats.totalTime, methodStats.count); + } catch (IllegalArgumentException iae) { + // if any issue with the data, log them and continue processing the rest of the report + log.error(iae); + } } return callTimeData; } diff --git a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB2BeanComponent.java b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB2BeanComponent.java index e073ed8..07fa732 100644 --- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB2BeanComponent.java +++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB2BeanComponent.java @@ -95,18 +95,21 @@ public class EJB2BeanComponent extends MBeanResourceComponent<JBossASServerCompo CallTimeData callTimeData = new CallTimeData(schedule); for (String methodName : stats.keySet()) { Stat timeStatistic = stats.get(methodName); + long minTime = timeStatistic.min; long maxTime = timeStatistic.max; long totalTime = timeStatistic.total; long count = timeStatistic.count; - if (count == 0) { - // Don't bother even adding data for this method if the call count is 0. + + try { + rawCallTimeData.addAggregatedCallData(methodName, lastResetTime, collectionTime, minTime, maxTime, + totalTime, count); + } catch (IllegalArgumentException iae) { + // if any issue with the data, log them and continue processing the rest of the report + log.error(iae); continue; }
- rawCallTimeData.addAggregatedCallData(methodName, lastResetTime, collectionTime, minTime, maxTime, - totalTime, count); - // Now compute the adjusted data, which is what we will report back to the server. CallTimeDataValue previousValue = (previousRawCallTimeData != null) ? previousRawCallTimeData.getValues() .get(methodName) : null; diff --git a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB3BeanComponent.java b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB3BeanComponent.java index ae254b5..af96d54 100644 --- a/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB3BeanComponent.java +++ b/modules/plugins/jboss-as/src/main/java/org/rhq/plugins/jbossas/EJB3BeanComponent.java @@ -1,25 +1,25 @@ - /* - * Jopr 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. - */ +/* + * Jopr 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.plugins.jbossas;
import java.lang.reflect.Field; @@ -29,6 +29,7 @@ import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
@@ -55,7 +56,7 @@ import org.rhq.plugins.jmx.MBeanResourceComponent; public class EJB3BeanComponent extends MBeanResourceComponent<JBossASServerComponent> { private final Log log = LogFactory.getLog(EJB3BeanComponent.class);
- private Map<Integer, CallTimeData> previousRawCallTimeDatas = new HashMap<Integer,CallTimeData>(); + private Map<Integer, CallTimeData> previousRawCallTimeDatas = new HashMap<Integer, CallTimeData>();
@Override public AvailabilityType getAvailability() { @@ -135,18 +136,21 @@ public class EJB3BeanComponent extends MBeanResourceComponent<JBossASServerCompo CallTimeData callTimeData = new CallTimeData(schedule); for (String methodName : stats.keySet()) { Object timeStatistic = stats.get(methodName); + long minTime = (Long) timeStatistic.getClass().getField("minTime").get(timeStatistic); long maxTime = (Long) timeStatistic.getClass().getField("maxTime").get(timeStatistic); long totalTime = (Long) timeStatistic.getClass().getField("totalTime").get(timeStatistic); long count = (Long) timeStatistic.getClass().getField("count").get(timeStatistic); - if (count == 0) { - // Don't bother even adding data for this method if the call count is 0. + + try { + rawCallTimeData.addAggregatedCallData(methodName, lastResetTime, collectionTime, minTime, maxTime, + totalTime, count); + } catch (IllegalArgumentException iae) { + // if any issue with the data, log them and continue processing the rest of the report + log.error(iae); continue; }
- rawCallTimeData.addAggregatedCallData(methodName, lastResetTime, collectionTime, minTime, maxTime, - totalTime, count); - // Now compute the adjusted data, which is what we will report back to the server. CallTimeDataValue previousValue = (previousRawCallTimeData != null) ? previousRawCallTimeData.getValues() .get(methodName) : null;
commit a733eb45ab0b918e3f6b1d1e77a0e6ce42b03845 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 14:27:31 2010 -0400
remove unnecessary todo
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/AuthzConstants.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/AuthzConstants.java index fca6a8c..6ef9b87 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/AuthzConstants.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/AuthzConstants.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.domain.util;
import org.rhq.core.domain.auth.Subject; @@ -162,7 +162,6 @@ public final class AuthzConstants { public static final Integer authzApplication = new Integer(308); public static final Integer authzLocation = new Integer(309);
- // TODO: see AuthorizationManager.isBuiltInSuperuser() public static boolean isOverlord(Integer subject) { return subject.equals(AuthzConstants.overlordIdInteger); }
commit e11f2ed9fa4e6601afbd45b233fce479a2cdd999 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 14:09:16 2010 -0400
mark AlertConditionLog.value as required / not null
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index cb7f1d7..1ce883c 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -22,7 +22,7 @@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.98</db.schema.version> + <db.schema.version>2.99</db.schema.version> </properties>
<dependencies> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml index 68e7635..100296c 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/alert-schema.xml @@ -105,7 +105,7 @@ <column name="CTIME" required="true" type="LONG"/> <column name="ALERT_ID" required="false" type="INTEGER" references="RHQ_ALERT(ID)"/> <column name="CONDITION_ID" required="true" type="INTEGER" references="RHQ_ALERT_CONDITION(ID)"/> - <column name="VALUE" required="false" size="250" type="VARCHAR2"/> + <column name="VALUE" required="true" size="250" type="VARCHAR2"/> <index name="RHQ_ALERT_COND_LOG_IDX_TIME"> <field ref="CTIME" /> </index> 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 70e4c46..d6fe7bc 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3246,6 +3246,10 @@ <schema-deleteColumn ignoreError="true" table="RHQ_CONF_PROP_DEF_ENUM" column="IS_DEFAULT" /> </schemaSpec>
+ <schemaSpec version="2.99"> + <schema-alterColumn table="RHQ_ALERT_CONDITION_LOG" column="VALUE" nullable="FALSE" /> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java index ddcf92e..2979bc2 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/alert/AlertConditionLog.java @@ -61,8 +61,7 @@ import javax.persistence.Table; + " WHERE acl.id IN ( SELECT iacl.id " // + " FROM AlertConditionLog iacl" // + " WHERE iacl.condition.alertDefinition.id = :alertDefinitionId )" // - + " AND acl.alert IS NULL") -}) + + " AND acl.alert IS NULL") }) @SequenceGenerator(name = "RHQ_ALERT_CONDITION_LOG_ID_SEQ", sequenceName = "RHQ_ALERT_CONDITION_LOG_ID_SEQ") @Table(name = "RHQ_ALERT_CONDITION_LOG") public class AlertConditionLog implements Serializable { @@ -92,10 +91,7 @@ public class AlertConditionLog implements Serializable { @Column(name = "CTIME", nullable = false) private long ctime;
- /* - * TODO: jmarques - should this be non-null? - */ - @Column(name = "VALUE") + @Column(name = "VALUE", nullable = false) private String value;
@JoinColumn(name = "ALERT_ID", referencedColumnName = "ID") diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/alert/test/AlertManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/alert/test/AlertManagerBeanTest.java index 79fcb3b..95897e3 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/alert/test/AlertManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/alert/test/AlertManagerBeanTest.java @@ -111,6 +111,7 @@ public class AlertManagerBeanTest extends AbstractEJB3Test { em.persist(ac);
AlertConditionLog acl = new AlertConditionLog(ac, now); + acl.setValue("dummy value"); em.persist(acl);
Alert a = new Alert(ad, now); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJobTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJobTest.java index 3145682..b499997 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJobTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/scheduler/jobs/DataPurgeJobTest.java @@ -434,6 +434,7 @@ public class DataPurgeJobTest extends AbstractEJB3Test { AlertCondition ac = ad.getConditions().iterator().next(); AlertConditionLog acl = new AlertConditionLog(ac, timestamp); acl.setAlert(a); + acl.setValue("dummy value"); em.persist(acl);
return a;
commit 3fccdaa26f06bd74909255f4f6673754f1b1c0f3 Author: Joseph Marques joseph@redhat.com Date: Wed Oct 6 14:06:52 2010 -0400
remove unnecessary todos in AbstractEJB3Test
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java b/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java index 0724ac6..ccf205f 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/test/AbstractEJB3Test.java @@ -1,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.domain.test;
import java.io.File; @@ -40,7 +40,7 @@ import org.testng.annotations.BeforeSuite; import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap; import org.jboss.ejb3.embedded.EJB3StandaloneDeployer;
- public abstract class AbstractEJB3Test extends AssertJUnit { +public abstract class AbstractEJB3Test extends AssertJUnit { @BeforeSuite(groups = "integration.ejb3") public static void startupEmbeddedJboss() { System.out.println("Starting ejb3..."); @@ -66,9 +66,6 @@ import org.jboss.ejb3.embedded.EJB3StandaloneDeployer; System.err.println("...... deploying MM ejb3....."); System.err.println("...... ejb3 deployed....");
- // Set the hibernate dialect -// System.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect"); // TODO - // Deploy everything we got deployer.setKernel(EJB3StandaloneBootstrap.getKernel()); deployer.create(); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java index 3425ebb..7991b89 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/test/AbstractEJB3Test.java @@ -106,9 +106,6 @@ public abstract class AbstractEJB3Test extends AssertJUnit { deployer.create(); System.err.println("...... deployer created....");
- // Set the hibernate dialect - // System.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect"); // TODO - deployer.start(); System.err.println("...... deployer started....");
commit faaf03d44c633f4299580bf797f7649e282c493b Author: John Sanda jsanda@redhat.com Date: Sun Oct 10 13:15:28 2010 -0400
Removing 'default' attribute that is no longer supported for property options
diff --git a/modules/enterprise/server/xml-schemas/src/test/resources/test-serverplugin-generic.xml b/modules/enterprise/server/xml-schemas/src/test/resources/test-serverplugin-generic.xml index 2a8927d..1f9e93b 100644 --- a/modules/enterprise/server/xml-schemas/src/test/resources/test-serverplugin-generic.xml +++ b/modules/enterprise/server/xml-schemas/src/test/resources/test-serverplugin-generic.xml @@ -22,7 +22,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 15 10 ? * MON-FRI" summary="true" description="Based on the schedule type, this is either the period, in milliseconds, or the cron expression"/> @@ -50,7 +50,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>
commit 7d97be5244740a1e88771d8b8634dfdef1f5cc38 Author: John Sanda jsanda@redhat.com Date: Sun Oct 10 13:08:24 2010 -0400
Fixing broken tests in UpdateConfigurationSubsystemTest
One test was failing due to a call to PropertyDefinitionEnumeration.setOrderIndex in ConfigurationMetadataManagerBean. That call should not be made because the owning PropertyDefinitionSimple object takes care of calling setOrderIndex. The other test was failing due to a parse error in a plugin descriptor that was using an attribute, 'default', that is no longer supported for property options.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java index bcf5e47..6312cfe 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java @@ -394,8 +394,8 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa for (PropertyDefinitionEnumeration pde : changed) { for (PropertyDefinitionEnumeration nPde : newOptions) { if (nPde.equals(pde)) { + pde.setValue(nPde.getValue()); pde.setName(nPde.getName()); - pde.setOrderIndex(nPde.getOrderIndex()); } } } diff --git a/modules/enterprise/server/jar/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml b/modules/enterprise/server/jar/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml index a50bd81..6da4878 100644 --- a/modules/enterprise/server/jar/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml +++ b/modules/enterprise/server/jar/src/test/resources/test/metadata/configuration/groupPropDeleted-v4.xml @@ -108,7 +108,7 @@ description="Whether to use local or xa transactions. If nothing is specified, the default of local will be used." required="false"> <c:property-options> - <c:option value="Local Transaction" default="true"/> + <c:option value="Local Transaction"/> <c:option value="XA Transaction"/> </c:property-options> </c:simple-property>
commit e7b6b09dd3cc91c0a974cf0f64c5edede3dda34c Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 8 16:37:10 2010 -0400
Fix Bug 640224 - On click of 'Topology->Agents' RHQ not showing agent UI
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java index 37770eb..8c82506 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/AdministrationView.java @@ -52,6 +52,22 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; public class AdministrationView extends LocatableHLayout implements BookmarkableView { public static final String VIEW_ID = "Administration";
+ private static final String SECTION_SECURITY_VIEW_ID = "Security"; + private static final String SECTION_TOPOLOGY_VIEW_ID = "Topology"; + private static final String SECTION_CONFIGURATION_VIEW_ID = "Configuration"; + + // TODO these iframe page view ids should go away in favor of the gwt view page view_id, when available + private static final String PAGE_SERVERS_VIEW_ID = "Servers"; + private static final String PAGE_AGENTS_VIEW_ID = "Agents"; + private static final String PAGE_AFFINITY_GROUPS_VIEW_ID = "AffinityGroups"; + private static final String PAGE_PARTITION_EVENTS_VIEW_ID = "PartitionEvents"; + + private static final String PAGE_SYSTEM_SETTINGS_VIEW_ID = "SystemSettings"; + private static final String PAGE_TEMPLATES_VIEW_ID = "Templates"; + private static final String PAGE_DOWNLOADS_VIEW_ID = "Downloads"; + private static final String PAGE_LICENSE_VIEW_ID = "License"; + private static final String PAGE_PLUGINS_VIEW_ID = "Plugins"; + private ViewId currentSectionViewId; private ViewId currentPageViewId;
@@ -61,10 +77,6 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable private Canvas currentContent; private Map<String, TreeGrid> treeGrids = new LinkedHashMap<String, TreeGrid>();
- private static final String SECURITY_SECTION_VIEW_ID = "Security"; - private static final String TOPOLOGY_SECTION_VIEW_ID = "Topology"; - private static final String CONFIGURATION_SECTION_VIEW_ID = "Configuration"; - public AdministrationView(String locatorId) { super(locatorId); } @@ -88,7 +100,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
addSection(buildSecuritySection()); addSection(buildSystemConfigurationSection()); - addSection(buildManagementClusterSection()); + addSection(buildTopologySection());
addMember(sectionStack); addMember(contentCanvas); @@ -101,7 +113,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) { - TreeNode node = (TreeNode)selectionEvent.getRecord(); + TreeNode node = (TreeNode) selectionEvent.getRecord(); String pageName = node.getName(); String viewPath = AdministrationView.VIEW_ID + "/" + sectionName + "/" + pageName; String currentViewPath = History.getToken(); @@ -130,7 +142,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private TreeGrid buildSecuritySection() {
- final TreeGrid securityTreeGrid = new LocatableTreeGrid(SECURITY_SECTION_VIEW_ID); + final TreeGrid securityTreeGrid = new LocatableTreeGrid(SECTION_SECURITY_VIEW_ID); securityTreeGrid.setLeaveScrollbarGap(false); securityTreeGrid.setShowHeader(false);
@@ -144,7 +156,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable final TreeNode remoteAgentInstall = new EnhancedTreeNode(RemoteAgentInstallView.VIEW_ID); remoteAgentInstall.setIcon("global/Agent_16.png");
- TreeNode rootNode = new EnhancedTreeNode(SECURITY_SECTION_VIEW_ID, manageUsersNode, manageRolesNode, + TreeNode rootNode = new EnhancedTreeNode(SECTION_SECURITY_VIEW_ID, manageUsersNode, manageRolesNode, remoteAgentInstall); tree.setRoot(rootNode);
@@ -153,19 +165,19 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable return securityTreeGrid; }
- private TreeGrid buildManagementClusterSection() { + private TreeGrid buildTopologySection() {
- final TreeGrid mgmtClusterTreeGrid = new LocatableTreeGrid(TOPOLOGY_SECTION_VIEW_ID); + final TreeGrid mgmtClusterTreeGrid = new LocatableTreeGrid(SECTION_TOPOLOGY_VIEW_ID); mgmtClusterTreeGrid.setLeaveScrollbarGap(false); mgmtClusterTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode manageServersNode = new EnhancedTreeNode("Servers"); - final TreeNode manageAgentsNode = new EnhancedTreeNode("Agents"); - final TreeNode manageAffinityGroupsNode = new EnhancedTreeNode("AffinityGroups"); - final TreeNode managePartitionEventsNode = new EnhancedTreeNode("PartitionEvents"); + final TreeNode manageServersNode = new EnhancedTreeNode(PAGE_SERVERS_VIEW_ID); + final TreeNode manageAgentsNode = new EnhancedTreeNode(PAGE_AGENTS_VIEW_ID); + final TreeNode manageAffinityGroupsNode = new EnhancedTreeNode(PAGE_AFFINITY_GROUPS_VIEW_ID); + final TreeNode managePartitionEventsNode = new EnhancedTreeNode(PAGE_PARTITION_EVENTS_VIEW_ID);
- TreeNode rootNode = new EnhancedTreeNode(TOPOLOGY_SECTION_VIEW_ID, manageServersNode, manageAgentsNode, + TreeNode rootNode = new EnhancedTreeNode(SECTION_TOPOLOGY_VIEW_ID, manageServersNode, manageAgentsNode, manageAffinityGroupsNode, managePartitionEventsNode); tree.setRoot(rootNode);
@@ -176,19 +188,19 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable
private TreeGrid buildSystemConfigurationSection() {
- final TreeGrid systemConfigTreeGrid = new LocatableTreeGrid(CONFIGURATION_SECTION_VIEW_ID); + final TreeGrid systemConfigTreeGrid = new LocatableTreeGrid(SECTION_CONFIGURATION_VIEW_ID); systemConfigTreeGrid.setLeaveScrollbarGap(false); systemConfigTreeGrid.setShowHeader(false);
Tree tree = new Tree(); - final TreeNode manageSettings = new EnhancedTreeNode("SystemSettings"); - final TreeNode manageTemplates = new EnhancedTreeNode("Templates"); - final TreeNode manageDownloads = new EnhancedTreeNode("Downloads"); - final TreeNode manageLicense = new EnhancedTreeNode("License"); - final TreeNode managePlugins = new EnhancedTreeNode("Plugins"); - - TreeNode rootNode = new EnhancedTreeNode(CONFIGURATION_SECTION_VIEW_ID, manageSettings, manageTemplates, manageDownloads, - manageLicense, managePlugins); + final TreeNode manageSettings = new EnhancedTreeNode(PAGE_SYSTEM_SETTINGS_VIEW_ID); + final TreeNode manageTemplates = new EnhancedTreeNode(PAGE_TEMPLATES_VIEW_ID); + final TreeNode manageDownloads = new EnhancedTreeNode(PAGE_DOWNLOADS_VIEW_ID); + final TreeNode manageLicense = new EnhancedTreeNode(PAGE_LICENSE_VIEW_ID); + final TreeNode managePlugins = new EnhancedTreeNode(PAGE_PLUGINS_VIEW_ID); + + TreeNode rootNode = new EnhancedTreeNode(SECTION_CONFIGURATION_VIEW_ID, manageSettings, manageTemplates, + manageDownloads, manageLicense, managePlugins); tree.setRoot(rootNode);
systemConfigTreeGrid.setData(tree); @@ -197,8 +209,13 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable }
public void setContent(Canvas newContent) { - for (Canvas child : contentCanvas.getChildren()) { - child.destroy(); + + // A call to destroy (e.g. certain IFrames/FullHTMLPane) can actually remove multiple children of the + // contentCanvas. As such, we need to query for the children after each destroy to ensure only valid children + // are in the array. + Canvas[] children; + while ((children = contentCanvas.getChildren()).length > 0) { + children[0].destroy(); }
contentCanvas.addChild(newContent); @@ -214,7 +231,7 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable String pageName = currentPageViewId.getPath();
Canvas content = null; - if (SECURITY_SECTION_VIEW_ID.equals(sectionName)) { + if (SECTION_SECURITY_VIEW_ID.equals(sectionName)) {
if (UsersView.VIEW_ID.equals(pageName)) { content = new UsersView(this.extendLocatorId("Users")); @@ -223,42 +240,41 @@ public class AdministrationView extends LocatableHLayout implements Bookmarkable } else if (RemoteAgentInstallView.VIEW_ID.equals(pageName)) { content = new RemoteAgentInstallView(this.extendLocatorId("RemoteAgentInstall")); } - } else if (CONFIGURATION_SECTION_VIEW_ID.equals(sectionName)) { + } else if (SECTION_CONFIGURATION_VIEW_ID.equals(sectionName)) {
String url = null; - if ("SystemSettings".equals(pageName)) { + if (PAGE_SYSTEM_SETTINGS_VIEW_ID.equals(pageName)) { url = "/admin/config/Config.do?mode=edit"; - } else if ("Templates".equals(pageName)) { + } else if (PAGE_TEMPLATES_VIEW_ID.equals(pageName)) { url = "/admin/config/EditDefaults.do?mode=monitor&viewMode=all"; - } else if ("Downloads".equals(pageName)) { + } else if (PAGE_DOWNLOADS_VIEW_ID.equals(pageName)) { url = "/rhq/admin/downloads-body.xhtml"; - } else if ("License".equals(pageName)) { + } else if (PAGE_LICENSE_VIEW_ID.equals(pageName)) { url = "/admin/license/LicenseAdmin.do?mode=view"; - } else if ("Plugins".equals(pageName)) { + } else if (PAGE_PLUGINS_VIEW_ID.equals(pageName)) { url = "/rhq/admin/plugin/plugin-list-plain.xhtml"; } url = addQueryStringParam(url, "nomenu=true"); content = new FullHTMLPane(url);
- } else if (TOPOLOGY_SECTION_VIEW_ID.equals(sectionName)) { + } else if (SECTION_TOPOLOGY_VIEW_ID.equals(sectionName)) { String url = null; - if ("Servers".equals(pageName)) { + if (PAGE_SERVERS_VIEW_ID.equals(pageName)) { url = "/rhq/ha/listServers-plain.xhtml"; - } else if ("Agents".equals(pageName)) { + } else if (PAGE_AGENTS_VIEW_ID.equals(pageName)) { url = "/rhq/ha/listAgents-plain.xhtml"; - } else if ("Affinity Groups".equals(pageName)) { + } else if (PAGE_AFFINITY_GROUPS_VIEW_ID.equals(pageName)) { url = "/rhq/ha/listAffinityGroups-plain.xhtml"; - } else if ("Partition Events".equals(pageName)) { + } else if (PAGE_PARTITION_EVENTS_VIEW_ID.equals(pageName)) { url = "/rhq/ha/listPartitionEvents-plain.xhtml"; } content = new FullHTMLPane(url); }
+ // when changing sections make sure the previous section's selection is deselected for (String name : treeGrids.keySet()) { TreeGrid treeGrid = treeGrids.get(name); - if (name.equals(sectionName)) { - // treeGrid.setSelectedPaths(page); - } else { + if (!name.equals(sectionName)) { treeGrid.deselectAllRecords(); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java index 48a4455..0a9359e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/ReportTopView.java @@ -58,7 +58,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; * @author Greg Hinkle */ public class ReportTopView extends LocatableHLayout implements BookmarkableView { - public static final String VIEW_ID = "Reports"; + public static final String VIEW_ID = "Reports";
private static final String SUBSYSTEMS_SECTION_VIEW_ID = "Subsystems"; private static final String INVENTORY_SECTION_VIEW_ID = "Inventory"; @@ -107,7 +107,7 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView treeGrid.addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent selectionEvent) { if (selectionEvent.getState()) { - TreeNode node = (TreeNode)selectionEvent.getRecord(); + TreeNode node = (TreeNode) selectionEvent.getRecord(); String pageName = node.getName(); String viewPath = ReportTopView.VIEW_ID + "/" + sectionName + "/" + pageName; String currentViewPath = History.getToken(); @@ -187,10 +187,12 @@ public class ReportTopView extends LocatableHLayout implements BookmarkableView }
public void setContent(Canvas newContent) { - if (contentCanvas.getChildren().length > 0) { - for (Canvas child : contentCanvas.getChildren()) { - child.destroy(); - } + // A call to destroy (e.g. certain IFrames/FullHTMLPane) can actually remove multiple children of the + // contentCanvas. As such, we need to query for the children after each destroy to ensure only valid children + // are in the array. + Canvas[] children; + while ((children = contentCanvas.getChildren()).length > 0) { + children[0].destroy(); }
contentCanvas.addChild(newContent);
commit 986d0749e6ab2871a3ce07fbf4b223130ee6e87e Author: John Mazzitelli mazz@redhat.com Date: Fri Oct 8 15:02:01 2010 -0400
this completesly about 70% of the resource operation notification editor functionality. need to implement the "relative" feature, finish/cleanup the self/specific resource op modes and get the new notification to actually save to the db
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java index 40bd990..28d2596 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java @@ -41,6 +41,7 @@ import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import org.rhq.core.domain.alert.AlertDefinition; import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; @@ -222,7 +223,15 @@ public class NewNotificationEditor extends LocatableDynamicForm { } else if ("System Roles".equals(sender)) { newCanvas = new SystemRolesNotificationSenderForm(newLocatorId, notificationToEdit, sender); } else if ("Resource Operations".equals(sender)) { - newCanvas = null; // TODO + ResourceType rt; + if (alertDefinition.getResourceType() != null) { + rt = alertDefinition.getResourceType(); + } else if (alertDefinition.getResourceGroup() != null) { + rt = alertDefinition.getResourceGroup().getResourceType(); + } else { + rt = alertDefinition.getResource().getResourceType(); + } + newCanvas = new ResourceOperationNotificationSenderForm(newLocatorId, notificationToEdit, sender, rt); } else { // catch all - all other senders are assumed to just have simple configuration definition // that can be used by our configuration editor UI component to ask for config values. diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java index 117fcb0..f707dc1 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NotificationsAlertDefinitionForm.java @@ -284,8 +284,8 @@ public class NotificationsAlertDefinitionForm extends LocatableVLayout implement winModal.setShowModalMask(true); winModal.setAutoSize(true); winModal.setAutoCenter(true); - winModal.setShowResizer(true); - winModal.setCanDragResize(true); + //winModal.setShowResizer(true); + //winModal.setCanDragResize(true); winModal.centerInPage(); winModal.addCloseClickHandler(new CloseClickHandler() { @Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationInfo.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationInfo.java new file mode 100644 index 0000000..d8f4b46 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationInfo.java @@ -0,0 +1,157 @@ +/* + * 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.alert.definitions; + +import org.rhq.core.domain.configuration.Configuration; + +/** + * Convienence class that encapsulates the different configuration properties that a notification + * needs to support the resource operation notification feature. + * + * @author John Mazzitelli + */ +public class ResourceOperationNotificationInfo { + public enum Constants { + SELECTION_MODE("selection-mode"), // self, specific, relative + SPECIFIC_RESOURCE_ID("selection-specific-resource-id"), // + RELATIVE_ANCESTOR_TYPE_ID("selection-relative-ancestor-type-id"), // + RELATIVE_DESCENDANT_TYPE_ID("selection-relative-descendant-type-id"), // + RELATIVE_DESCENDANT_NAME("selection-relative-descendant-name"), // + OPERATION_ID("operation-definition-id"); + + private final String propertyName; // the actual name of the property stored in the config object - must match server-side expectations + + private Constants(String propertyName) { + this.propertyName = propertyName; + } + + public String getPropertyName() { + return propertyName; + } + }; // gwt compiler needs this semi + + public enum ResourceSelectionMode { + SELF, // + SPECIFIC, // + RELATIVE; + + public String getDisplayString() { + switch (ordinal()) { + case 0: { + return "This Resource"; + } + case 1: { + return "Specific Resource"; + } + case 2: { + return "Relative Resource"; + } + default: { + return "UNKNOWN OPTION - THIS IS A BUG"; // should never happen + } + } + } + }; // gwt compiler needs this semi + + private ResourceSelectionMode mode; // will never be null + private Integer resourceId; + private Integer ancestorTypeId; + private Integer descendantTypeId; + private String descendantName; + private Integer operationId; + private Configuration operationArguments; // may be null + + private ResourceOperationNotificationInfo(String mode, String resourceId, String ancestorTypeId, + String descendantTypeId, String descendantName, String operationId, Configuration opArgs) { + + ResourceSelectionMode selectionMode = null; + try { + if (mode != null) { + selectionMode = ResourceSelectionMode.valueOf(mode); + } + } catch (Throwable t) { + } + this.mode = selectionMode; + this.resourceId = getInteger(resourceId); + this.ancestorTypeId = getInteger(ancestorTypeId); + this.descendantTypeId = getInteger(descendantTypeId); + this.descendantName = descendantName; + this.operationId = getInteger(operationId); + this.operationArguments = opArgs; + } + + private Integer getInteger(String data) { + if (data == null || data.equals("") || data.equals("none")) { + return null; + } + + return Integer.parseInt(data); + } + + public static ResourceOperationNotificationInfo load(Configuration configuration, Configuration extraConfiguration) { + String mode = get(configuration, Constants.SELECTION_MODE, ResourceSelectionMode.SELF.name()); + String resourceId = get(configuration, Constants.SPECIFIC_RESOURCE_ID, null); + String ancestorTypeId = get(configuration, Constants.RELATIVE_ANCESTOR_TYPE_ID, null); + String descendantTypeId = get(configuration, Constants.RELATIVE_DESCENDANT_TYPE_ID, null); + String descendantName = get(configuration, Constants.RELATIVE_DESCENDANT_NAME, null); + String operationId = get(configuration, Constants.OPERATION_ID, null); + + return new ResourceOperationNotificationInfo(mode, resourceId, ancestorTypeId, descendantTypeId, + descendantName, operationId, extraConfiguration); + } + + private static String get(Configuration configuration, Constants operationInfoConstants, String defaultValue) { + return configuration.getSimpleValue(operationInfoConstants.propertyName, defaultValue); + } + + /** + * Indicates how to interpret the rest of the data in this info object. + * If this is <code>null</code>, there is no info that can be gleened from the rest of this object's data. + * + * @return the operation selection mode - e.g. self, specific or relative + */ + public ResourceSelectionMode getMode() { + return mode; + } + + public Integer getResourceId() { + return resourceId; + } + + public Integer getAncestorTypeId() { + return ancestorTypeId; + } + + public Integer getDescendantTypeId() { + return descendantTypeId; + } + + public String getDescendantName() { + return descendantName; + } + + public Integer getOperationId() { + return operationId; + } + + public Configuration getOperationArguments() { + return operationArguments; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java new file mode 100644 index 0000000..cd50d2c --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/ResourceOperationNotificationSenderForm.java @@ -0,0 +1,427 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.rhq.enterprise.gui.coregui.client.alert.definitions; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Set; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.widgets.Canvas; +import com.smartgwt.client.widgets.Label; +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.CanvasItem; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.SelectItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +import com.smartgwt.client.widgets.form.fields.events.ClickHandler; + +import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.criteria.ResourceCriteria; +import org.rhq.core.domain.criteria.ResourceTypeCriteria; +import org.rhq.core.domain.operation.OperationDefinition; +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.alert.definitions.ResourceOperationNotificationInfo.ResourceSelectionMode; +import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.SingleResourcePicker; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.selection.ResourcePicker.OkHandler; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm; + +/** + * This notification form will be used for the Resource Operation sender. This form lets + * you pick a resource operation that the sender will invoke when an alert is triggered. + * + * @author John Mazzitelli + */ +public class ResourceOperationNotificationSenderForm extends AbstractNotificationSenderForm { + + private static final String RESOURCE_ID_ATTRIBUTE = "singleResourceId"; + private static final String OPERATION_DEFS_ATTRIBUTE = "operationDefinitions"; + + private final ResourceType resourceType; // the type representing the current resource or the current type being edited + + private LocatableDynamicForm dynamicForm; + private StaticTextItem singleResourceTextItem; + private SelectItem ancestorTypeSelectItem; + private CanvasItem operationArgumentsCanvasItem; + private SelectItem operationSelectItem; + + public ResourceOperationNotificationSenderForm(String locatorId, AlertNotification notif, String sender, + ResourceType resourceType) { + + super(locatorId, notif, sender); + this.resourceType = resourceType; + } + + @Override + protected void onInit() { + super.onInit(); + + dynamicForm = new LocatableDynamicForm(extendLocatorId("resOpForm")); + dynamicForm.setNumCols(3); + + operationArgumentsCanvasItem = new CanvasItem(); + operationArgumentsCanvasItem.setStartRow(true); + operationArgumentsCanvasItem.setEndRow(true); + operationArgumentsCanvasItem.setShowTitle(false); + operationArgumentsCanvasItem.setColSpan(3); + operationArgumentsCanvasItem.setCanvas(new Label()); + operationArgumentsCanvasItem.setWidth("*"); + operationArgumentsCanvasItem.setVisible(false); + + operationSelectItem = new SelectItem("operationSelectItem", "Operation"); + operationSelectItem.setStartRow(true); + operationSelectItem.setEndRow(true); + operationSelectItem.setWrapTitle(false); + operationSelectItem.setRedrawOnChange(true); + operationSelectItem.setVisible(false); + operationSelectItem.setDefaultToFirstOption(true); + operationSelectItem.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + int operationId = Integer.valueOf(event.getValue().toString()); + selectOperation(operationId); + } + }); + + // for SPECIFIC mode + + singleResourceTextItem = new StaticTextItem("singleResourceTextItem", "Resource"); + singleResourceTextItem.setStartRow(true); + singleResourceTextItem.setEndRow(false); + singleResourceTextItem.setValue("Pick a resource..."); + singleResourceTextItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.SPECIFIC)); + singleResourceTextItem.setAttribute(RESOURCE_ID_ATTRIBUTE, 0); // we hide the resource ID in this attribute + + ButtonItem singleResourceButtonItem = new ButtonItem("singleResourceButtonItem", "Pick"); + singleResourceButtonItem.setStartRow(false); + singleResourceButtonItem.setEndRow(true); + singleResourceButtonItem.setShowTitle(false); + singleResourceButtonItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.SPECIFIC)); + singleResourceButtonItem.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + SingleResourcePicker singleResourcePicker; + singleResourcePicker = new SingleResourcePicker(extendLocatorId("singleResourcePicker"), + new OkHandler() { + @Override + public boolean ok(HashSet<Integer> resourceIdSelection) { + final int resourceId = resourceIdSelection.iterator().next().intValue(); + setSpecificResource(resourceId, null, null); + return true; + } + }, null); + singleResourcePicker.show(); + } + }); + + // for RELATIVE mode + + ancestorTypeSelectItem = new SelectItem("ancestorTypeSelectItem", "Start Search From"); + ancestorTypeSelectItem.setStartRow(true); + ancestorTypeSelectItem.setEndRow(true); + ancestorTypeSelectItem.setWrapTitle(false); + ancestorTypeSelectItem.setRedrawOnChange(true); + ancestorTypeSelectItem.setVisible(false); + ancestorTypeSelectItem.setShowIfCondition(new ShowIfModeFunction(ResourceSelectionMode.RELATIVE)); + + // the mode selector menu + + SelectItem modeSelectItem = new SelectItem("modeSelectItem", "Resource Selection Mode"); + modeSelectItem.setStartRow(true); + modeSelectItem.setEndRow(true); + modeSelectItem.setWrapTitle(false); + modeSelectItem.setRedrawOnChange(true); + LinkedHashMap<String, String> modes = new LinkedHashMap<String, String>(3); + modes.put(ResourceSelectionMode.SELF.name(), ResourceSelectionMode.SELF.getDisplayString()); + modes.put(ResourceSelectionMode.SPECIFIC.name(), ResourceSelectionMode.SPECIFIC.getDisplayString()); + modes.put(ResourceSelectionMode.RELATIVE.name(), ResourceSelectionMode.RELATIVE.getDisplayString()); + modeSelectItem.setValueMap(modes); + modeSelectItem.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent event) { + ResourceSelectionMode mode = ResourceSelectionMode.valueOf(event.getValue().toString()); + switch (mode) { + case SELF: { + setOperationDropDownMenuValues(resourceType.getId(), null, null); + break; + } + case SPECIFIC: { + singleResourceTextItem.setValue("Pick a resource..."); + singleResourceTextItem.setAttribute(RESOURCE_ID_ATTRIBUTE, 0); + hideOperationDropDownMenu(); + break; + } + case RELATIVE: { + // TODO + hideOperationDropDownMenu(); + break; + } + } + } + }); + + dynamicForm.setFields(modeSelectItem, singleResourceTextItem, singleResourceButtonItem, ancestorTypeSelectItem, + operationSelectItem, operationArgumentsCanvasItem); + + addMember(dynamicForm); + + // prepopulate the form + ResourceOperationNotificationInfo notifInfo; + notifInfo = ResourceOperationNotificationInfo.load(getConfiguration(), getExtraConfiguration()); + ResourceSelectionMode mode = notifInfo.getMode(); + if (mode != null) { + modeSelectItem.setValue(mode.name()); + switch (mode) { + case SELF: { + setOperationDropDownMenuValues(resourceType.getId(), notifInfo.getOperationId(), notifInfo + .getOperationArguments()); + break; + } + case SPECIFIC: { + setSpecificResource(notifInfo.getResourceId(), notifInfo.getOperationId(), notifInfo + .getOperationArguments()); + break; + } + case RELATIVE: { + // TODO + break; + } + } + } else { + modeSelectItem.setValue(ResourceSelectionMode.SELF.name()); + setOperationDropDownMenuValues(resourceType.getId(), null, getExtraConfiguration()); + } + } + + /** + * This assumes the user or our code selected a specific operation from the drop down list. + * This will show the operation arguments as appropriate for the selected operation. + * + * @param operationId the selected operation; if 0 or less, selects the value of the drop down component + */ + @SuppressWarnings("unchecked") + private void selectOperation(int operationId) { + // someone changed the operation selection. + // there is a attribute on the select item that is a map<int,def> of all ops in the drop down list. + // if there is a non-empty map (i.e. we know what ops are available) we need to show the arguments. + // if there are no parameters needed for this operation, null out the extra config + LinkedHashMap<Integer, OperationDefinition> ops = (LinkedHashMap<Integer, OperationDefinition>) operationSelectItem + .getAttributeAsObject(OPERATION_DEFS_ATTRIBUTE); + if (ops == null || ops.isEmpty()) { + // why did this happen? there are no op defs so we should not be able to see any drop down menu anyway + hideOperationDropDownMenu(); + return; + } + + if (operationId <= 0) { + operationId = Integer.valueOf(operationSelectItem.getValue().toString()); + } + + OperationDefinition def = ops.get(operationId); + if (def != null) { + ConfigurationDefinition paramDef = def.getParametersConfigurationDefinition(); + if (paramDef != null) { + Configuration extraConfig = getExtraConfiguration(); + if (extraConfig != null) { + extraConfig.getMap().clear(); // changing the op, the old props are no longer valid + } else { + extraConfig = new Configuration(); + setExtraConfiguration(extraConfig); + } + showOperationArguments(paramDef, extraConfig); + } else { + setExtraConfiguration(null); + hideOperationArguments(); + } + } else { + hideOperationDropDownMenu(); + } + } + + /** + * Sets up the operation drop down menu by looking up the resource type and gets its operation definitions. + * If opId is non-null, the drop down menu will default to that operation. + * If args is non-null (and if opId is non-null), this will pre-populate the argument config editor. + * + * @param resourceTypeId the type whose operation definitions are to be shown in the operation drop down menu + * @param opId if not-null, the selected operation + * @param args if not-null (and opId is not null), this will prepopulate the argument config + */ + private void setOperationDropDownMenuValues(int resourceTypeId, final Integer opId, final Configuration args) { + ResourceTypeCriteria criteria = new ResourceTypeCriteria(); + criteria.addFilterId(resourceTypeId); + criteria.fetchOperationDefinitions(true); + GWTServiceLookup.getResourceTypeGWTService().findResourceTypesByCriteria(criteria, + new AsyncCallback<PageList<ResourceType>>() { + + @Override + public void onSuccess(PageList<ResourceType> result) { + if (result == null || result.size() != 1) { + CoreGUI.getErrorHandler().handleError("Error getting operations: " + result); + hideOperationDropDownMenu(); + return; + } + Set<OperationDefinition> set = result.get(0).getOperationDefinitions(); + if (set != null && set.size() > 0) { + LinkedHashMap<Integer, OperationDefinition> opDefs; + LinkedHashMap<String, String> valueMap; + opDefs = new LinkedHashMap<Integer, OperationDefinition>(set.size()); + valueMap = new LinkedHashMap<String, String>(set.size()); + for (OperationDefinition def : set) { + opDefs.put(def.getId(), def); + valueMap.put(String.valueOf(def.getId()), def.getDisplayName()); + } + operationSelectItem.setAttribute(OPERATION_DEFS_ATTRIBUTE, (Object) opDefs); + operationSelectItem.setValueMap(valueMap); + if (opId != null && opId > 0 && valueMap.containsKey(opId)) { + operationSelectItem.setValue(String.valueOf(opId)); + showOperationArguments(opDefs.get(opId).getParametersConfigurationDefinition(), args); + } else { + operationSelectItem.clearValue(); // sets it to the default + hideOperationArguments(); + selectOperation(Integer.valueOf(operationSelectItem.getValue().toString())); + } + operationSelectItem.show(); + markForRedraw(); + } else { + hideOperationDropDownMenu(); + } + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load the list of available operations", caught); + hideOperationDropDownMenu(); + } + }); + } + + /** + * For the SPECIFIC mode, sets the selected resource and optionally the operation. + * + * @param resourceId the resource selected + * @param opId if not-null, the selected operation + * @param args if not-null (and opId is not null), this will prepopulate the argument config + */ + private void setSpecificResource(final int resourceId, final Integer opId, final Configuration args) { + singleResourceTextItem.setAttribute(RESOURCE_ID_ATTRIBUTE, resourceId); + ResourceCriteria criteria = new ResourceCriteria(); + criteria.addFilterId(resourceId); + criteria.fetchResourceType(true); + GWTServiceLookup.getResourceService().findResourcesByCriteria(criteria, + new AsyncCallback<PageList<Resource>>() { + @Override + public void onSuccess(PageList<Resource> result) { + if (result.size() > 0) { + Resource resource = result.get(0); + singleResourceTextItem.setValue(resource.getName()); + setOperationDropDownMenuValues(resource.getResourceType().getId(), opId, args); + } else { + onFailure(new Exception("query returns no results")); + } + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot determine resource name", caught); + singleResourceTextItem.setValue(resourceId); + hideOperationDropDownMenu(); + } + }); + } + + private void hideOperationDropDownMenu() { + LinkedHashMap<Integer, OperationDefinition> ops = new LinkedHashMap<Integer, OperationDefinition>(0); + LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>(0); + operationSelectItem.setAttribute(OPERATION_DEFS_ATTRIBUTE, (Object) ops); + operationSelectItem.setValueMap(valueMap); + operationSelectItem.hide(); + hideOperationArguments(); + } + + private void hideOperationArguments() { + Canvas canvas = operationArgumentsCanvasItem.getCanvas(); + if (canvas != null) { + canvas.destroy(); + } + + operationArgumentsCanvasItem.setCanvas(new Label("")); + operationArgumentsCanvasItem.hide(); + markForRedraw(); + } + + private void showOperationArguments(ConfigurationDefinition def, Configuration config) { + Canvas canvas = operationArgumentsCanvasItem.getCanvas(); + if (canvas != null) { + canvas.destroy(); + } + + if (def != null) { + canvas = new ConfigurationEditor(extendLocatorId("opArgs"), def, config); + } else { + Label l = new Label("This operation does not take any parameters"); + l.setWrap(false); + canvas = l; + } + + operationArgumentsCanvasItem.setCanvas(canvas); + operationArgumentsCanvasItem.show(); + markForRedraw(); + } + + @Override + public boolean validate() { + try { + return true; + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Cannot save the notification configuration", e); + return false; + } + } + + private class ShowIfModeFunction implements FormItemIfFunction { + private final ResourceSelectionMode mode; + + public ShowIfModeFunction(ResourceSelectionMode mode) { + this.mode = mode; + } + + public boolean execute(FormItem item, Object value, DynamicForm form) { + String modeTypeString = form.getValue("modeSelectItem").toString(); + return mode.name().equals(modeTypeString); + } + } +}
commit 8ee9d9adfc34326567c3495f37f32c5c432b39c8 Author: John Mazzitelli mazz@redhat.com Date: Fri Oct 8 14:59:18 2010 -0400
extend the resource selector component so we have one that only allows a single resource to be selected extend that further to provide a window dialog "picker" that lets you pick one or more (ResourcePicker) or only one (SingleResourcePicker)
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java index e5a9d1f..91c622a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/selector/AbstractSelector.java @@ -263,6 +263,8 @@ public abstract class AbstractSelector<T> extends LocatableVLayout { } }
+ updateButtons(); // initialize their state + addMember(hlayout); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourcePicker.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourcePicker.java new file mode 100644 index 0000000..0731396 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourcePicker.java @@ -0,0 +1,202 @@ +/* + * 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.inventory.resource.selection; + +import java.util.HashSet; + +import com.google.gwt.user.client.Timer; +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.widgets.Label; +import com.smartgwt.client.widgets.events.CloseClickHandler; +import com.smartgwt.client.widgets.events.CloseClientEvent; +import com.smartgwt.client.widgets.form.fields.ButtonItem; +import com.smartgwt.client.widgets.form.fields.events.ClickEvent; +import com.smartgwt.client.widgets.form.fields.events.ClickHandler; + +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; + +/** + * A window dialog box that lets you pick one or more resources. + * + * @author John Mazzitelli + */ +public class ResourcePicker extends LocatableWindow { + + private final OkHandler okHandler; + private final CancelHandler cancelHandler; + + private ResourceSelector selector; + private Label warningLabel; + + public ResourcePicker(String locatorId, OkHandler okHandler, CancelHandler cancelHandler) { + super(locatorId); + + if (okHandler == null) { + throw new IllegalArgumentException("okHandler == null"); + } + + this.okHandler = okHandler; + this.cancelHandler = cancelHandler; + + if (getTitle() == null || getTitle().contains("Untitled")) { + setTitle(getDefaultTitle()); + } + + setShowModalMask(true); + setShowMinimizeButton(false); + setIsModal(true); + setWidth(600); + setHeight(500); + setAutoCenter(true); + centerInPage(); + + addCloseClickHandler(new CloseClickHandler() { + @Override + public void onCloseClick(CloseClientEvent event) { + cancel(); + } + }); + + LocatableVLayout layout = new LocatableVLayout(extendLocatorId("layout")); + layout.setLayoutAlign(Alignment.CENTER); + layout.setLayoutMargin(10); + + warningLabel = new Label(); + warningLabel.setContents(""); + warningLabel.setAlign(Alignment.CENTER); + warningLabel.setStyleName("WarnBlock"); + warningLabel.setAutoHeight(); + warningLabel.setWidth100(); + warningLabel.setWrap(false); + warningLabel.setVisible(false); + + selector = getResourceSelector(); + + LocatableDynamicForm form = new LocatableDynamicForm(extendLocatorId("buttons")); + form.setLayoutAlign(Alignment.CENTER); + + ButtonItem ok = new ButtonItem("ok", "OK"); + ok.setStartRow(true); + ok.setEndRow(false); + ok.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + ok(); + } + }); + ButtonItem cancel = new ButtonItem("cancel", "Cancel"); + cancel.addClickHandler(new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + cancel(); + } + }); + cancel.setStartRow(false); + cancel.setEndRow(true); + form.setFields(ok, cancel); + + layout.addMember(warningLabel); + layout.addMember(selector); + layout.addMember(form); + addItem(layout); + } + + protected OkHandler getOkHandler() { + return okHandler; + } + + protected CancelHandler getCancelHandler() { + return cancelHandler; + } + + protected String getDefaultTitle() { + return "Select Resources"; + } + + protected ResourceSelector getResourceSelector() { + if (selector == null) { + selector = createResourceSelector(); + } + return selector; + } + + protected ResourceSelector createResourceSelector() { + return new ResourceSelector(extendLocatorId("resourceSelector")); + } + + protected void ok() { + OkHandler handler = getOkHandler(); + HashSet<Integer> selection = selector.getSelection(); + + if (selection == null || selection.isEmpty()) { + showWarningMessage("Please select one of more resources"); + } else { + if (handler.ok(selection)) { + selector = null; + markForDestroy(); + } + } + } + + protected void cancel() { + CancelHandler handler = getCancelHandler(); + if (handler != null) { + handler.cancel(); + } + selector = null; + markForDestroy(); + } + + protected void showWarningMessage(String msg) { + warningLabel.setContents(msg); + warningLabel.show(); + markForRedraw(); + + // just show the warning message for a short time, hide it after a few seconds + Timer timer = new Timer() { + @Override + public void run() { + warningLabel.hide(); + markForRedraw(); + } + }; + timer.schedule(15000); + } + + /** + * The handler type used to be notified when the ok button is pressed. + * If false is returned by the ok method, the picker window will not + * close - true means the picker can close the window. + */ + public interface OkHandler { + public boolean ok(HashSet<Integer> resourceIdSelection); + } + + /** + * The handler type used to be notified when the cancel button is pressed + * or when the close-button in the title bar is pressed. + * The picker window will always be closed when canceled. + */ + public interface CancelHandler { + public void cancel(); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourcePicker.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourcePicker.java new file mode 100644 index 0000000..74f2a83 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourcePicker.java @@ -0,0 +1,57 @@ +/* + * 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.inventory.resource.selection; + +import java.util.HashSet; + +/** + * A window dialog box that lets you pick a single resource. + * + * @author John Mazzitelli + */ +public class SingleResourcePicker extends ResourcePicker { + + public SingleResourcePicker(String locatorId, OkHandler okHandler, CancelHandler cancelHandler) { + super(locatorId, okHandler, cancelHandler); + } + + @Override + protected String getDefaultTitle() { + return "Select a Resource"; + } + + @Override + protected ResourceSelector createResourceSelector() { + return new SingleResourceSelector(extendLocatorId("singleResourceSelector")); + } + + protected void ok() { + OkHandler handler = getOkHandler(); + HashSet<Integer> selection = getResourceSelector().getSelection(); + + if (selection == null || selection.size() != 1) { + showWarningMessage("Please select a resource"); + } else { + if (handler.ok(selection)) { + markForDestroy(); + } + } + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourceSelector.java new file mode 100644 index 0000000..e9ab0a4 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/SingleResourceSelector.java @@ -0,0 +1,47 @@ +/* + * 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.inventory.resource.selection; + +import org.rhq.core.domain.resource.ResourceType; + +/** + * This forces the user to only be able to select a single resource. + * + * @author John Mazzitelli + */ +public class SingleResourceSelector extends ResourceSelector { + + public SingleResourceSelector(String locatorId) { + super(locatorId); + } + + public SingleResourceSelector(String locatorId, ResourceType resourceTypeFilter, boolean forceResourceTypeFilter) { + super(locatorId, resourceTypeFilter, forceResourceTypeFilter); + } + + @Override + protected void updateButtons() { + addButton.setDisabled(!availableGrid.anySelected() || availableGrid.getTotalRows() == 0 + || assignedGrid.getTotalRows() > 0); + removeButton.setDisabled(!assignedGrid.anySelected()); + addAllButton.hide(); + removeAllButton.hide(); + } +}
commit f713382a57f067e46b22a55553a005685fb705c4 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 8 11:27:42 2010 -0400
fix metadata test failures
diff --git a/modules/core/client-api/src/test/resources/metadata-manager-test-1.xml b/modules/core/client-api/src/test/resources/metadata-manager-test-1.xml index 88929d1..bcdf81d 100644 --- a/modules/core/client-api/src/test/resources/metadata-manager-test-1.xml +++ b/modules/core/client-api/src/test/resources/metadata-manager-test-1.xml @@ -11,9 +11,9 @@ <c:regex-constraint expression="^\w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$"/> </c:constraint> </c:simple-property> - <c:simple-property name="bravo" type="string" description="String with options"> + <c:simple-property name="bravo" type="string" default="FirstOptionValue" description="String with options"> <c:property-options> - <c:option value="FirstOptionValue" name="First Option Name" default="true"/> + <c:option value="FirstOptionValue" name="First Option Name"/> <c:option value="SecondOptionValue" name="Second Option Name"/> <c:option value="ThirdOptionValue" name="Third Option Name"/> <c:option value="FourthOptionValue" name="Fourth Option Name"/> diff --git a/modules/core/client-api/src/test/resources/test-custom-jmx.xml b/modules/core/client-api/src/test/resources/test-custom-jmx.xml index 4f1e098..9f3c85f 100644 --- a/modules/core/client-api/src/test/resources/test-custom-jmx.xml +++ b/modules/core/client-api/src/test/resources/test-custom-jmx.xml @@ -14,11 +14,12 @@ description="A JMX Server that houses the custom MBeans that are to be managed">
<plugin-configuration> - <c:simple-property name="type" type="string" description="The EMS connection type for this JMX Server"> + <c:simple-property name="type" type="string" default="LocalVMTypeDescriptor" + description="The EMS connection type for this JMX Server"> <c:property-options> - <c:option value="LocalVMTypeDescriptor" name="Local" default="true"/> - <c:option value="org.mc4j.ems.connection.support.metadata.JBossConnectionTypeDescriptor" name="JBoss"/> - <c:option value="org.mc4j.ems.connection.support.metadata.Tomcat55ConnectionTypeDescriptor" name="Tomcat"/> + <c:option value="LocalVMTypeDescriptor" name="Local"/> + <c:option value="org.mc4j.ems.connection.support.metadata.JBossConnectionTypeDescriptor" name="JBoss"/> + <c:option value="org.mc4j.ems.connection.support.metadata.Tomcat55ConnectionTypeDescriptor" name="Tomcat"/> </c:property-options> </c:simple-property> <c:simple-property name="url" required="true" type="string" description="The connection url in the form of a JMXServiceURL"/>
commit 78763d27f78b03215853e6c2340189ea35911ee7 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 8 11:23:05 2010 -0400
make sure a subtab's view is refreshed when the user switches to that subtab
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/RefreshableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/RefreshableView.java new file mode 100644 index 0000000..162e950 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/RefreshableView.java @@ -0,0 +1,32 @@ +/* + * RHQ Management Platform + * Copyright (C) 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; + +/** + * A view that can refresh its content. + * + * @author Ian Springer + */ +public interface RefreshableView { + + /** + * Refresh this view, i.e. reload its data from the Server. + */ + void refresh(); +} \ No newline at end of file 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 3f01cde..2cbebe4 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 @@ -128,6 +128,7 @@ import org.rhq.core.domain.configuration.definition.constraint.IntegerRangeConst import org.rhq.core.domain.configuration.definition.constraint.RegexConstraint; import org.rhq.core.domain.resource.ResourceType; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.table.PropertyGrid; import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTServiceAsync; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; 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 b25b625..de29950 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 @@ -49,6 +49,7 @@ 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.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** 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 f5c9a40..917946a 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 @@ -56,6 +56,7 @@ import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; @@ -65,7 +66,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableListGrid; * @author Greg Hinkle * @author Ian Springer */ -public class Table extends LocatableHLayout { +public class Table extends LocatableHLayout implements RefreshableView {
private static final SelectionEnablement DEFAULT_SELECTION_ENABLEMENT = SelectionEnablement.ALWAYS;
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 74c5ca3..84ccc47 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 @@ -31,6 +31,7 @@ import com.smartgwt.client.widgets.layout.Layout; import org.rhq.core.domain.authz.Permission; import org.rhq.enterprise.gui.coregui.client.BookmarkableView; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.ViewPath; import org.rhq.enterprise.gui.coregui.client.components.tab.SubTab; import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTab; @@ -221,8 +222,11 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo
// Handle any remaining view items (e.g. id of a selected item in a subtab that contains a Master-Details view). Canvas subView = subtab.getCanvas(); + if (subView instanceof RefreshableView) { + ((RefreshableView)subView).refresh(); + } if (subView instanceof BookmarkableView) { - ((BookmarkableView) subView).renderView(viewPath); + ((BookmarkableView)subView).renderView(viewPath); }
this.tabSet.markForRedraw(); 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 cef496a..4e9d337 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 @@ -41,6 +41,7 @@ import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.GroupConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.GroupMemberConfiguration; @@ -60,7 +61,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * * @author Ian Springer */ -public class GroupResourceConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { +public class GroupResourceConfigurationEditView extends LocatableVLayout + implements PropertyValueChangeListener, RefreshableView { private final ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
private ResourceGroup group; @@ -81,10 +83,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme @Override protected void onDraw() { super.onDraw(); - build(); - }
- public void build() { ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100();
@@ -98,9 +97,9 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme } }); toolStrip.addMember(saveButton); - + addMember(toolStrip); - reloadConfiguration(); + refresh();
if (!this.resourcePermission.isConfigureWrite()) { Message message = new Message("You do not have permission to edit this group's configuration.", @@ -109,12 +108,14 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme } }
- private void reloadConfiguration() { + @Override + public void refresh() { this.saveButton.disable(); if (editor != null) { editor.destroy(); removeMember(editor); } + // TODO (ips): If editor != null, use editor.reload() instead.
loadConfigurationDefinition(); loadConfigurations(); @@ -191,7 +192,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme "Configuration update initiated for " + group.getResourceType().getName() + " compatible group '" + group.getName() + "'.", Message.Severity.Info)); - reloadConfiguration(); + refresh(); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java index d616f81..875fc0d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java @@ -35,6 +35,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; @@ -50,7 +51,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle * @author Ian Springer */ -public class ResourceConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { +public class ResourceConfigurationEditView extends LocatableVLayout + implements PropertyValueChangeListener, RefreshableView { private Resource resource; private ResourcePermission resourcePermission; private ConfigurationEditor editor; @@ -66,10 +68,7 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P @Override protected void onDraw() { super.onDraw(); - build(); - }
- public void build() { ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100();
@@ -82,9 +81,9 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P } }); toolStrip.addMember(saveButton); - + addMember(toolStrip); - reloadConfiguration(); + refresh();
if (!this.resourcePermission.isConfigureWrite()) { Message message = new Message("You do not have permission to edit this Resource's configuration.", @@ -93,8 +92,10 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P } }
- private void reloadConfiguration() { + @Override + public void refresh() { this.saveButton.disable(); + if (editor != null) { editor.destroy(); removeMember(editor); @@ -104,9 +105,10 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P editor.setOverflow(Overflow.AUTO); editor.addPropertyValueChangeListener(this); editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); - addMember(editor); + addMember(editor); + // TODO (ips): If editor != null, use editor.reload() instead. } - + private void save() { Configuration updatedConfiguration = editor.getConfiguration();
@@ -121,7 +123,7 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P new Message("Configuration updated.", "Configuration updated for Resource [" + resource.getName() + "].", Message.Severity.Info)); - reloadConfiguration(); + refresh(); } }); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java index 703f9d4..b3a5709 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java @@ -34,6 +34,7 @@ import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.RefreshableView; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; @@ -49,7 +50,8 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle * @author Ian Springer */ -public class PluginConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { +public class PluginConfigurationEditView extends LocatableVLayout + implements PropertyValueChangeListener, RefreshableView { private Resource resource; private ResourcePermission resourcePermission; private ConfigurationEditor editor; @@ -65,10 +67,7 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro @Override protected void onDraw() { super.onDraw(); - build(); - }
- public void build() { ToolStrip toolStrip = new ToolStrip(); toolStrip.setWidth100();
@@ -82,9 +81,9 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro }); this.saveButton.disable(); toolStrip.addMember(this.saveButton); - + addMember(toolStrip); - reloadConfiguration(); + refresh();
if (!this.resourcePermission.isInventory()) { Message message = new Message("You do not have permission to edit this Resource's connection settings.", @@ -93,8 +92,10 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro } }
- private void reloadConfiguration() { + @Override + public void refresh() { this.saveButton.disable(); + if (editor != null) { editor.destroy(); removeMember(editor); @@ -105,6 +106,7 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro editor.addPropertyValueChangeListener(this); editor.setReadOnly(!this.resourcePermission.isInventory()); addMember(editor); + // TODO (ips): If editor != null, use editor.reload() instead. }
private void save() { @@ -120,7 +122,7 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro CoreGUI.getMessageCenter().notify( new Message("Connection settings updated.", "Connection settings updated for Resource [" + resource.getName() + "].")); - reloadConfiguration(); + refresh(); } }); }
commit f1da64dcb747835917e43e45361236ced104c509 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 8 10:24:39 2010 -0400
fix compile error in ConfigurationMetadataManager; improve PropertyDefinitionEnumeration's toString() impl
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java index a121510..96ca8ac 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java @@ -151,6 +151,11 @@ public class PropertyDefinitionEnumeration implements Serializable {
@Override public String toString() { - return "PropertyDefinitionEnumeration: " + value; + return "PropertyDefinitionEnumeration{" + + "id=" + id + + ", name='" + name + ''' + + ", value='" + value + ''' + + ", orderIndex=" + orderIndex + + '}'; } } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java index f46c7a4..bcf5e47 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java @@ -394,8 +394,8 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa for (PropertyDefinitionEnumeration pde : changed) { for (PropertyDefinitionEnumeration nPde : newOptions) { if (nPde.equals(pde)) { - pde.setDefault(nPde.isDefault()); - pde.setValue(nPde.getValue()); + pde.setName(nPde.getName()); + pde.setOrderIndex(nPde.getOrderIndex()); } } }
commit b531bbe8b661e46cb872338c2c19a6804faff396 Author: Ian Springer ian.springer@redhat.com Date: Fri Oct 8 10:23:30 2010 -0400
first functional cut of resource group config editor!
diff --git a/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/MetadataManagerTest.java b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/MetadataManagerTest.java index 9ef0ca8..2df1e43 100644 --- a/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/MetadataManagerTest.java +++ b/modules/core/client-api/src/test/java/org/rhq/core/clientapi/agent/metadata/test/MetadataManagerTest.java @@ -213,8 +213,7 @@ public class MetadataManagerTest { assert bravo.getEnumeratedValues().size() == 4; assert bravo.getEnumeratedValues().get(0).getName().equals("First Option Name"); assert bravo.getEnumeratedValues().get(0).getValue().equals("FirstOptionValue"); - assert bravo.getEnumeratedValues().get(0).isDefault(); - assert !bravo.getEnumeratedValues().get(1).isDefault(); + assert bravo.getEnumeratedValues().get(0).getValue().equals(def.getDefaultTemplate().getConfiguration().getSimpleValue("bravo", null));
assert def.getPropertyDefinitionSimple("charlie").getType() == PropertySimpleType.BOOLEAN; assert def.getPropertyDefinitionSimple("delta").getType() == PropertySimpleType.INTEGER; 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 310f59f..3f01cde 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 @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; +import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; @@ -73,6 +74,9 @@ import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.form.validator.CustomValidator; import com.smartgwt.client.widgets.form.validator.FloatRangeValidator; import com.smartgwt.client.widgets.form.validator.IntegerRangeValidator; +import com.smartgwt.client.widgets.form.validator.IsBooleanValidator; +import com.smartgwt.client.widgets.form.validator.IsFloatValidator; +import com.smartgwt.client.widgets.form.validator.IsIntegerValidator; import com.smartgwt.client.widgets.form.validator.LengthRangeValidator; import com.smartgwt.client.widgets.form.validator.RegExpValidator; import com.smartgwt.client.widgets.form.validator.Validator; @@ -668,8 +672,7 @@ public class ConfigurationEditor extends LocatableVLayout { PropertyDefinition propertyDefinition, boolean isValid) { boolean wasValidBefore = this.invalidPropertyNames.isEmpty(); - Property topLevelProperty = getTopLevelProperty(property); - validate(); + Property topLevelProperty = getTopLevelProperty(property); if (isValid) { this.invalidPropertyNames.remove(topLevelProperty.getName()); } else { @@ -1243,45 +1246,37 @@ public class ConfigurationEditor extends LocatableVLayout { } } else { switch (propertyDefinitionSimple.getType()) { - - case STRING: - case FILE: - case DIRECTORY: - valueItem = new TextItem(); - valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); - break; - case LONG_STRING: - valueItem = new TextAreaItem(); - valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); - break; - case PASSWORD: - valueItem = new PasswordItem(); - valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); - break; - case BOOLEAN: - valueItem = new RadioGroupItem(); - LinkedHashMap<String, String> valMap = new LinkedHashMap<String, String>(); - valMap.put("true", "Yes"); - valMap.put("false", "No"); - valueItem.setValueMap(valMap); - valueItem.setValue(propertySimple == null || propertySimple.getStringValue() == null ? false : propertySimple - .getBooleanValue()); - break; - case INTEGER: - case LONG: - valueItem = new IntegerItem(); - if (propertySimple != null && propertySimple.getStringValue() != null) - valueItem.setValue(propertySimple.getLongValue()); - break; - case FLOAT: - case DOUBLE: - valueItem = new FloatItem(); - valueItem.setValue(propertySimple == null || propertySimple.getStringValue() == null ? 0 : propertySimple - .getDoubleValue()); - break; + case STRING: + case FILE: + case DIRECTORY: + valueItem = new TextItem(); + break; + case LONG_STRING: + valueItem = new TextAreaItem(); + break; + case PASSWORD: + valueItem = new PasswordItem(); + break; + case BOOLEAN: + valueItem = new RadioGroupItem(); + LinkedHashMap<String, String> valMap = new LinkedHashMap<String, String>(); + valMap.put("true", "Yes"); + valMap.put("false", "No"); + valueItem.setValueMap(valMap); + break; + case INTEGER: + case LONG: + valueItem = new IntegerItem(); + break; + case FLOAT: + case DOUBLE: + valueItem = new FloatItem(); + break; } }
+ valueItem.setDefaultValue((String)null); + valueItem.setValue(propertySimple.getStringValue()); valueItem.setRequired(propertyDefinitionSimple.isRequired());
List<Validator> validators = buildValidators(propertyDefinitionSimple, propertySimple); @@ -1339,7 +1334,7 @@ public class ConfigurationEditor extends LocatableVLayout { public void onChange(ChangeEvent changeEvent) { Boolean isUnset = (Boolean) changeEvent.getValue(); if (isUnset) { - valueItem.getForm().setValue(valueItem.getName(), (String)null); + setValue(valueItem, null); valueItem.setDisabled(true); } else { valueItem.setDisabled(false); @@ -1350,12 +1345,14 @@ public class ConfigurationEditor extends LocatableVLayout { } });
+/* valueItem.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent changeEvent) { - String value = (String)changeEvent.getValue(); + Object value = changeEvent.getValue(); unsetItem.setDisabled(value == null); } }); +*/
item = unsetItem; } else { @@ -1385,19 +1382,34 @@ public class ConfigurationEditor extends LocatableVLayout { return !isInvalidRequiredProperty && (propertyDefinition.isReadOnly() || this.readOnly); }
- private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, Property property) { + protected List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, Property property) { List<Validator> validators = new ArrayList<Validator>();
+ Validator typeValidator = null; switch (propertyDefinition.getType()) { case STRING: case LONG_STRING: case FILE: case DIRECTORY: - LengthRangeValidator validator = new LengthRangeValidator(); - validator.setMax(PropertySimple.MAX_VALUE_LENGTH); - validators.add(validator); + LengthRangeValidator lengthRangeValidator = new LengthRangeValidator(); + lengthRangeValidator.setMax(PropertySimple.MAX_VALUE_LENGTH); + typeValidator = lengthRangeValidator; + break; + case BOOLEAN: + typeValidator = new IsBooleanValidator(); + break; + case INTEGER: + case LONG: + typeValidator = new IsIntegerValidator(); + break; + case FLOAT: + case DOUBLE: + typeValidator = new IsFloatValidator(); break; } + if (typeValidator != null) { + validators.add(typeValidator); + }
Set<Constraint> constraints = propertyDefinition.getConstraints(); if (constraints != null) { @@ -1527,12 +1539,31 @@ public class ConfigurationEditor extends LocatableVLayout { popup.show(); }
+ protected static void setValue(FormItem item, Object value) { + if (value instanceof String) { + item.setValue((String)value); + } else if (value instanceof Boolean) { + item.setValue((Boolean)value); + } else if (value instanceof Integer) { + item.setValue((Integer)value); + } else if (value instanceof Float) { + item.setValue((Float)value); + } else if (value instanceof Double) { + item.setValue((Double)value); + } else if (value instanceof Date) { + item.setValue((Date)value); + } else { + String stringValue = (value != null) ? value.toString() : null; + item.setValue(stringValue); + } + } + private static class PropertyDefinitionComparator implements Comparator<PropertyDefinition> { public int compare(PropertyDefinition o1, PropertyDefinition o2) { return new Integer(o1.getOrder()).compareTo(o2.getOrder()); } } - + private class PluginReportedErrorValidator extends CustomValidator { private Property property;
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 463ee42..b25b625 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 @@ -35,6 +35,8 @@ import com.smartgwt.client.widgets.form.events.ItemChangedHandler; import com.smartgwt.client.widgets.form.fields.FormItem; import com.smartgwt.client.widgets.form.fields.FormItemIcon; import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; +import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.form.fields.events.FormItemClickHandler; import com.smartgwt.client.widgets.form.fields.events.FormItemIconClickEvent; import com.smartgwt.client.widgets.layout.HLayout; @@ -57,6 +59,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ public class GroupConfigurationEditor extends ConfigurationEditor { private List<GroupMemberConfiguration> memberConfigurations; + private Map<String, FormItem> valueItemNameToUnsetItemMap = new HashMap<String, FormItem>();
public GroupConfigurationEditor(String locatorId, ConfigurationDefinition configurationDefinition, List<GroupMemberConfiguration> memberConfigurations) { @@ -78,47 +81,62 @@ public class GroupConfigurationEditor extends ConfigurationEditor { @Override protected FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, final PropertySimple propertySimple) { - final FormItem item; - boolean isAggregate = isAggregateProperty(propertySimple); - if (!isAggregate || isHomogeneous(propertySimple)) { - item = super.buildSimpleField(propertyDefinitionSimple, propertySimple); - } else { - item = new StaticTextItem(); - item.setDefaultValue("<span style='color: red'><i>Member Values Differ</i></span>"); - item.setShowTitle(false); - } + final FormItem item = super.buildSimpleField(propertyDefinitionSimple, propertySimple);
+ boolean isAggregate = isAggregateProperty(propertySimple); if (isAggregate) { // Add the icon that user can click to edit the member values. FormItemIcon icon = new FormItemIcon(); icon.setSrc("[SKIN]/actions/edit.png"); icon.setName("Edit Member Values"); + icon.setNeverDisable(true); icon.addFormItemClickHandler(new FormItemClickHandler() { - public void onFormItemClick(FormItemIconClickEvent event) { - // TODO: Pass the actual index, rather than null, if the prop is inside a list. - displayMemberValuesEditor(extendLocatorId("MemberValuesEditor"), propertyDefinitionSimple, item, - propertySimple, null); + public void onFormItemClick(FormItemIconClickEvent event) { + // TODO: Pass the actual index, rather than null, if the prop is inside a list. + displayMemberValuesEditor(extendLocatorId("MemberValuesEditor"), propertyDefinitionSimple, + propertySimple, null, item); + } + }); + // TODO: Figure out a way to add a tooltip to the icon. + item.setIcons(icon); + + if (!isHomogeneous(propertySimple)) { + updateHeterogeneousValueItem(item); + } + + item.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent changedEvent) { + Object value = changedEvent.getValue(); + for (GroupMemberConfiguration memberConfiguration : memberConfigurations) { + Configuration configuration = memberConfiguration.getConfiguration(); + PropertySimple memberPropertySimple = + getPropertySimple(configuration, propertyDefinitionSimple, propertySimple, null); + memberPropertySimple.setValue(value); + } } }); - // TODO: Figure out a way to add a tooltip to the icon. - item.setIcons(icon); }
return item; }
- private boolean isAggregateProperty(PropertySimple propertySimple) { - return (propertySimple.getConfiguration() == getConfiguration()); - } - - private static Boolean isHomogeneous(PropertySimple propertySimple) { - Boolean override = propertySimple.getOverride(); - return (override != null && override); + @Override + protected FormItem buildUnsetItem(final PropertyDefinitionSimple propertyDefinitionSimple, final PropertySimple propertySimple, + final FormItem valueItem) { + final FormItem unsetItem = super.buildUnsetItem(propertyDefinitionSimple, propertySimple, valueItem); + if (!isHomogeneous(propertySimple) && isAggregateProperty(propertySimple)) { + // non-homogeneous aggregate property (i.e. members have mixed values) + unsetItem.setValue(false); + unsetItem.setDisabled(true); + } + this.valueItemNameToUnsetItemMap.put(valueItem.getName(), unsetItem); + return unsetItem; }
- private void displayMemberValuesEditor(String locatorId, PropertyDefinitionSimple propertyDefinitionSimple, - final FormItem aggregateValueItem, - final PropertySimple aggregatePropertySimple, Integer index) { + private void displayMemberValuesEditor(String locatorId, final PropertyDefinitionSimple propertyDefinitionSimple, + final PropertySimple aggregatePropertySimple, + Integer index, final FormItem aggregateValueItem + ) { LocatableVLayout layout = new LocatableVLayout(locatorId); layout.setHeight100();
@@ -151,14 +169,13 @@ public class GroupConfigurationEditor extends ConfigurationEditor { final List<FormItem> valueItems = new ArrayList<FormItem>(this.memberConfigurations.size()); final List<FormItem> unsetItems = new ArrayList<FormItem>(this.memberConfigurations.size()); for (GroupMemberConfiguration memberConfiguration : this.memberConfigurations) { - // TODO: Format the disambiguated member name. String memberName = memberConfiguration.getLabel(); StaticTextItem memberItem = new StaticTextItem(); memberItem.setShowTitle(false); memberItem.setDefaultValue(memberName); items.add(memberItem); Configuration configuration = memberConfiguration.getConfiguration(); - PropertySimple memberPropertySimple = getPropertySimple(configuration, propertyDefinitionSimple, index); + PropertySimple memberPropertySimple = getPropertySimple(configuration, propertyDefinitionSimple, aggregatePropertySimple, index); memberProperties.put(memberName, memberPropertySimple); FormItem valueItem = buildSimpleField(propertyDefinitionSimple, memberPropertySimple); valueItem.setAttribute("rhq:property", memberPropertySimple); @@ -170,7 +187,7 @@ public class GroupConfigurationEditor extends ConfigurationEditor { valueItem.setEndRow(true); } form.setItems(items.toArray(new FormItem[items.size()])); - + final Window popup = new Window(); popup.setTitle("Member Values for Property '" + propertyDefinitionSimple.getName()); popup.setWidth(800); @@ -185,28 +202,43 @@ public class GroupConfigurationEditor extends ConfigurationEditor { okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { boolean valuesHomogeneous = true; - String firstValue = (String)valueItems.get(0).getValue(); + Object firstValue = valueItems.get(0).getValue(); for (FormItem valueItem : valueItems) { - String value = (String)valueItem.getValue(); + Object value = valueItem.getValue(); if ((value != null && !value.equals(firstValue)) || (value == null && firstValue != null)) { valuesHomogeneous = false; } PropertySimple memberPropertySimple = (PropertySimple)valueItem.getAttributeAsObject("rhq:property"); - memberPropertySimple.setStringValue(value); + memberPropertySimple.setValue(value); memberPropertySimple.setErrorMessage(null); } + + FormItem aggregateUnsetItem = valueItemNameToUnsetItemMap.get(aggregateValueItem.getName()); + aggregateUnsetItem.setDisabled(!valuesHomogeneous); if (valuesHomogeneous) { - // Values are all the same, so update the value of the aggregate property and set its override flag to true. - aggregateValueItem.getForm().setValue(aggregateValueItem.getName(), firstValue); - // TODO: Will this cause a value changed event to fire for the aggregate form item? - aggregatePropertySimple.setStringValue(firstValue); + // Update the value of the aggregate property and set its override flag to true. + aggregatePropertySimple.setValue(firstValue); aggregatePropertySimple.setOverride(true); + + // Set the aggregate value item's value to the homogeneous value, enable it, and make sure it has + // validators set. + aggregateValueItem.setDisabled(false); + setValue(aggregateValueItem, firstValue); + aggregateValueItem.setTooltip(null); + aggregateValueItem.setValidateOnChange(true); + aggregateValueItem.setValidateOnExit(true); + + aggregateUnsetItem.setValue(firstValue == null); } else { - aggregatePropertySimple.setStringValue(null); + aggregatePropertySimple.setValue(null); aggregatePropertySimple.setOverride(false); + + updateHeterogeneousValueItem(aggregateValueItem); + + aggregateUnsetItem.setValue((String)null); } - // TODO: Figure out a way to update the aggregate Unset checkbox. + popup.destroy(); } }); @@ -237,8 +269,17 @@ public class GroupConfigurationEditor extends ConfigurationEditor { popup.show(); }
+ private void updateHeterogeneousValueItem(FormItem item) { + item.setDisabled(true); + item.setValidateOnChange(false); + item.setValidateOnExit(false); + item.setValue("MEMBER VALUES DIFFER"); + item.setTooltip("Member values differ - click icon to edit them."); + } + private PropertySimple getPropertySimple(Configuration configuration, - PropertyDefinitionSimple propertyDefinitionSimple, Integer index) { + PropertyDefinitionSimple propertyDefinitionSimple, + PropertySimple aggregatePropertySimple, Integer index) { LinkedList<PropertyDefinition> propertyDefinitionHierarchy = new LinkedList<PropertyDefinition>(); PropertyDefinition currentPropertyDefinition = propertyDefinitionSimple; do { @@ -266,7 +307,21 @@ public class GroupConfigurationEditor extends ConfigurationEditor { } }
- return (PropertySimple)property; + PropertySimple propertySimple = (PropertySimple)property; + if (isHomogeneous(aggregatePropertySimple)) { + // If the aggregate property has its override bit set, make sure the member property has the same value. + propertySimple.setStringValue(aggregatePropertySimple.getStringValue()); + } + return propertySimple; + } + + private boolean isAggregateProperty(PropertySimple propertySimple) { + return (getConfiguration(propertySimple) == getConfiguration()); + } + + private static Boolean isHomogeneous(PropertySimple propertySimple) { + Boolean override = propertySimple.getOverride(); + return (override != null && override); }
private static Configuration getConfiguration(Property property) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java index e0be6ef..f96d603 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java @@ -2,10 +2,8 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
import java.util.List;
-import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; -import org.rhq.core.domain.configuration.RawConfiguration; import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @@ -13,14 +11,15 @@ import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; -import org.rhq.enterprise.server.configuration.ConfigurationUpdateStillInProgressException;
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
+/** + * + */ @RemoteServiceRelativePath("ConfigurationGWTService") public interface ConfigurationGWTService extends RemoteService { - Configuration getPluginConfiguration(int resourceId);
ConfigurationDefinition getPluginConfigurationDefinition(int resourceTypeId); @@ -40,6 +39,11 @@ public interface ConfigurationGWTService extends RemoteService {
List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId);
- RawConfiguration dummy(RawConfiguration config); + List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup(int groupId); + + void updateResourceConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> resourceConfigurations); + + void updatePluginConfigurationsForGroup(int groupId, List<ResourceConfigurationComposite> pluginConfigurations);
+ //RawConfiguration dummy(RawConfiguration config); } 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 03cfc83..cef496a 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 @@ -26,7 +26,6 @@ import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -92,6 +91,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme toolStrip.addMember(new LayoutSpacer());
this.saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + this.saveButton.setTooltip("Update the configurations of all group members."); this.saveButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { save(); @@ -176,26 +176,34 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme }); }
- private void save() { - // TODO - - SC.say("Boo!"); -/* - GWTServiceLookup.getConfigurationService().updateResourceConfiguration(resource.getId(), updatedConfiguration, - new AsyncCallback<ResourceConfigurationUpdate>() { + private void save() { + List<ResourceConfigurationComposite> resourceConfigurations = convertToCompositeList(); + GWTServiceLookup.getConfigurationService().updateResourceConfigurationsForGroup(this.group.getId(), + resourceConfigurations, new AsyncCallback<Void>() { public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to update configuration.", caught); + CoreGUI.getErrorHandler().handleError("Configuration update failed for " + + group.getResourceType().getName() + " compatible group '" + group.getName() + "'.", caught); }
- public void onSuccess(ResourceConfigurationUpdate result) { + public void onSuccess(Void result) { CoreGUI.getMessageCenter().notify( - new Message("Configuration updated.", - "Configuration updated for Resource [" + resource.getName() + "].", + new Message("Configuration update initiated.", + "Configuration update initiated for " + group.getResourceType().getName() + + " compatible group '" + group.getName() + "'.", Message.Severity.Info)); reloadConfiguration(); } }); -*/ + } + + private List<ResourceConfigurationComposite> convertToCompositeList() { + List<ResourceConfigurationComposite> resourceConfigurations = + new ArrayList<ResourceConfigurationComposite>(this.memberConfigurations.size()); + for (GroupMemberConfiguration memberConfiguration : this.memberConfigurations) { + resourceConfigurations.add(new ResourceConfigurationComposite(memberConfiguration.getId(), + memberConfiguration.getConfiguration())); + } + return resourceConfigurations; }
@Override diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java index 63fa33f..e20bd50 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java @@ -1,14 +1,12 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map;
-import com.allen_sauer.gwt.log.client.Log; - import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; -import org.rhq.core.domain.configuration.RawConfiguration; import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @@ -34,6 +32,13 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen
private static final long serialVersionUID = 1L;
+ private static final IntExtractor<ResourceConfigurationComposite> RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR = + new IntExtractor<ResourceConfigurationComposite>() { + public int extract(ResourceConfigurationComposite configurationComposite) { + return configurationComposite.getResourceId(); + } + }; + private ConfigurationManagerLocal configurationManager = LookupUtil.getConfigurationManager(); private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager(); @@ -125,14 +130,7 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen ResourceGroup group = this.groupManager.getResourceGroup(getSessionSubject(), groupId); Map<Integer,Configuration> configurations = this.configurationManager.getResourceConfigurationMapForCompatibleGroup(group); - List<ResourceConfigurationComposite> configurationComposites = - new ArrayList<ResourceConfigurationComposite>(configurations.size()); - for (Integer resourceId : configurations.keySet()) { - Configuration configuration = configurations.get(resourceId); - ResourceConfigurationComposite configurationComposite = - new ResourceConfigurationComposite(resourceId, configuration); - configurationComposites.add(configurationComposite); - } + List<ResourceConfigurationComposite> configurationComposites = convertToCompositesList(configurations);
// Disambiguate - i.e. generate unambiguous Resource names for each of the Resource id's. List<DisambiguationReport<ResourceConfigurationComposite>> disambiguatedConfigurationComposites = resourceManager @@ -146,24 +144,70 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
- public RawConfiguration dummy(RawConfiguration config) { - Log.info(config.getPath()); - return new RawConfiguration(); - // Dummy method for gwt compiler + public List<DisambiguationReport<ResourceConfigurationComposite>> findPluginConfigurationsForGroup( + int groupId) { + try { + Map<Integer,Configuration> configurations = + this.configurationManager.getPluginConfigurationsForCompatibleGroup(getSessionSubject(), groupId); + List<ResourceConfigurationComposite> configurationComposites = convertToCompositesList(configurations); + + // Disambiguate - i.e. generate unambiguous Resource names for each of the Resource id's. + List<DisambiguationReport<ResourceConfigurationComposite>> disambiguatedConfigurationComposites = resourceManager + .disambiguate(configurationComposites, RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR, + DefaultDisambiguationUpdateStrategies.getDefault()); + + return SerialUtility.prepare(disambiguatedConfigurationComposites, + "ConfigurationService.findPluginConfigurationsForGroup"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public void updateResourceConfigurationsForGroup(int groupId, + List<ResourceConfigurationComposite> resourceConfigurations) { + try { + Map<Integer, Configuration> configurations = convertToMap(resourceConfigurations); + this.configurationManager.scheduleGroupResourceConfigurationUpdate(getSessionSubject(), groupId, configurations); + } catch (RuntimeException e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + + public void updatePluginConfigurationsForGroup(int groupId, + List<ResourceConfigurationComposite> pluginConfigurations) { + try { + Map<Integer, Configuration> configurations = convertToMap(pluginConfigurations); + this.configurationManager.scheduleGroupPluginConfigurationUpdate(getSessionSubject(), groupId, configurations); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } }
/* - public ResourceConfigurationComposite dummy(ResourceConfigurationComposite resourceConfigurationComposite) { - return new ResourceConfigurationComposite(); - // Dummy method for gwt compiler + // Dummy method for gwt compiler + public RawConfiguration dummy(RawConfiguration config) { + Log.info(config.getPath()); + return new RawConfiguration(); } */
- private static final IntExtractor<ResourceConfigurationComposite> RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR = - new IntExtractor<ResourceConfigurationComposite>() { - public int extract(ResourceConfigurationComposite configurationComposite) { - return configurationComposite.getResourceId(); + private List<ResourceConfigurationComposite> convertToCompositesList(Map<Integer, Configuration> configurations) { + List<ResourceConfigurationComposite> configurationComposites = + new ArrayList<ResourceConfigurationComposite>(configurations.size()); + for (Integer resourceId : configurations.keySet()) { + Configuration configuration = configurations.get(resourceId); + ResourceConfigurationComposite configurationComposite = + new ResourceConfigurationComposite(resourceId, configuration); + configurationComposites.add(configurationComposite); } - }; + return configurationComposites; + }
+ private Map<Integer, Configuration> convertToMap(List<ResourceConfigurationComposite> resourceConfigurations) { + Map<Integer, Configuration> configurations = new HashMap<Integer, Configuration>(resourceConfigurations.size()); + for (ResourceConfigurationComposite resourceConfiguration : resourceConfigurations) { + configurations.put(resourceConfiguration.getResourceId(), resourceConfiguration.getConfiguration()); + } + return configurations; + } }
commit 5f911a17a3d287a8b4b72ec4059bbb27822fc3ac Author: Heiko W. Rupp hwr@redhat.com Date: Fri Oct 8 14:38:39 2010 +0200
AlertDefinitions need a name ...
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java index 8e62cf0..c95f0d4 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java @@ -334,6 +334,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest {
AlertDefinition def = new AlertDefinition(); def.addCondition(goingDown); + def.setName("Test alert definition"); alertDefinitionManager.createAlertDefinition(overlord,def,res.getId());
for (int MULTI : ROUNDS) {
commit 9205aab63fc04adbe36aca531fe33fcf881eb48b Author: Heiko W. Rupp hwr@redhat.com Date: Fri Oct 8 14:27:39 2010 +0200
Add a test that also stresses the alert subsystem.
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java index a96ac9b..8e62cf0 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/performance/test/AvailabilityInsertPurgeTest.java @@ -24,11 +24,16 @@ import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query;
+import org.rhq.core.domain.alert.AlertCondition; +import org.rhq.core.domain.alert.AlertConditionCategory; +import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.discovery.AvailabilityReport; import org.rhq.core.domain.measurement.Availability; import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Agent; import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.server.alert.AlertDefinitionManagerLocal; import org.rhq.enterprise.server.core.AgentManagerLocal; import org.rhq.enterprise.server.measurement.AvailabilityManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; @@ -59,10 +64,13 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { AvailabilityManagerLocal availabilityManager; AgentManagerLocal agentManager; SystemManagerLocal systemManager; + AlertDefinitionManagerLocal alertDefinitionManager; private static final int MILLIS_APART = 2000; private static final String ROUND__FORMAT = "Round %6d"; private static final String PURGE__FORMAT = "Purge %6d"; private static final int[] ROUNDS = new int[]{1000,2000,3000,5000,10000}; + // private static final int[] ROUNDS = new int[]{10,20}; + private Subject overlord ;
@BeforeMethod public void beforeMethod() { @@ -71,6 +79,8 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { this.resourceManager = LookupUtil.getResourceManager(); this.agentManager = LookupUtil.getAgentManager(); this.systemManager = LookupUtil.getSystemManager(); + this.alertDefinitionManager = LookupUtil.getAlertDefinitionManager(); + this.overlord = LookupUtil.getSubjectManager().getOverlord(); } catch (Throwable t) { // Catch RuntimeExceptions and Errors and dump their stack trace, because Surefire will completely swallow them // and throw a cryptic NPE (see http://jira.codehaus.org/browse/SUREFIRE-157)! @@ -101,7 +111,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { if (l!=0) { throw new IllegalStateException("Availabilities table is not empty"); } - systemManager.vacuum(LookupUtil.getSubjectManager().getOverlord(),new String[]{"rhq_availability"}); + systemManager.vacuum(overlord,new String[]{"rhq_availability"});
for (int MULTI : ROUNDS) { String round = String.format(ROUND__FORMAT, MULTI); @@ -128,7 +138,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { availabilityManager.purgeAvailabilities(t1); endTiming(String.format(PURGE__FORMAT,MULTI)); // Vacuum the db - systemManager.vacuum(LookupUtil.getSubjectManager().getOverlord(),new String[]{"rhq_availability"}); + systemManager.vacuum(overlord,new String[]{"rhq_availability"});
}
@@ -195,7 +205,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { availabilityManager.purgeAvailabilities(t1); endTiming(String.format(PURGE__FORMAT,MULTI)); // Vacuum the db - systemManager.vacuum(LookupUtil.getSubjectManager().getOverlord(),new String[]{"rhq_availability"}); + systemManager.vacuum(overlord,new String[]{"rhq_availability"});
}
@@ -262,7 +272,7 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest { availabilityManager.purgeAvailabilities(t1); endTiming(String.format(PURGE__FORMAT,MULTI)); // Vacuum the db - systemManager.vacuum(LookupUtil.getSubjectManager().getOverlord(),new String[]{"rhq_availability"}); + systemManager.vacuum(overlord,new String[]{"rhq_availability"});
}
@@ -291,4 +301,92 @@ public class AvailabilityInsertPurgeTest extends AbstractEJB3PerformanceTest {
}
+ /** + * Send availability reports to the server and measure timing. + * For each resource, availability alternates for each report. + * There are multiple rounds of sending with higher numbers of reports. + * For one resource we set up an alert to fire every going down report. + * @throws Exception If anything goes wrong + * @see #ROUNDS for the number of availability reports per round + */ + @DatabaseState(url = "perftest/AvailabilityInsertPurgeTest-testOne-data.xml.zip", dbVersion="2.94") + public void testAlternatingWithAlert() throws Exception { + + EntityManager em = getEntityManager(); + Query q = em.createQuery("SELECT r FROM Resource r"); + List<Resource> resources = q.getResultList(); + Resource res = resources.get(0); + Agent agent = agentManager.getAgentByResourceId(res.getId()); + + q = em.createQuery("SELECT COUNT(a) FROM Availability a "); + Object o = q.getSingleResult(); + Long l = (Long)o; + if (l!=0) { + throw new IllegalStateException("Availabilities table is not empty"); + } + systemManager.vacuum(overlord,new String[]{"rhq_availability"}); + + // Set up an alert definition on one resource + AlertCondition goingDown = new AlertCondition(); + goingDown.setCategory(AlertConditionCategory.AVAILABILITY); + goingDown.setComparator("=="); + goingDown.setOption(AvailabilityType.DOWN.toString()); + + AlertDefinition def = new AlertDefinition(); + def.addCondition(goingDown); + alertDefinitionManager.createAlertDefinition(overlord,def,res.getId()); + + for (int MULTI : ROUNDS) { + String round = String.format(ROUND__FORMAT, MULTI); + + long t1 = System.currentTimeMillis() - (MULTI * MILLIS_APART); + for (int i = 0; i < MULTI; i++) { + + AvailabilityReport report = new AvailabilityReport(agent.getName()); + for (Resource r : resources) { + AvailabilityType at = (i % 2 == 0) ? AvailabilityType.UP : AvailabilityType.DOWN; + Availability a = new Availability(r, new Date(t1 + i * MILLIS_APART), at); + report.addAvailability(a); + } + startTiming(round); + availabilityManager.mergeAvailabilityReport(report); + endTiming(round); + } + + // merge is over. Now lets purge in two steps + startTiming(String.format(PURGE__FORMAT,MULTI)); + availabilityManager.purgeAvailabilities(t1 + (MULTI/2)*MILLIS_APART); + endTiming(String.format(PURGE__FORMAT,MULTI)); + startTiming(String.format(PURGE__FORMAT,MULTI)); + availabilityManager.purgeAvailabilities(t1); + endTiming(String.format(PURGE__FORMAT,MULTI)); + // Vacuum the db + systemManager.vacuum(overlord,new String[]{"rhq_availability"}); + + } + + + long timing1000 = getTiming(String.format(ROUND__FORMAT,1000)); + long timing2000 = getTiming(String.format(ROUND__FORMAT,2000)); + long timing3000 = getTiming(String.format(ROUND__FORMAT,3000)); + long timing5000 = getTiming(String.format(ROUND__FORMAT,5000)); + long timing10000 = getTiming(String.format(ROUND__FORMAT,10000)); + + assertLinear(timing1000,timing2000,2,"Merge2"); + assertLinear(timing1000,timing3000,3,"Merge3"); + assertLinear(timing1000,timing5000,5,"Merge5"); + assertLinear(timing1000,timing10000,10,"Merge10"); + + long purge1000 = getTiming(String.format(PURGE__FORMAT,1000)); + long purge2000 = getTiming(String.format(PURGE__FORMAT,2000)); + long purge3000 = getTiming(String.format(PURGE__FORMAT,3000)); + long purge5000 = getTiming(String.format(PURGE__FORMAT,5000)); + + assertLinear(purge1000,purge2000,2,"Purge2"); + assertLinear(purge1000,purge3000,3,"Purge3"); + assertLinear(purge1000,purge5000,5,"Purge3"); + + } + + }
commit 915e740bb29e3ac21eaa1674a8a51779c1494991 Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 22:17:23 2010 -0400
add Resource name to Disambiguation report; more work on group config editor
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java index e00e29d..cbff0b9 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java @@ -35,8 +35,8 @@ public class ResourceConfigurationComposite implements Serializable{ */ private Configuration configuration;
- // No-arg constructor required by GWT - protected ResourceConfigurationComposite() { + // Default constructor required by GWT + public ResourceConfigurationComposite() { }
public ResourceConfigurationComposite(int resourceId, Configuration configuration) { diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java index f54354b..717721b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java @@ -165,6 +165,7 @@ public class DisambiguationReport<T> implements Serializable { }
public String toString() { - return "DisambiguationReport(type=" + resourceType + ", parents=" + parents + ", original=" + original + ")"; + return "DisambiguationReport(type=" + resourceType + ", parents=" + parents + ", original=" + original + + ", name=" + name + ")"; } } \ No newline at end of file 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 8a4d9fa..310f59f 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 @@ -569,18 +569,23 @@ public class ConfigurationEditor extends LocatableVLayout { final FormItem valueItem; if (propertyDefinition instanceof PropertyDefinitionSimple) { final PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple)propertyDefinition; - final PropertySimple propertySimple = (PropertySimple)property; + PropertySimple propertySimple = (PropertySimple)property; + + if (propertySimple == null) { + propertySimple = new PropertySimple(propertyDefinitionSimple.getName(), null); + }
+ final PropertySimple finalPropertySimple = propertySimple; valueItem = buildSimpleField(propertyDefinitionSimple, propertySimple); valueItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { - propertySimple.setErrorMessage(null); + finalPropertySimple.setErrorMessage(null); boolean isValid = changedEvent.getItem().validate(); if (isValid) { - propertySimple.setValue(changedEvent.getValue()); + finalPropertySimple.setValue(changedEvent.getValue()); } if (firePropertyChangedEvents) { - firePropertyChangedEvent(propertySimple, propertyDefinitionSimple, isValid); + firePropertyChangedEvent(finalPropertySimple, propertyDefinitionSimple, isValid); } } }); @@ -602,6 +607,9 @@ public class ConfigurationEditor extends LocatableVLayout { PropertyDefinitionList propertyDefinitionList = (PropertyDefinitionList)propertyDefinition; PropertyDefinition memberDefinition = propertyDefinitionList.getMemberDefinition(); PropertyList propertyList = (PropertyList)property; + if (propertyList == null) { + propertyList = new PropertyList(propertyDefinitionList.getName()); + } if (memberDefinition instanceof PropertyDefinitionMap) { // List of Maps is a specially supported case with summary fields as columns in a table // Note: This field spans 3 columns. @@ -638,9 +646,15 @@ public class ConfigurationEditor extends LocatableVLayout { fields.add(canvasItem); } } else if (propertyDefinition instanceof PropertyDefinitionMap) { + PropertyDefinitionMap propertyDefinitionMap = (PropertyDefinitionMap)propertyDefinition; + PropertyMap propertyMap = (PropertyMap)property; + if (propertyMap == null) { + propertyMap = new PropertyMap(propertyDefinitionMap.getName()); + } + // Note: This field spans 3 columns. FormItem mapField = - buildMapField(locatorId, (PropertyDefinitionMap)propertyDefinition, (PropertyMap)property); + buildMapField(locatorId, propertyDefinitionMap, propertyMap); fields.add(mapField); }
@@ -1293,7 +1307,7 @@ public class ConfigurationEditor extends LocatableVLayout { return valueItem; }
- private static Property getTopLevelProperty(Property property) { + protected static Property getTopLevelProperty(Property property) { Property currentProperty = property; while (currentProperty.getConfiguration() == null) { if (currentProperty.getParentList() != null) { @@ -1307,12 +1321,12 @@ public class ConfigurationEditor extends LocatableVLayout { } return currentProperty; } - + protected FormItem buildUnsetItem(PropertyDefinitionSimple propertyDefinition, final PropertySimple property, final FormItem valueItem) { FormItem item; if (!propertyDefinition.isRequired()) { - CheckboxItem unsetItem = new CheckboxItem(); + final CheckboxItem unsetItem = new CheckboxItem(); boolean unset = isUnset(propertyDefinition, property); unsetItem.setValue(unset); unsetItem.setDisabled(isReadOnly(propertyDefinition, property)); @@ -1325,15 +1339,24 @@ public class ConfigurationEditor extends LocatableVLayout { public void onChange(ChangeEvent changeEvent) { Boolean isUnset = (Boolean) changeEvent.getValue(); if (isUnset) { + valueItem.getForm().setValue(valueItem.getName(), (String)null); valueItem.setDisabled(true); - valueItem.setValue((String) null); } else { valueItem.setDisabled(false); valueItem.focusInItem(); } + valueItem.redraw(); property.setValue(valueItem.getValue()); } }); + + valueItem.addChangeHandler(new ChangeHandler() { + public void onChange(ChangeEvent changeEvent) { + String value = (String)changeEvent.getValue(); + unsetItem.setDisabled(value == null); + } + }); + item = unsetItem; } else { item = new SpacerItem(); 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 4bdb9e6..463ee42 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 @@ -79,30 +79,43 @@ public class GroupConfigurationEditor extends ConfigurationEditor { protected FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, final PropertySimple propertySimple) { final FormItem item; - if (propertySimple.getOverride()) { + boolean isAggregate = isAggregateProperty(propertySimple); + if (!isAggregate || isHomogeneous(propertySimple)) { item = super.buildSimpleField(propertyDefinitionSimple, propertySimple); } else { item = new StaticTextItem(); - item.setTitle("<i>Member Values Differ</i>"); - item.setIcons(); + item.setDefaultValue("<span style='color: red'><i>Member Values Differ</i></span>"); + item.setShowTitle(false); }
- // Add the icon that user can click to edit the member values. - FormItemIcon icon = new FormItemIcon(); - icon.setSrc("[SKIN]/actions/edit.png"); - icon.setName("Edit Member Values"); - icon.addFormItemClickHandler(new FormItemClickHandler() { - public void onFormItemClick(FormItemIconClickEvent event) { - // TODO: Pass the actual index, rather than null, if the prop is inside a list. - displayMemberValuesEditor(extendLocatorId("MemberValuesEditor"), propertyDefinitionSimple, item, - propertySimple, null); - } - }); - item.setIcons(icon); + if (isAggregate) { + // Add the icon that user can click to edit the member values. + FormItemIcon icon = new FormItemIcon(); + icon.setSrc("[SKIN]/actions/edit.png"); + icon.setName("Edit Member Values"); + icon.addFormItemClickHandler(new FormItemClickHandler() { + public void onFormItemClick(FormItemIconClickEvent event) { + // TODO: Pass the actual index, rather than null, if the prop is inside a list. + displayMemberValuesEditor(extendLocatorId("MemberValuesEditor"), propertyDefinitionSimple, item, + propertySimple, null); + } + }); + // TODO: Figure out a way to add a tooltip to the icon. + item.setIcons(icon); + }
return item; }
+ private boolean isAggregateProperty(PropertySimple propertySimple) { + return (propertySimple.getConfiguration() == getConfiguration()); + } + + private static Boolean isHomogeneous(PropertySimple propertySimple) { + Boolean override = propertySimple.getOverride(); + return (override != null && override); + } + private void displayMemberValuesEditor(String locatorId, PropertyDefinitionSimple propertyDefinitionSimple, final FormItem aggregateValueItem, final PropertySimple aggregatePropertySimple, Integer index) { @@ -113,26 +126,36 @@ public class GroupConfigurationEditor extends ConfigurationEditor {
final DynamicForm form = new DynamicForm(); form.setHeight100(); - form.setColWidths("55%", "5%", "40%"); + form.setNumCols(3); + form.setColWidths("60%", "8%", "32%"); layout.addMember(form);
// Add header row. List<FormItem> items = new ArrayList<FormItem>(); - StaticTextItem memberHeader = new StaticTextItem("memberHeader", "Member"); + StaticTextItem memberHeader = new StaticTextItem(); + memberHeader.setShowTitle(false); + memberHeader.setDefaultValue("<h4>Member</h4>"); items.add(memberHeader); - StaticTextItem unsetHeader = new StaticTextItem("unsetHeader", "Unset"); + StaticTextItem unsetHeader = new StaticTextItem(); + unsetHeader.setShowTitle(false); + unsetHeader.setDefaultValue("<h4>Unset</h4>"); items.add(unsetHeader); - StaticTextItem valueHeader = new StaticTextItem("valueHeader", "Value"); + StaticTextItem valueHeader = new StaticTextItem(); + valueHeader.setShowTitle(false); + valueHeader.setDefaultValue("<h4>Value</h4>"); valueHeader.setEndRow(true); items.add(valueHeader);
// Add data rows. final Map<String, PropertySimple> memberProperties = new HashMap<String, PropertySimple>(this.memberConfigurations.size()); final List<FormItem> valueItems = new ArrayList<FormItem>(this.memberConfigurations.size()); + final List<FormItem> unsetItems = new ArrayList<FormItem>(this.memberConfigurations.size()); for (GroupMemberConfiguration memberConfiguration : this.memberConfigurations) { // TODO: Format the disambiguated member name. String memberName = memberConfiguration.getLabel(); - StaticTextItem memberItem = new StaticTextItem("member", memberName); + StaticTextItem memberItem = new StaticTextItem(); + memberItem.setShowTitle(false); + memberItem.setDefaultValue(memberName); items.add(memberItem); Configuration configuration = memberConfiguration.getConfiguration(); PropertySimple memberPropertySimple = getPropertySimple(configuration, propertyDefinitionSimple, index); @@ -142,6 +165,7 @@ public class GroupConfigurationEditor extends ConfigurationEditor { valueItems.add(valueItem); FormItem unsetItem = buildUnsetItem(propertyDefinitionSimple, memberPropertySimple, valueItem); items.add(unsetItem); + unsetItems.add(unsetItem); items.add(valueItem); valueItem.setEndRow(true); } @@ -164,7 +188,7 @@ public class GroupConfigurationEditor extends ConfigurationEditor { String firstValue = (String)valueItems.get(0).getValue(); for (FormItem valueItem : valueItems) { String value = (String)valueItem.getValue(); - if ((value != null && !value.equals(firstValue)) || firstValue != null) { + if ((value != null && !value.equals(firstValue)) || (value == null && firstValue != null)) { valuesHomogeneous = false; } PropertySimple memberPropertySimple = @@ -174,12 +198,15 @@ public class GroupConfigurationEditor extends ConfigurationEditor { } if (valuesHomogeneous) { // Values are all the same, so update the value of the aggregate property and set its override flag to true. - aggregateValueItem.setValue(firstValue); + aggregateValueItem.getForm().setValue(aggregateValueItem.getName(), firstValue); // TODO: Will this cause a value changed event to fire for the aggregate form item? aggregatePropertySimple.setStringValue(firstValue); - aggregatePropertySimple.setErrorMessage(null); aggregatePropertySimple.setOverride(true); + } else { + aggregatePropertySimple.setStringValue(null); + aggregatePropertySimple.setOverride(false); } + // TODO: Figure out a way to update the aggregate Unset checkbox. popup.destroy(); } }); @@ -189,7 +216,7 @@ public class GroupConfigurationEditor extends ConfigurationEditor { public void onItemChanged(ItemChangedEvent itemChangedEvent) { okButton.setDisabled(!form.validate()); } - }); + });
final IButton cancelButton = new IButton("Cancel"); cancelButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { @@ -241,4 +268,9 @@ public class GroupConfigurationEditor extends ConfigurationEditor {
return (PropertySimple)property; } + + private static Configuration getConfiguration(Property property) { + Property topLevelProperty = getTopLevelProperty(property); + return topLevelProperty.getConfiguration(); + } } 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 ee2297c..03cfc83 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 @@ -67,7 +67,6 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme private ResourceGroup group; private ResourcePermission resourcePermission; private ConfigurationDefinition configurationDefinition; - private Configuration aggregateConfiguration; private List<GroupMemberConfiguration> memberConfigurations;
private ConfigurationEditor editor; @@ -122,7 +121,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme }
private void initEditor() { - if (this.configurationDefinition != null && this.aggregateConfiguration != null) { + if (this.configurationDefinition != null && this.memberConfigurations != null) { this.editor = new GroupConfigurationEditor(this.extendLocatorId("Editor"), this.configurationDefinition, this.memberConfigurations); this.editor.setOverflow(Overflow.AUTO); @@ -150,7 +149,6 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme }
private void loadConfigurations() { - this.aggregateConfiguration = null; this.memberConfigurations = null; this.configurationService.findResourceConfigurationsForGroup(group.getId(), new AsyncCallback<List<DisambiguationReport<ResourceConfigurationComposite>>>() { public void onFailure(Throwable caught) { @@ -165,8 +163,12 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme String resourceHtml = ReportDecorator.decorateResourceName(ReportDecorator.GWT_RESOURCE_URL, result.getResourceType(), result.getName(), resourceId); String label = parentsHtml + ReportDecorator.DEFAULT_SEPARATOR + resourceHtml; + Configuration configuration = result.getOriginal().getConfiguration(); GroupMemberConfiguration memberConfiguration = new GroupMemberConfiguration(resourceId, label, - result.getOriginal().getConfiguration()); + configuration); + if (configuration == null || configuration.getProperties().isEmpty()) { + throw new RuntimeException("One or more null or empty member Resource configuration was returned by the Server."); + } memberConfigurations.add(memberConfiguration); } initEditor(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java index abd6592..63fa33f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map;
+import com.allen_sauer.gwt.log.client.Log; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; import org.rhq.core.domain.configuration.RawConfiguration; @@ -11,7 +13,6 @@ import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; -import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageControl; @@ -26,6 +27,9 @@ import org.rhq.enterprise.server.resource.disambiguation.DefaultDisambiguationUp import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
+/** + * + */ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implements ConfigurationGWTService {
private static final long serialVersionUID = 1L; @@ -135,18 +139,26 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen .disambiguate(configurationComposites, RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR, DefaultDisambiguationUpdateStrategies.getDefault());
- return disambiguatedConfigurationComposites; + return SerialUtility.prepare(disambiguatedConfigurationComposites, + "ConfigurationService.findResourceConfigurationsForGroup"); } catch (RuntimeException e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } }
public RawConfiguration dummy(RawConfiguration config) { - com.allen_sauer.gwt.log.client.Log.info(config.getPath()); + Log.info(config.getPath()); return new RawConfiguration(); // Dummy method for gwt compiler }
+/* + public ResourceConfigurationComposite dummy(ResourceConfigurationComposite resourceConfigurationComposite) { + return new ResourceConfigurationComposite(); + // Dummy method for gwt compiler + } +*/ + private static final IntExtractor<ResourceConfigurationComposite> RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR = new IntExtractor<ResourceConfigurationComposite>() { public int extract(ResourceConfigurationComposite configurationComposite) {
commit c36bfe4e917c6e8cbb8b814d1b0b1001e3c8a926 Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Oct 7 18:24:06 2010 -0400
Resource Tree Work - Fix dual tree building for new trees - Fix issue with duplicate resources for tree population - Fix issue when navigating directly to an autogroup - Reselect previous selected node when selecting locked or subctageory nodes
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java index 713a558..a707e15 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java @@ -48,4 +48,26 @@ public class ResourceLineageComposite implements Serializable { public boolean isLocked() { return isLocked; } + + /* + * Uses Resource.equals() so composites for the same Resource will be equal. + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof ResourceLineageComposite)) { + return false; + } + + ResourceLineageComposite other = (ResourceLineageComposite) obj; + return this.resource.equals(other.getResource()); + } + + /* + * Uses Resource.hascode() + */ + @Override + public int hashCode() { + return this.resource.hashCode(); + } + } \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java index 17012f8..43d6b8c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java @@ -61,9 +61,9 @@ public class ResourceTreeDatasource extends DataSource { private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
public ResourceTreeDatasource(List<Resource> initialData, List<Resource> lockedData) { - setClientOnly(false); - setDataProtocol(DSProtocol.CLIENTCUSTOM); - setDataFormat(DSDataFormat.CUSTOM); + this.setClientOnly(false); + this.setDataProtocol(DSProtocol.CLIENTCUSTOM); + this.setDataFormat(DSDataFormat.CUSTOM);
this.initialData = initialData; this.lockedData = (null != lockedData) ? lockedData : new ArrayList<Resource>(); @@ -80,9 +80,9 @@ public class ResourceTreeDatasource extends DataSource { DataSourceTextField parentIdField = new DataSourceTextField("parentId", "Parent ID"); parentIdField.setForeignKey("id");
- setDropExtraFields(false); + this.setDropExtraFields(false);
- setFields(idDataField, nameDataField, descriptionDataField); + this.setFields(idDataField, nameDataField, descriptionDataField); }
@Override @@ -116,40 +116,42 @@ public class ResourceTreeDatasource extends DataSource { //final long start = System.currentTimeMillis();
String parentResourceId = request.getCriteria().getAttribute("parentId"); - // com.allen_sauer.gwt.log.client.Log.info("All attributes: " + Arrays.toString(request.getCriteria().getAttributes())); + //com.allen_sauer.gwt.log.client.Log.info("All attributes: " + Arrays.toString(request.getCriteria().getAttributes()));
ResourceCriteria criteria = new ResourceCriteria();
if (parentResourceId == null) { - com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading initial data..."); - - // criteria.addFilterId(rootId); - - processIncomingData(initialData, response, requestId); - response.setStatus(DSResponse.STATUS_SUCCESS); - return; + // If this gets called more than once it's a problem. Don't load initial data more than once. + // Subsequent fetches should be due to parent node tree expansion + if (null != this.initialData) { + com.allen_sauer.gwt.log.client.Log.debug("ResourceTreeDatasource: Loading initial data..."); + + processIncomingData(this.initialData, response, requestId); + response.setStatus(DSResponse.STATUS_SUCCESS); + this.initialData = null; + } else { + processResponse(requestId, response); + response.setStatus(DSResponse.STATUS_FAILURE); + }
} else { - com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading Resource [" + parentResourceId + com.allen_sauer.gwt.log.client.Log.debug("ResourceTreeDatasource: Loading Resource [" + parentResourceId + "]...");
criteria.addFilterParentResourceId(Integer.parseInt(parentResourceId)); - } - - // The server is already eager fetch resource type - // * criteria.fetchResourceType(true);
- resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load resource data for tree", caught); - response.setStatus(RPCResponse.STATUS_FAILURE); - processResponse(requestId, response); - } + resourceService.findResourcesByCriteria(criteria, new AsyncCallback<PageList<Resource>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load resource data for tree", caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(requestId, response); + }
- public void onSuccess(PageList<Resource> result) { - processIncomingData(result, response, requestId); - } - }); + public void onSuccess(PageList<Resource> result) { + processIncomingData(result, response, requestId); + } + }); + } }
private void processIncomingData(List<Resource> result, final DSResponse response, final String requestId) { @@ -182,11 +184,7 @@ public class ResourceTreeDatasource extends DataSource { }
List<TreeNode> result = introduceTypeAndCategoryNodes(resourceNodes); - com.allen_sauer.gwt.log.client.Log.debug("\nSTARTING FINAL TREE\n"); - for (TreeNode node : result) { - com.allen_sauer.gwt.log.client.Log.debug("Final: " + node); - } - com.allen_sauer.gwt.log.client.Log.debug("\nENDING FINAL TREE\n"); + return result.toArray(new TreeNode[result.size()]); }
@@ -198,6 +196,7 @@ public class ResourceTreeDatasource extends DataSource { // The resulting list of nodes, including AG and SC nodes. The list is ordered to ensure all // referenced parent nodes have lower indexes than the referencing child. List<TreeNode> allNodes = new ArrayList<TreeNode>(resourceNodes.size()); + // Keep track of the node IDs added so far to ensure we don't add the same node more than once. Note // that the list of resourceNodes passed in may have duplicates as the caller may not be able to // ensure a clean set. @@ -205,13 +204,14 @@ public class ResourceTreeDatasource extends DataSource {
for (ResourceTreeNode resourceNode : resourceNodes) { if (allNodeIds.contains(resourceNode.getID())) { - com.allen_sauer.gwt.log.client.Log.debug("skipping duplicate resourceNode: " + resourceNode); + com.allen_sauer.gwt.log.client.Log.debug("Duplicate ResourceTreeNode - Skipping: " + resourceNode); continue; }
Resource resource = resourceNode.getResource();
if (resourceNode.isParentSubCategory()) { + // If the parent node is a subcategory node, make sure the subcategory node is in the // tree prior to the resource node. Note that it could itself be a tree of subcategories. addSubCategoryNodes(allNodes, allNodeIds, resource); @@ -225,6 +225,7 @@ public class ResourceTreeDatasource extends DataSource { AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource);
if (autogroupNode.isParentSubcategory()) { + // If the parent node of the autogroup node is a subcategory node, make sure the subcategory // node is in the tree prior to the autogroup node. Note that it could itself be a // tree of subcategories. @@ -232,12 +233,10 @@ public class ResourceTreeDatasource extends DataSource {
} allNodeIds.add(resourceNode.getParentID()); - com.allen_sauer.gwt.log.client.Log.debug("Adding " + autogroupNode); allNodes.add(autogroupNode); } }
- com.allen_sauer.gwt.log.client.Log.debug("Adding " + resourceNode + " to tree..."); allNodeIds.add(resourceNode.getID()); allNodes.add(resourceNode); } @@ -259,7 +258,6 @@ public class ResourceTreeDatasource extends DataSource { if (!allNodeIds.contains(subCategoryNodeId)) { SubCategoryTreeNode subCategoryNode = new SubCategoryTreeNode(subCategory, parentResource); allNodeIds.add(subCategoryNodeId); - com.allen_sauer.gwt.log.client.Log.debug("Adding " + subCategoryNode); allNodes.add(insertAt, subCategoryNode); } } while ((subCategory = subCategory.getParentSubCategory()) != null); 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 1b1ebc6..88b00ad 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 @@ -126,7 +126,9 @@ public class ResourceTreeView extends LocatableVLayout { treeGrid.setOpenerImage("resources/dir.png"); treeGrid.setOpenerIconSize(16);
- treeGrid.setAutoFetchData(true); + // don't auto-fetch data, the initial fetch is requested manually using initial lineage information + treeGrid.setAutoFetchData(false); + treeGrid.setAnimateFolders(false); treeGrid.setSelectionType(SelectionStyle.SINGLE); treeGrid.setShowRollOver(false); @@ -155,8 +157,10 @@ public class ResourceTreeView extends LocatableVLayout { CoreGUI.goToView(viewPath); } } else { - // TODO: Can we select the previous node? Or do we need a "Locked" hover etc... - treeGrid.deselectAllRecords(); + treeGrid.deselectRecord(resourceNode); + if (null != selectedNodeId) { + treeGrid.selectRecord(treeGrid.getTree().findById(selectedNodeId)); + } } } else if (selectedRecord instanceof AutoGroupTreeNode) { com.allen_sauer.gwt.log.client.Log.info("AutoGroup Node selected in tree: " + selectedRecord); @@ -173,7 +177,11 @@ public class ResourceTreeView extends LocatableVLayout { } }); } else { - com.allen_sauer.gwt.log.client.Log.info("Unhandled Node selected in tree: " + selectedRecord); + // TODO: probably clicked on a subcategory, do we need a message? + treeGrid.deselectRecord(selectedRecord); + if (null != selectedNodeId) { + treeGrid.selectRecord(treeGrid.getTree().findById(selectedNodeId)); + } } } } @@ -616,12 +624,12 @@ public class ResourceTreeView extends LocatableVLayout {
} else { // This is for cases where we have to load the tree fresh including down to the currently visible node - loadTree(selectedResourceId); + loadTree(selectedResourceId, null); }
}
- private void loadTree(final int selectedResourceId) { + private void loadTree(final int selectedResourceId, final AsyncCallback<Void> callback) { selectedNodeId = ResourceTreeNode.idOf(selectedResourceId);
final ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); @@ -666,6 +674,10 @@ public class ResourceTreeView extends LocatableVLayout { public void execute(DSResponse response, Object rawData, DSRequest request) { System.out.println("Done fetching data for tree."); updateSelection(); + + if (null != callback) { + callback.onSuccess(null); + } } });
@@ -694,7 +706,6 @@ public class ResourceTreeView extends LocatableVLayout {
} }); - } } }); @@ -724,16 +735,25 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(PageList<ResourceGroup> result) { - ResourceGroup backingGroup = result.get(0); + final ResourceGroup backingGroup = result.get(0); // load the tree up to the autogroup's parent resource - loadTree(backingGroup.getAutoGroupParentResource().getId()); + loadTree(backingGroup.getAutoGroupParentResource().getId(), new AsyncCallback<Void>() {
- // get the node ID and use it to add a map entry, then call this again to finish up... - selectedNodeId = AutoGroupTreeNode.idOf(backingGroup.getAutoGroupParentResource(), backingGroup - .getResourceType()); - AutoGroupTreeNode agNode = (AutoGroupTreeNode) treeGrid.getTree().findById(selectedNodeId); - autoGroupNodeMap.put(backingGroup.getId(), agNode); - updateSelection(); + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load tree", caught); + } + + @Override + public void onSuccess(Void arg) { + // get the node ID and use it to add a map entry, then call this again to finish up... + selectedNodeId = AutoGroupTreeNode.idOf(backingGroup.getAutoGroupParentResource(), + backingGroup.getResourceType()); + AutoGroupTreeNode agNode = (AutoGroupTreeNode) treeGrid.getTree().findById(selectedNodeId); + autoGroupNodeMap.put(backingGroup.getId(), agNode); + updateSelection(); + } + }); } }); } 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 9f5693b..62091bc 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 @@ -751,6 +751,8 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage
// get children Set<Resource> children = ancestor.getResource().getChildResources(); + // remove any that are in the ancestry to avoid repeated handling + children.removeAll(rawResourceLineage); // only add the viewable children List<Resource> viewableChildren = new ArrayList<Resource>(children.size()); for (Resource child : children) { @@ -760,8 +762,10 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage if (isCommitted && isViewable) { // if not a direct ancestor add to the list (direct ancestors already added by default) if (!rawResourceLineage.contains(child)) { + // ensure we have the parent in the entity child.getParentResource().getId(); - result.add(new ResourceLineageComposite(child, false)); + ResourceLineageComposite composite = new ResourceLineageComposite(child, false); + result.add(composite); } viewableChildren.add(child); } @@ -770,6 +774,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage // get grandchildren for (Resource child : viewableChildren) { // This ensures Hibernate actually fetches the parent Resource. + // ensure we have the parent child.getParentResource().getId(); Set<Resource> grandChildren = child.getChildResources(); for (Resource grandChild : grandChildren) { @@ -779,8 +784,10 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage if (isCommitted && isViewable) { // if not a direct ancestor add to the list (direct ancestors already added by default) if (!rawResourceLineage.contains(grandChild)) { + // ensure we have the parent in the entity grandChild.getParentResource().getId(); - result.add(new ResourceLineageComposite(grandChild, false)); + ResourceLineageComposite composite = new ResourceLineageComposite(grandChild, false); + result.add(composite); } } } @@ -1813,7 +1820,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage try { resource = getResourceById(overlord, resourceError.getResource().getId()); } catch (ResourceNotFoundException rnfe) { - throw new ResourceNotFoundException("Resource error contains an unknown Resource id: " + resourceError); + throw new ResourceNotFoundException("Resource error an unknown Resource id: " + resourceError); }
if (resourceError.getErrorType() == ResourceErrorType.INVALID_PLUGIN_CONFIGURATION @@ -1881,7 +1888,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage Query query = entityManager.createNamedQuery(Resource.QUERY_FIND_PLATFORM_BY_AGENT); query.setParameter("category", ResourceCategory.PLATFORM); query.setParameter("agent", agent); - + try { Resource platform = (Resource) query.getSingleResult(); return platform; @@ -2087,7 +2094,7 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage // ListIterator<ResourceFlyweight> iter = resources.listIterator(); // while (iter.hasNext()) { // ResourceFlyweight res = iter.next(); - // res.setLocked(!visibleIdSet.contains(res.getId())); + // res.setLocked(!visibleIdSet.(res.getId())); // } // }
commit 2ed9702c13f07cecf26573bf4057a468c6fbf40a Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 17:59:57 2010 -0400
remove a remaining use of the no-longer-valid c:option 'default' attribute
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 d59b312..2361c2d 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 @@ -417,7 +417,7 @@ <c:simple-property name="rhq.communications.connector.security.keystore.type" type="string" activationPolicy="restart" required="false" default="JKS" displayName="Incoming: Keystore Type"> <c:property-options allowCustomValue="true"> - <c:option name="JKS" value="JKS" default="true" /> + <c:option name="JKS" value="JKS" /> <c:option name="PKCS12" value="PKCS12" /> </c:property-options> </c:simple-property>
commit f7e8e4c7cbd4bb0080fbc9fc9921316f5738448b Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 17:55:56 2010 -0400
add no-arg ctor to ResourceConfigurationComposite to make GWT happy; remove a few remaining uses of the no-longer-valid c:option 'default' attribute in as5 plugin descriptor
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java index 3ce48ee..e00e29d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java @@ -35,6 +35,10 @@ public class ResourceConfigurationComposite implements Serializable{ */ private Configuration configuration;
+ // No-arg constructor required by GWT + protected ResourceConfigurationComposite() { + } + public ResourceConfigurationComposite(int resourceId, Configuration configuration) { this.resourceId = resourceId; this.configuration = configuration; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java index af0882f..e4df2b8 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java @@ -163,5 +163,4 @@ public class SubjectCriteria extends Criteria { addSortField("department"); this.sortDepartment = sortDepartment; } - } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java index f363993..545a6af 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java @@ -77,7 +77,7 @@ public class AggregateConfigurationBuilder { } // If the property is a Map, recurse into it and group together its child properties. else if (propertyDefinition instanceof PropertyDefinitionMap) { - List<AbstractPropertyMap> nestedSourceParentPropertyMaps = new ArrayList(); + List<AbstractPropertyMap> nestedSourceParentPropertyMaps = new ArrayList<AbstractPropertyMap>(); for (AbstractPropertyMap sourceParentPropertyMap : sourceParentPropertyMaps) { PropertyMap nestedSourceParentPropertyMap = sourceParentPropertyMap .getMap(propertyDefinition.getName()); @@ -139,14 +139,14 @@ public class AggregateConfigurationBuilder {
private static Map<String, Map<String, Integer>> createMemberNameValueFrequenciesMap( List<AbstractPropertyMap> sourceParentPropertyMaps) { - Map<String, Map<String, Integer>> nameValueFrequenciesMap = new HashMap(); + Map<String, Map<String, Integer>> nameValueFrequenciesMap = new HashMap<String, Map<String, Integer>>(); for (AbstractPropertyMap map : sourceParentPropertyMaps) { for (String propertyName : map.getMap().keySet()) { PropertySimple propertySimple = map.getSimple(propertyName); String propertyValue = (propertySimple != null) ? propertySimple.getStringValue() : null; Map<String, Integer> valueFrequencies = nameValueFrequenciesMap.get(propertyName); if (valueFrequencies == null) { - valueFrequencies = new HashMap(); + valueFrequencies = new HashMap<String, Integer>(); nameValueFrequenciesMap.put(propertyName, valueFrequencies); } Integer valueFrequency = (valueFrequencies.containsKey(propertyValue)) ? (valueFrequencies 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 473daf1..bab4121 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 @@ -447,7 +447,7 @@ </c:description> </c:simple-property>
- <c:simple-property name="track-statements" type="string" + <c:simple-property name="track-statements" type="string" default="yes-no-warnings" displayName="Track Statements" required="false"> <c:description> Whether to check for unclosed Statements and ResultSets when connections are returned to the pool. The @@ -456,15 +456,15 @@ <c:property-options> <c:option name="No" value="no"/> <c:option name="Yes" value="yes"/> - <c:option name="Yes, but no warnings" value="yes-no-warnings" default="true"/> + <c:option name="Yes, but no warnings" value="yes-no-warnings"/> </c:property-options> </c:simple-property>
- <c:simple-property name="transaction-isolation" required="false" + <c:simple-property name="transaction-isolation" required="false" default="TRANSACTION_READ_COMMITTED" description="The Transaction Isolation level. The default setting is to use whichever isolation level is provided by default by the database."> <c:property-options> <c:option value="TRANSACTION_READ_UNCOMMITTED" name="Read Uncommitted"/> - <c:option value="TRANSACTION_READ_COMMITTED" default="true" name="Read Committed"/> + <c:option value="TRANSACTION_READ_COMMITTED" name="Read Committed"/> <c:option value="TRANSACTION_REPEATABLE_READ" name="Repeatable Read"/> <c:option value="TRANSACTION_SERIALIZABLE" name="Serializable"/> <c:option value="TRANSACTION_NONE" name="None"/> @@ -1003,7 +1003,7 @@ description="The method used to execute the Shut Down operation; defaults to 'JMX MBean'."> <c:property-options> - <c:option value="JMX" name="JMX MBean" default="true"/> + <c:option value="JMX" name="JMX MBean"/> <c:option value="SCRIPT" name="shutdown script"/> </c:property-options> </c:simple-property>
commit 9c9af766eee99ddf5c9f14929841e223a5cbc714 Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 17:27:41 2010 -0400
fix a few spots i missed when removing is_default field from propdef enum entity ; more work on the group config editor and group resource config view
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java new file mode 100644 index 0000000..3ce48ee --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/composite/ResourceConfigurationComposite.java @@ -0,0 +1,50 @@ +/* + * RHQ Management Platform + * Copyright 2010, 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.core.domain.configuration.composite; + +import java.io.Serializable; + +import org.rhq.core.domain.configuration.Configuration; + +/** + * @author Ian Springer + */ +public class ResourceConfigurationComposite implements Serializable{ + private static final long serialVersionUID = 1L; + + private int resourceId; + /** + * This could be a resource config or a plugin config depending on the context. + */ + private Configuration configuration; + + public ResourceConfigurationComposite(int resourceId, Configuration configuration) { + this.resourceId = resourceId; + this.configuration = configuration; + } + + public int getResourceId() { + return resourceId; + } + + public Configuration getConfiguration() { + return configuration; + } +} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java index 4412cec..a121510 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java @@ -63,13 +63,6 @@ public class PropertyDefinitionEnumeration implements Serializable { @Column(name = "ORDER_INDEX", nullable = false) private int orderIndex = -1;
- @Column(name = "IS_DEFAULT") - @Deprecated - /** - * @deprecated - not used; TODO: remove in dbsetup/dbupgrade scripts - */ - private boolean isDefault; - @JoinColumn(name = "PROPERTY_DEF_ID") @ManyToOne @XmlTransient @@ -125,14 +118,6 @@ public class PropertyDefinitionEnumeration implements Serializable { this.value = value; }
- public boolean isDefault() { - return isDefault; - } - - public void setDefault(boolean aDefault) { - isDefault = aDefault; - } - public int getOrderIndex() { return orderIndex; } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java index a83d1f8..f54354b 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/DisambiguationReport.java @@ -20,14 +20,13 @@ * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ - package org.rhq.core.domain.resource.composite;
import java.io.Serializable; import java.util.List;
/** - * Contains information about disambiguation of a resource name. + * Contains information about disambiguation of a Resource name. * * @author Lukas Krejci */ @@ -37,6 +36,7 @@ public class DisambiguationReport<T> implements Serializable { private T original; private List<Resource> parents; private ResourceType resourceType; + private String name;
public static class ResourceType implements Serializable {
@@ -127,12 +127,13 @@ public class DisambiguationReport<T> implements Serializable { public DisambiguationReport() { }
- public DisambiguationReport(T original, List<Resource> parents, ResourceType resourceType) { + public DisambiguationReport(T original, List<Resource> parents, ResourceType resourceType, String name) { this.original = original; // this.parents = Collections.unmodifiableList(parents); //spinder: the returned type is not Serializable and causes GWT serialization errors. this.parents = parents; this.resourceType = resourceType; + this.name = name; }
public T getOriginal() { @@ -155,6 +156,14 @@ public class DisambiguationReport<T> implements Serializable { return resourceType; }
+ /** + * + * @return the Resource name + */ + public String getName() { + return name; + } + public String toString() { return "DisambiguationReport(type=" + resourceType + ", parents=" + parents + ", original=" + original + ")"; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java new file mode 100644 index 0000000..f363993 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/AggregateConfigurationBuilder.java @@ -0,0 +1,167 @@ +/* + * RHQ Management Platform + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.gui.coregui.client.components.configuration; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.rhq.core.domain.configuration.AbstractPropertyMap; +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.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; + +/** + * @author Ian Springer + */ +public class AggregateConfigurationBuilder { + public static Configuration buildAggregateConfiguration(List<Configuration> configurations, + ConfigurationDefinition configurationDefinition) { + Configuration aggregateConfiguration = new Configuration(); + + if (configurations.isEmpty()) { + return aggregateConfiguration; + } + + Map<String, PropertyDefinition> childPropertyDefinitions = configurationDefinition.getPropertyDefinitions(); + for (PropertyDefinition childPropertyDefinition : childPropertyDefinitions.values()) { + buildAggregateProperty(childPropertyDefinition, configurations, aggregateConfiguration); + } + + return aggregateConfiguration; + } + + private static void buildAggregateProperty(PropertyDefinition propertyDefinition, + List<? extends AbstractPropertyMap> sourceParentPropertyMaps, AbstractPropertyMap targetParentPropertyMap) { + if (propertyDefinition instanceof PropertyDefinitionSimple) { + String sampleValue = getSimpleValue(sourceParentPropertyMaps.get(0), propertyDefinition.getName()); + boolean valuesHomogeneous = true; + for (int i = 1; i < sourceParentPropertyMaps.size(); i++) { + String value = getSimpleValue(sourceParentPropertyMaps.get(i), propertyDefinition.getName()); + if ((value == null && sampleValue != null) || (value != null && !value.equals(sampleValue))) { + valuesHomogeneous = false; + break; + } + } + PropertySimple propertySimple = new PropertySimple(propertyDefinition.getName(), + (valuesHomogeneous) ? sampleValue : null); + targetParentPropertyMap.put(propertySimple); + if (valuesHomogeneous) { + // Set override to true so the config renderer will know the prop is homogeneous. + propertySimple.setOverride(true); + } + } + // If the property is a Map, recurse into it and group together its child properties. + else if (propertyDefinition instanceof PropertyDefinitionMap) { + List<AbstractPropertyMap> nestedSourceParentPropertyMaps = new ArrayList(); + for (AbstractPropertyMap sourceParentPropertyMap : sourceParentPropertyMaps) { + PropertyMap nestedSourceParentPropertyMap = sourceParentPropertyMap + .getMap(propertyDefinition.getName()); + nestedSourceParentPropertyMaps + .add((nestedSourceParentPropertyMap != null) ? nestedSourceParentPropertyMap : new PropertyMap( + propertyDefinition.getName())); + } + PropertyMap targetPropertyMap = new PropertyMap(propertyDefinition.getName()); + targetParentPropertyMap.put(targetPropertyMap); + buildAggregatePropertyMap((PropertyDefinitionMap) propertyDefinition, nestedSourceParentPropertyMaps, + targetPropertyMap); + } else if (propertyDefinition instanceof PropertyDefinitionList) { + PropertyDefinitionList propertyDefinitionList = (PropertyDefinitionList) propertyDefinition; + PropertyDefinition listMemberPropertyDefinition = propertyDefinitionList.getMemberDefinition(); + PropertyList targetPropertyList = new PropertyList(propertyDefinition.getName()); + targetParentPropertyMap.put(targetPropertyList); + if (listMemberPropertyDefinition instanceof PropertyDefinitionMap) { + PropertyDefinitionMap propertyDefinitionMap = (PropertyDefinitionMap) listMemberPropertyDefinition; + // TODO: How do we group together Lists of Maps? Not trivial... + } + } + } + + private static void buildAggregatePropertyMap(PropertyDefinitionMap propertyDefinitionMap, + List<AbstractPropertyMap> sourceParentPropertyMaps, AbstractPropertyMap targetParentPropertyMap) { + Map<String, PropertyDefinition> childPropertyDefinitions = propertyDefinitionMap.getPropertyDefinitions(); + if (!childPropertyDefinitions.isEmpty()) { + for (PropertyDefinition childPropertyDefinition : childPropertyDefinitions.values()) + buildAggregateProperty(childPropertyDefinition, sourceParentPropertyMaps, targetParentPropertyMap); + } else { + buildAggregateOpenPropertyMap(sourceParentPropertyMaps, targetParentPropertyMap); + } + } + + private static void buildAggregateOpenPropertyMap(List<AbstractPropertyMap> sourceParentPropertyMaps, + AbstractPropertyMap targetParentPropertyMap) { + Map<String, Map<String, Integer>> memberNameValueFrequenciesMap = createMemberNameValueFrequenciesMap(sourceParentPropertyMaps); + for (String memberName : memberNameValueFrequenciesMap.keySet()) { + // Add each unique member to the target map, so the renderer will be able to display it on the main + // config page. + PropertySimple member = new PropertySimple(memberName, null); + targetParentPropertyMap.put(member); + // Also add it to each of the source config maps that don't already contain it, so that they can be + // rendered as unset on the propSet page. + for (AbstractPropertyMap map : sourceParentPropertyMaps) { + if (map.get(memberName) == null) + map.put(new PropertySimple(memberName, null)); + } + Map<String, Integer> valueFrequencies = memberNameValueFrequenciesMap.get(memberName); + if (valueFrequencies.size() == 1 + && valueFrequencies.values().iterator().next() == sourceParentPropertyMaps.size()) { + // Set override to true so the renderers will know the prop is homogenous. + member.setOverride(true); + // And set the value, so it can be displayed on the main config page. + member.setStringValue(valueFrequencies.keySet().iterator().next()); + } + } + } + + private static Map<String, Map<String, Integer>> createMemberNameValueFrequenciesMap( + List<AbstractPropertyMap> sourceParentPropertyMaps) { + Map<String, Map<String, Integer>> nameValueFrequenciesMap = new HashMap(); + for (AbstractPropertyMap map : sourceParentPropertyMaps) { + for (String propertyName : map.getMap().keySet()) { + PropertySimple propertySimple = map.getSimple(propertyName); + String propertyValue = (propertySimple != null) ? propertySimple.getStringValue() : null; + Map<String, Integer> valueFrequencies = nameValueFrequenciesMap.get(propertyName); + if (valueFrequencies == null) { + valueFrequencies = new HashMap(); + nameValueFrequenciesMap.put(propertyName, valueFrequencies); + } + Integer valueFrequency = (valueFrequencies.containsKey(propertyValue)) ? (valueFrequencies + .get(propertyValue) + 1) : 1; + valueFrequencies.put(propertyValue, valueFrequency); + } + } + return nameValueFrequenciesMap; + } + + private static String getSimpleValue(AbstractPropertyMap parentPropertyMap, String propertyName) { + PropertySimple samplePropertySimple = parentPropertyMap.getSimple(propertyName); + return (samplePropertySimple != null) ? samplePropertySimple.getStringValue() : null; + } + + private AggregateConfigurationBuilder() { + } +} 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 d47f8e1..8a4d9fa 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 @@ -501,7 +501,7 @@ public class ConfigurationEditor extends LocatableVLayout { return section; }
- private DynamicForm buildPropertiesForm(String locatorId, Collection<PropertyDefinition> propertyDefinitions, + protected DynamicForm buildPropertiesForm(String locatorId, Collection<PropertyDefinition> propertyDefinitions, AbstractPropertyMap propertyMap, boolean firePropertyChangedEvents) {
LocatableDynamicForm form = new LocatableDynamicForm(locatorId); 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 a7150e1..4bdb9e6 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 @@ -33,7 +33,10 @@ import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.events.ItemChangedEvent; import com.smartgwt.client.widgets.form.events.ItemChangedHandler; import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.FormItemIcon; import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.form.fields.events.FormItemClickHandler; +import com.smartgwt.client.widgets.form.fields.events.FormItemIconClickEvent; import com.smartgwt.client.widgets.layout.HLayout;
import org.rhq.core.domain.configuration.Configuration; @@ -53,15 +56,53 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Ian Springer */ public class GroupConfigurationEditor extends ConfigurationEditor { - private Map<String, Configuration> memberConfigurations; + private List<GroupMemberConfiguration> memberConfigurations;
public GroupConfigurationEditor(String locatorId, ConfigurationDefinition configurationDefinition, - Configuration aggregateConfiguration, - Map<String, Configuration> memberConfigurations) { - super(locatorId, configurationDefinition, aggregateConfiguration); + List<GroupMemberConfiguration> memberConfigurations) { + super(locatorId, configurationDefinition, buildAggregateConfiguration(memberConfigurations, configurationDefinition)); this.memberConfigurations = memberConfigurations; }
+ private static Configuration buildAggregateConfiguration( + List<GroupMemberConfiguration> memberConfigurations, + ConfigurationDefinition configurationDefinition) { + List<Configuration> configurations = new ArrayList<Configuration>(memberConfigurations.size()); + for (GroupMemberConfiguration memberConfiguration : memberConfigurations) { + Configuration configuration = memberConfiguration.getConfiguration(); + configurations.add(configuration); + } + return AggregateConfigurationBuilder.buildAggregateConfiguration(configurations, configurationDefinition); + } + + @Override + protected FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, + final PropertySimple propertySimple) { + final FormItem item; + if (propertySimple.getOverride()) { + item = super.buildSimpleField(propertyDefinitionSimple, propertySimple); + } else { + item = new StaticTextItem(); + item.setTitle("<i>Member Values Differ</i>"); + item.setIcons(); + } + + // Add the icon that user can click to edit the member values. + FormItemIcon icon = new FormItemIcon(); + icon.setSrc("[SKIN]/actions/edit.png"); + icon.setName("Edit Member Values"); + icon.addFormItemClickHandler(new FormItemClickHandler() { + public void onFormItemClick(FormItemIconClickEvent event) { + // TODO: Pass the actual index, rather than null, if the prop is inside a list. + displayMemberValuesEditor(extendLocatorId("MemberValuesEditor"), propertyDefinitionSimple, item, + propertySimple, null); + } + }); + item.setIcons(icon); + + return item; + } + private void displayMemberValuesEditor(String locatorId, PropertyDefinitionSimple propertyDefinitionSimple, final FormItem aggregateValueItem, final PropertySimple aggregatePropertySimple, Integer index) { @@ -88,11 +129,13 @@ public class GroupConfigurationEditor extends ConfigurationEditor { // Add data rows. final Map<String, PropertySimple> memberProperties = new HashMap<String, PropertySimple>(this.memberConfigurations.size()); final List<FormItem> valueItems = new ArrayList<FormItem>(this.memberConfigurations.size()); - for (String memberName : this.memberConfigurations.keySet()) { + for (GroupMemberConfiguration memberConfiguration : this.memberConfigurations) { + // TODO: Format the disambiguated member name. + String memberName = memberConfiguration.getLabel(); StaticTextItem memberItem = new StaticTextItem("member", memberName); items.add(memberItem); - Configuration memberConfiguration = this.memberConfigurations.get(memberName); - PropertySimple memberPropertySimple = getPropertySimple(memberConfiguration, propertyDefinitionSimple, index); + Configuration configuration = memberConfiguration.getConfiguration(); + PropertySimple memberPropertySimple = getPropertySimple(configuration, propertyDefinitionSimple, index); memberProperties.put(memberName, memberPropertySimple); FormItem valueItem = buildSimpleField(propertyDefinitionSimple, memberPropertySimple); valueItem.setAttribute("rhq:property", memberPropertySimple); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupMemberConfiguration.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupMemberConfiguration.java new file mode 100644 index 0000000..a9e04ac --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupMemberConfiguration.java @@ -0,0 +1,81 @@ +/* + * RHQ Management Platform + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.gui.coregui.client.components.configuration; + +import org.rhq.core.domain.configuration.Configuration; + +/** + * @author Ian Springer + */ +public class GroupMemberConfiguration { + private int id; + private String label; + private Configuration configuration; + + public GroupMemberConfiguration(int id, String label, Configuration configuration) { + this.id = id; + this.label = (label != null) ? label : String.valueOf(id); + this.configuration = configuration; + } + + public int getId() { + return id; + } + + public String getLabel() { + return label; + } + + public Configuration getConfiguration() { + return configuration; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + GroupMemberConfiguration that = (GroupMemberConfiguration)o; + + if (id != that.id) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + return id; + } + + @Override + public String toString() { + return "GroupMemberConfiguration{" + + "id=" + id + + ", label='" + label + ''' + + ", configuration=" + configuration + + '}'; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java index 4010ae0..e0be6ef 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ConfigurationGWTService.java @@ -1,12 +1,16 @@ package org.rhq.enterprise.gui.coregui.client.gwt;
+import java.util.List; + import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; import org.rhq.core.domain.configuration.RawConfiguration; import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; +import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; +import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.server.configuration.ConfigurationUpdateStillInProgressException; @@ -28,13 +32,14 @@ public interface ConfigurationGWTService extends RemoteService { PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdates( Integer resourceId, Long beginDate, Long endDate, boolean suppressOldest, PageControl pc);
- ResourceConfigurationUpdate updateResourceConfiguration(int resourceId, Configuration configuration);
PluginConfigurationUpdate updatePluginConfiguration(int resourceId, Configuration configuration);
PageList<ResourceConfigurationUpdate> findResourceConfigurationUpdatesByCriteria(ResourceConfigurationUpdateCriteria criteria);
+ List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup(int groupId); + RawConfiguration dummy(RawConfiguration config);
} 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 8d8db75..b41d7f0 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 @@ -46,6 +46,7 @@ import org.rhq.enterprise.gui.coregui.client.components.tab.TwoLevelTab; import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; 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; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.inventory.ResourceGroupMembershipView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.monitoring.schedules.SchedulesView; import org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.monitoring.traits.TraitsView; @@ -250,8 +251,11 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
visible = groupCategory == GroupCategory.COMPATIBLE && facets.contains(ResourceTypeFacet.CONFIGURATION); if (updateTab(this.configurationTab, visible, visible && this.permissions.isConfigureRead())) { - updateSubTab(this.configurationTab, this.configCurrent, new FullHTMLPane( - "/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" + groupId), true, true); + //updateSubTab(this.configurationTab, this.configCurrent, new FullHTMLPane( + // "/rhq/group/configuration/viewCurrent-plain.xhtml?groupId=" + groupId), true, true); + updateSubTab(this.configurationTab, this.configCurrent, + new GroupResourceConfigurationEditView(this.configCurrent.extendLocatorId("View"), + this.groupComposite), true, true); updateSubTab(this.configurationTab, this.configHistory, new FullHTMLPane( "/rhq/group/configuration/history-plain.xhtml?groupId=" + groupId), true, true); } 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 d77b10e..ee2297c 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 @@ -18,11 +18,15 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.configuration;
+import java.util.ArrayList; import java.util.EnumSet; +import java.util.List; import java.util.Map; import java.util.Set;
+import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; @@ -30,17 +34,23 @@ import com.smartgwt.client.widgets.layout.LayoutSpacer; import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; import org.rhq.enterprise.gui.coregui.client.components.configuration.GroupConfigurationEditor; +import org.rhq.enterprise.gui.coregui.client.components.configuration.GroupMemberConfiguration; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; +import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.resource.disambiguation.ReportDecorator; import org.rhq.enterprise.gui.coregui.client.util.message.Message; import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; @@ -52,11 +62,13 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Ian Springer */ public class GroupResourceConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { + private final ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService(); + private ResourceGroup group; private ResourcePermission resourcePermission; private ConfigurationDefinition configurationDefinition; private Configuration aggregateConfiguration; - private Map<Integer, Configuration> memberConfigurations; + private List<GroupMemberConfiguration> memberConfigurations;
private ConfigurationEditor editor; private IButton saveButton; @@ -112,7 +124,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme private void initEditor() { if (this.configurationDefinition != null && this.aggregateConfiguration != null) { this.editor = new GroupConfigurationEditor(this.extendLocatorId("Editor"), this.configurationDefinition, - this.aggregateConfiguration, null); + this.memberConfigurations); this.editor.setOverflow(Overflow.AUTO); this.editor.addPropertyValueChangeListener(this); this.editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); @@ -121,7 +133,7 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme }
private void loadConfigurationDefinition() { - if (configurationDefinition == null) { + if (this.configurationDefinition == null) { final ResourceType type = this.group.getResourceType(); ResourceTypeRepository.Cache.getInstance().getResourceTypes(new Integer[] { type.getId() }, EnumSet.of(ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), @@ -138,25 +150,34 @@ public class GroupResourceConfigurationEditView extends LocatableVLayout impleme }
private void loadConfigurations() { - // TODO this.aggregateConfiguration = null; - /*configurationService.getResourceConfiguration(resourceId, new AsyncCallback<Configuration>() { + this.memberConfigurations = null; + this.configurationService.findResourceConfigurationsForGroup(group.getId(), new AsyncCallback<List<DisambiguationReport<ResourceConfigurationComposite>>>() { public void onFailure(Throwable caught) { - showError(caught); + CoreGUI.getErrorHandler().handleError("Failed to retrieve member Resource configurations for " + group + ".", caught); }
- public void onSuccess(Configuration result) { - configuration = result; - Log.info("Config retreived in: " + (System.currentTimeMillis() - start)); + public void onSuccess(List<DisambiguationReport<ResourceConfigurationComposite>> results) { + memberConfigurations = new ArrayList<GroupMemberConfiguration>(results.size()); + for (DisambiguationReport<ResourceConfigurationComposite> result : results) { + String parentsHtml = ReportDecorator.decorateResourceLineage(result.getParents()); + int resourceId = result.getOriginal().getResourceId(); + String resourceHtml = ReportDecorator.decorateResourceName(ReportDecorator.GWT_RESOURCE_URL, + result.getResourceType(), result.getName(), resourceId); + String label = parentsHtml + ReportDecorator.DEFAULT_SEPARATOR + resourceHtml; + GroupMemberConfiguration memberConfiguration = new GroupMemberConfiguration(resourceId, label, + result.getOriginal().getConfiguration()); + memberConfigurations.add(memberConfiguration); + } initEditor(); } - });*/ + }); }
- private void save() { - Configuration updatedConfiguration = this.editor.getConfiguration(); - + private void save() { // TODO + + SC.say("Boo!"); /* GWTServiceLookup.getConfigurationService().updateResourceConfiguration(resource.getId(), updatedConfiguration, new AsyncCallback<ResourceConfigurationUpdate>() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java index 4bddff6..396f07a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java @@ -28,6 +28,7 @@ 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.PropertyDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionEnumeration; import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; @@ -45,6 +46,12 @@ import org.rhq.core.domain.configuration.definition.PropertySimpleType; public abstract class TestConfigurationFactory { public static ConfigurationDefinition createConfigurationDefinition() { ConfigurationDefinition configurationDefinition = new ConfigurationDefinition("TestConfig", "a test config"); + + ConfigurationTemplate defaultTemplate = new ConfigurationTemplate(ConfigurationTemplate.DEFAULT_TEMPLATE_NAME, "default template"); + configurationDefinition.putTemplate(defaultTemplate); + Configuration defaultConfiguration = new Configuration(); + defaultTemplate.setConfiguration(defaultConfiguration); + Map<String, PropertyDefinition> propertyDefinitions = new HashMap<String, PropertyDefinition>(); configurationDefinition.setPropertyDefinitions(propertyDefinitions);
@@ -85,9 +92,10 @@ public abstract class TestConfigurationFactory { "a String enum prop with <=5 items - should be rendered as radio buttons", false, PropertySimpleType.STRING); simplePropDef.setDisplayName(simplePropDef.getName()); + defaultConfiguration.put(new PropertySimple("StringEnum1", "NJ")); ArrayList<PropertyDefinitionEnumeration> propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); propDefEnums.add(new PropertyDefinitionEnumeration("NY", "NY")); - propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ")); propDefEnums.add(new PropertyDefinitionEnumeration("PA", "PA")); simplePropDef.setEnumeratedValues(propDefEnums, false); addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++); @@ -95,9 +103,10 @@ public abstract class TestConfigurationFactory { simplePropDef = new PropertyDefinitionSimple("StringEnum2", "a String enum prop with >5 items - should be rendered as a popup menu", false, PropertySimpleType.STRING); simplePropDef.setDisplayName(simplePropDef.getName()); + defaultConfiguration.put(new PropertySimple("StringEnum2", "blue")); propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); propDefEnums.add(new PropertyDefinitionEnumeration("red", "red")); - propDefEnums.add(new PropertyDefinitionEnumeration("orange", "orange", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("orange", "orange")); propDefEnums.add(new PropertyDefinitionEnumeration("yellow", "yellow")); propDefEnums.add(new PropertyDefinitionEnumeration("green", "green")); propDefEnums.add(new PropertyDefinitionEnumeration("blue", "blue")); @@ -186,9 +195,10 @@ public abstract class TestConfigurationFactory { PropertyDefinitionSimple enumExample = new PropertyDefinitionSimple("myEnum", "a grouped enum prop with <=5 items", false, PropertySimpleType.STRING); enumExample.setDisplayName(enumExample.getName()); + defaultConfiguration.put(new PropertySimple("myEnum", "Burlington")); ArrayList<PropertyDefinitionEnumeration> myEnums = new ArrayList<PropertyDefinitionEnumeration>(); myEnums.add(new PropertyDefinitionEnumeration("Burlington", "Burlington")); - myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden", true)); + myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden")); myEnums.add(new PropertyDefinitionEnumeration("Gloucester", "Gloucester")); enumExample.setEnumeratedValues(myEnums, false); addPropertyDefinition(propertyDefinitions, enumExample, orderIndex++); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java index 08d8046..abd6592 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ConfigurationGWTServiceImpl.java @@ -1,17 +1,29 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
+import java.util.ArrayList; +import java.util.List; +import java.util.Map; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.PluginConfigurationUpdate; import org.rhq.core.domain.configuration.RawConfiguration; import org.rhq.core.domain.configuration.ResourceConfigurationUpdate; +import org.rhq.core.domain.configuration.composite.ResourceConfigurationComposite; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria; +import org.rhq.core.domain.operation.composite.ResourceOperationLastCompletedComposite; +import org.rhq.core.domain.resource.composite.DisambiguationReport; +import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; +import org.rhq.core.util.IntExtractor; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTService; import org.rhq.enterprise.gui.coregui.server.util.SerialUtility; import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal; +import org.rhq.enterprise.server.resource.ResourceManagerLocal; +import org.rhq.enterprise.server.resource.disambiguation.DefaultDisambiguationUpdateStrategies; +import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; import org.rhq.enterprise.server.util.LookupUtil;
public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implements ConfigurationGWTService { @@ -19,6 +31,8 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen private static final long serialVersionUID = 1L;
private ConfigurationManagerLocal configurationManager = LookupUtil.getConfigurationManager(); + private ResourceManagerLocal resourceManager = LookupUtil.getResourceManager(); + private ResourceGroupManagerLocal groupManager = LookupUtil.getResourceGroupManager();
public Configuration getPluginConfiguration(int resourceId) { try { @@ -101,9 +115,43 @@ public class ConfigurationGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
+ public List<DisambiguationReport<ResourceConfigurationComposite>> findResourceConfigurationsForGroup( + int groupId) { + try { + ResourceGroup group = this.groupManager.getResourceGroup(getSessionSubject(), groupId); + Map<Integer,Configuration> configurations = + this.configurationManager.getResourceConfigurationMapForCompatibleGroup(group); + List<ResourceConfigurationComposite> configurationComposites = + new ArrayList<ResourceConfigurationComposite>(configurations.size()); + for (Integer resourceId : configurations.keySet()) { + Configuration configuration = configurations.get(resourceId); + ResourceConfigurationComposite configurationComposite = + new ResourceConfigurationComposite(resourceId, configuration); + configurationComposites.add(configurationComposite); + } + + // Disambiguate - i.e. generate unambiguous Resource names for each of the Resource id's. + List<DisambiguationReport<ResourceConfigurationComposite>> disambiguatedConfigurationComposites = resourceManager + .disambiguate(configurationComposites, RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR, + DefaultDisambiguationUpdateStrategies.getDefault()); + + return disambiguatedConfigurationComposites; + } catch (RuntimeException e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + public RawConfiguration dummy(RawConfiguration config) { com.allen_sauer.gwt.log.client.Log.info(config.getPath()); return new RawConfiguration(); // Dummy method for gwt compiler } + + private static final IntExtractor<ResourceConfigurationComposite> RESOURCE_CONFIGURATION_COMPOSITE_RESOURCE_ID_EXTRACTOR = + new IntExtractor<ResourceConfigurationComposite>() { + public int extract(ResourceConfigurationComposite configurationComposite) { + return configurationComposite.getResourceId(); + } + }; + } diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java index ccc5eeb..e9092fc 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java @@ -26,6 +26,7 @@ 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.PropertyDefinition; import org.rhq.core.domain.configuration.definition.PropertyDefinitionEnumeration; import org.rhq.core.domain.configuration.definition.PropertyDefinitionList; @@ -40,6 +41,12 @@ import org.rhq.core.domain.configuration.definition.PropertySimpleType; public abstract class TestConfigurationFactory { public static ConfigurationDefinition createConfigurationDefinition() { ConfigurationDefinition configurationDefinition = new ConfigurationDefinition("TestConfig", "a test config"); + + ConfigurationTemplate defaultTemplate = new ConfigurationTemplate(ConfigurationTemplate.DEFAULT_TEMPLATE_NAME, "default template"); + configurationDefinition.putTemplate(defaultTemplate); + Configuration defaultConfiguration = new Configuration(); + defaultTemplate.setConfiguration(defaultConfiguration); + Map<String, PropertyDefinition> propertyDefinitions = new HashMap<String, PropertyDefinition>(); configurationDefinition.setPropertyDefinitions(propertyDefinitions);
@@ -77,9 +84,10 @@ public abstract class TestConfigurationFactory { simplePropDef = new PropertyDefinitionSimple("StringEnum1", "a String enum prop with <=5 items - should be rendered as radio buttons", false, PropertySimpleType.STRING); simplePropDef.setDisplayName(simplePropDef.getName()); + defaultConfiguration.put(new PropertySimple("StringEnum1", "NJ")); ArrayList<PropertyDefinitionEnumeration> propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); propDefEnums.add(new PropertyDefinitionEnumeration("NY", "NY")); - propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ")); propDefEnums.add(new PropertyDefinitionEnumeration("PA", "PA")); simplePropDef.setEnumeratedValues(propDefEnums, false); propertyDefinitions.put(simplePropDef.getName(), simplePropDef); @@ -87,9 +95,10 @@ public abstract class TestConfigurationFactory { simplePropDef = new PropertyDefinitionSimple("StringEnum2", "a String enum prop with >5 items - should be rendered as a popup menu", false, PropertySimpleType.STRING); simplePropDef.setDisplayName(simplePropDef.getName()); + defaultConfiguration.put(new PropertySimple("StringEnum2", "blue")); propDefEnums = new ArrayList<PropertyDefinitionEnumeration>(); propDefEnums.add(new PropertyDefinitionEnumeration("red", "red")); - propDefEnums.add(new PropertyDefinitionEnumeration("orange", "orange", true)); + propDefEnums.add(new PropertyDefinitionEnumeration("orange", "orange")); propDefEnums.add(new PropertyDefinitionEnumeration("yellow", "yellow")); propDefEnums.add(new PropertyDefinitionEnumeration("green", "green")); propDefEnums.add(new PropertyDefinitionEnumeration("blue", "blue")); @@ -176,9 +185,10 @@ public abstract class TestConfigurationFactory { PropertyDefinitionSimple enumExample = new PropertyDefinitionSimple("myEnum", "a grouped enum prop with <=5 items", false, PropertySimpleType.STRING); enumExample.setDisplayName(enumExample.getName()); + defaultConfiguration.put(new PropertySimple("myEnum", "Burlington")); ArrayList<PropertyDefinitionEnumeration> myEnums = new ArrayList<PropertyDefinitionEnumeration>(); myEnums.add(new PropertyDefinitionEnumeration("Burlington", "Burlington")); - myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden", true)); + myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden")); myEnums.add(new PropertyDefinitionEnumeration("Gloucester", "Gloucester")); enumExample.setEnumeratedValues(myEnums, false); propertyDefinitions.put(enumExample.getName(), enumExample); diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/portlet/recentlyApproved/ViewAction.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/portlet/recentlyApproved/ViewAction.java index 90d59a3..e3d4723 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/portlet/recentlyApproved/ViewAction.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/legacy/portlet/recentlyApproved/ViewAction.java @@ -44,7 +44,6 @@ import org.rhq.enterprise.gui.legacy.WebUserPreferences.RecentlyApprovedPortletP import org.rhq.enterprise.gui.legacy.util.SessionUtils; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.disambiguation.DefaultDisambiguationUpdateStrategies; -import org.rhq.enterprise.server.resource.disambiguation.DisambiguationUpdateStrategy; import org.rhq.enterprise.server.util.LookupUtil;
public class ViewAction extends TilesAction { @@ -155,7 +154,7 @@ public class ViewAction extends TilesAction { }
public DisambiguatedRecentlyAddedResourceComposite(DisambiguationReport<RecentlyAddedResourceComposite> report) { - super(report.getOriginal(), report.getParents(), report.getResourceType()); + super(report.getOriginal(), report.getParents(), report.getResourceType(), report.getName()); children = new ArrayList<DisambiguatedRecentlyAddedResourceComposite>(); }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java index 3084285..8c4f78b 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/disambiguation/MutableDisambiguationReport.java @@ -99,9 +99,10 @@ public class MutableDisambiguationReport<T> { realParents.add(p.getResource()); } } - return new DisambiguationReport<T>(original, realParents, resource.resourceType.getResourceType()); + return new DisambiguationReport<T>(original, realParents, resource.resourceType.getResourceType(), resource.name); }
+ @Override public String toString() { return "MutableDisambiguationReport[resource=" + resource + ", parents=" + parents + "]"; } diff --git a/modules/enterprise/server/plugins/alert-mobicents/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-mobicents/src/main/resources/META-INF/rhq-serverplugin.xml index dfb28f6..5493cbc 100644 --- a/modules/enterprise/server/plugins/alert-mobicents/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-mobicents/src/main/resources/META-INF/rhq-serverplugin.xml @@ -40,9 +40,9 @@ <alert-configuration> <c:simple-property name="targetAddress" displayName="Address of the receiver" type="string" description="Address of the receiver. This may e.g. be a telephone number"/> - <c:simple-property name="kind" displayName="Type of notification" type="string" default="Voice"> + <c:simple-property name="kind" displayName="Type of notification" type="string" default="VOICE"> <c:property-options> - <c:option value="VOICE" name="Voice" default="true"/> + <c:option value="VOICE" name="Voice"/> <c:option value="SMS" name="SMS"/> <!-- <c:option value="MMS"/> diff --git a/modules/enterprise/server/plugins/alert-scriptlang/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-scriptlang/src/main/resources/META-INF/rhq-serverplugin.xml index df5d936..30c89a0 100644 --- a/modules/enterprise/server/plugins/alert-scriptlang/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-scriptlang/src/main/resources/META-INF/rhq-serverplugin.xml @@ -45,7 +45,7 @@ default="JRuby">
<c:property-options> - <c:option value="jruby" name="Ruby" default="true"/> + <c:option value="JRuby" name="Ruby"/> <c:option value="JavaScript"/> </c:property-options> </c:simple-property> diff --git a/modules/enterprise/server/plugins/alert-sms/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-sms/src/main/resources/META-INF/rhq-serverplugin.xml index cf87641..edd7531 100644 --- a/modules/enterprise/server/plugins/alert-sms/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-sms/src/main/resources/META-INF/rhq-serverplugin.xml @@ -22,9 +22,9 @@ serverplugin:plugin-configuration <c:simple-property name="login" type="string" description="Login to the provider" required="true"/> <c:simple-property name="password" type="password" description="Password for the provider" required="true"/> - <c:simple-property name="environment"> + <c:simple-property name="environment" default="sandbox"> <c:property-options> - <c:option value="sandbox" default="true"/> + <c:option value="sandbox"/> <c:option value="production"/> </c:property-options> </c:simple-property> diff --git a/modules/enterprise/server/plugins/cobbler/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/cobbler/src/main/resources/META-INF/rhq-serverplugin.xml index 1bcc161..6109a85 100644 --- a/modules/enterprise/server/plugins/cobbler/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/cobbler/src/main/resources/META-INF/rhq-serverplugin.xml @@ -60,7 +60,7 @@ <c:simple-property name="scheduleType" type="string" required="true" default="cron" summary="true" description="Indicates the type of trigger this synchronize job will use"> <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/30 * * * ?" summary="true" description="Determines how often Cobbler will be synchronized with RHQ content. Based on the schedule type, this is either the period, in milliseconds, or the cron expression."/> diff --git a/modules/enterprise/server/plugins/groovy-script/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/groovy-script/src/main/resources/META-INF/rhq-serverplugin.xml index fe6e665..f69104f 100644 --- a/modules/enterprise/server/plugins/groovy-script/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/groovy-script/src/main/resources/META-INF/rhq-serverplugin.xml @@ -54,7 +54,7 @@ <!--<c:simple-property name="scheduleType" type="string" required="true" default="cron" summary="true">--> <!--<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/30 * * * ?" summary="true"/>-->
commit 50c2b4a82e511ef60041f8bd34301a0958cc67f9 Author: Heiko W. Rupp hwr@redhat.com Date: Thu Oct 7 22:52:41 2010 +0200
Update help to better suit reality
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java index cb93aa2..e8c1c05 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/StandaloneContainer.java @@ -323,6 +323,7 @@ public class StandaloneContainer { for (Command comm : EnumSet.allOf(Command.class)) { System.out.println(comm + " ( " + comm.getAbbrev() + " ), " + comm.getArgs() + " : " + comm.getHelp()); } + System.out.println("Also check out !h for help on history commands"); break; case INVOKE: invokeOps(tokens); @@ -707,7 +708,7 @@ public class StandaloneContainer { NATIVE("n", "e | d | s", 1, "Enables/disables native system or shows native status"), // QUIT("quit", "", 0, "Terminates the application"), // RESOURCES("res", "", 0, "Shows the discovered resources"), // - SET("set", "resourceId n", 2, + SET("set", "'resource' N", 2, "Sets the resource id to work with. N can be a number or '$r' as result of last find resource call"), // WAIT("w", "milliseconds", 1, "Waits the given amount of time"), P_CONFIG("pc", "", 0, "Shows the plugin configuration of the current resource."),
commit 5dacfc94663d163f92d499f6ccddf901e6207b05 Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 12:44:02 2010 -0400
start of group resource config view
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 new file mode 100644 index 0000000..d77b10e --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/configuration/GroupResourceConfigurationEditView.java @@ -0,0 +1,199 @@ +/* + * 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.inventory.groups.detail.configuration; + +import java.util.EnumSet; +import java.util.Map; +import java.util.Set; + +import com.smartgwt.client.types.Overflow; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.layout.LayoutSpacer; +import com.smartgwt.client.widgets.toolbar.ToolStrip; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.composite.ResourcePermission; +import org.rhq.core.domain.resource.group.ResourceGroup; +import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.components.configuration.ConfigurationEditor; +import org.rhq.enterprise.gui.coregui.client.components.configuration.GroupConfigurationEditor; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeEvent; +import org.rhq.enterprise.gui.coregui.client.components.configuration.PropertyValueChangeListener; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; +import org.rhq.enterprise.gui.coregui.client.util.message.MessageCenter; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * A view for editing a group's configuration. + * + * @author Ian Springer + */ +public class GroupResourceConfigurationEditView extends LocatableVLayout implements PropertyValueChangeListener { + private ResourceGroup group; + private ResourcePermission resourcePermission; + private ConfigurationDefinition configurationDefinition; + private Configuration aggregateConfiguration; + private Map<Integer, Configuration> memberConfigurations; + + private ConfigurationEditor editor; + private IButton saveButton; + + public GroupResourceConfigurationEditView(String locatorId, ResourceGroupComposite groupComposite) { + super(locatorId); + + this.group = groupComposite.getResourceGroup(); + this.resourcePermission = groupComposite.getResourcePermission(); + } + + @Override + protected void onDraw() { + super.onDraw(); + build(); + } + + public void build() { + ToolStrip toolStrip = new ToolStrip(); + toolStrip.setWidth100(); + + toolStrip.addMember(new LayoutSpacer()); + + this.saveButton = new LocatableIButton(this.extendLocatorId("Save"), "Save"); + this.saveButton.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent clickEvent) { + save(); + } + }); + toolStrip.addMember(saveButton); + + addMember(toolStrip); + reloadConfiguration(); + + if (!this.resourcePermission.isConfigureWrite()) { + Message message = new Message("You do not have permission to edit this group's configuration.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); + CoreGUI.getMessageCenter().notify(message); + } + } + + private void reloadConfiguration() { + this.saveButton.disable(); + if (editor != null) { + editor.destroy(); + removeMember(editor); + } + + loadConfigurationDefinition(); + loadConfigurations(); + } + + private void initEditor() { + if (this.configurationDefinition != null && this.aggregateConfiguration != null) { + this.editor = new GroupConfigurationEditor(this.extendLocatorId("Editor"), this.configurationDefinition, + this.aggregateConfiguration, null); + this.editor.setOverflow(Overflow.AUTO); + this.editor.addPropertyValueChangeListener(this); + this.editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); + addMember(this.editor); + } + } + + private void loadConfigurationDefinition() { + if (configurationDefinition == null) { + final ResourceType type = this.group.getResourceType(); + ResourceTypeRepository.Cache.getInstance().getResourceTypes(new Integer[] { type.getId() }, + EnumSet.of(ResourceTypeRepository.MetadataType.resourceConfigurationDefinition), + new ResourceTypeRepository.TypesLoadedCallback() { + public void onTypesLoaded(Map<Integer, ResourceType> types) { + configurationDefinition = types.get(type.getId()).getResourceConfigurationDefinition(); + if (configurationDefinition == null) { + throw new IllegalStateException("Configuration is not supported by this group."); + } + initEditor(); + } + }); + } + } + + private void loadConfigurations() { + // TODO + this.aggregateConfiguration = null; + /*configurationService.getResourceConfiguration(resourceId, new AsyncCallback<Configuration>() { + public void onFailure(Throwable caught) { + showError(caught); + } + + public void onSuccess(Configuration result) { + configuration = result; + Log.info("Config retreived in: " + (System.currentTimeMillis() - start)); + initEditor(); + } + });*/ + } + + private void save() { + Configuration updatedConfiguration = this.editor.getConfiguration(); + + // TODO +/* + GWTServiceLookup.getConfigurationService().updateResourceConfiguration(resource.getId(), updatedConfiguration, + new AsyncCallback<ResourceConfigurationUpdate>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to update configuration.", caught); + } + + public void onSuccess(ResourceConfigurationUpdate result) { + CoreGUI.getMessageCenter().notify( + new Message("Configuration updated.", + "Configuration updated for Resource [" + resource.getName() + "].", + Message.Severity.Info)); + reloadConfiguration(); + } + }); +*/ + } + + @Override + public void propertyValueChanged(PropertyValueChangeEvent event) { + MessageCenter messageCenter = CoreGUI.getMessageCenter(); + Message message; + if (event.isValidationStateChanged()) { + Set<String> invalidPropertyNames = event.getInvalidPropertyNames(); + if (invalidPropertyNames.isEmpty()) { + this.saveButton.enable(); + message = new Message("All configuration properties have valid values, so the configuration can now be saved.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); + } else { + this.saveButton.disable(); + message = new Message("The following configuration properties have invalid values: " + + invalidPropertyNames + ". The values must be corrected before the configuration can be saved.", + Message.Severity.Error, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); + } + messageCenter.notify(message); + } else { + this.saveButton.enable(); + } + } +}
commit 1d814e59264be7bb2c4fcc6a54be6518cc61be53 Author: Ian Springer ian.springer@redhat.com Date: Thu Oct 7 12:41:34 2010 -0400
get rid of unused is_default field in PropertyDefinitionEnumeration (https://bugzilla.redhat.com/show_bug.cgi?id=536496)
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java index 9d09ba1..72e107a 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/ConfigurationMetadataParser.java @@ -265,8 +265,8 @@ public class ConfigurationMetadataParser { name = option.getValue(); }
- parentProperty.addEnumeratedValues(new PropertyDefinitionEnumeration(name, option.getValue(), option - .isDefault())); + PropertyDefinitionEnumeration enumeration = new PropertyDefinitionEnumeration(name, option.getValue()); + parentProperty.addEnumeratedValues(enumeration); }
parentProperty.setAllowCustomEnumeratedValue(options.isAllowCustomValue()); diff --git a/modules/core/client-api/src/main/resources/rhq-configuration.xsd b/modules/core/client-api/src/main/resources/rhq-configuration.xsd index 590f459..fe898f2 100644 --- a/modules/core/client-api/src/main/resources/rhq-configuration.xsd +++ b/modules/core/client-api/src/main/resources/rhq-configuration.xsd @@ -442,7 +442,7 @@
<xs:complexType name="option"> xs:annotation - xs:documentationUsed to describe items available in a property with a list type. + xs:documentationDescribes an allowed value for an enumerated simple property. </xs:documentation> </xs:annotation> <xs:attribute name="name" use="optional"> @@ -463,15 +463,6 @@ <xs:restriction base="xs:string"/> </xs:simpleType> </xs:attribute> - <xs:attribute name="default" default="false" use="optional"> - xs:annotation - xs:documentationIndicates this item is the default item in the list. Default value is false. - </xs:documentation> - </xs:annotation> - xs:simpleType - <xs:restriction base="xs:boolean"/> - </xs:simpleType> - </xs:attribute> </xs:complexType>
<!-- == Property Constraints ================= --> diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 4cf8ae1..cb7f1d7 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -22,7 +22,7 @@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.97</db.schema.version> + <db.schema.version>2.98</db.schema.version> </properties>
<dependencies> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml index 4db0a57..209a8a9 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/config-schema.xml @@ -54,7 +54,6 @@ <column name="ID" type="INTEGER" required="true" default="sequence-only" initial="10001" primarykey="true"/> <column name="STRING_VALUE" type="VARCHAR2" required="false" size="500"/> <column name="ORDER_INDEX" type="INTEGER" required="false"/> - <column name="IS_DEFAULT" type="BOOLEAN" required="false"/> <column name="NAME" type="VARCHAR2" required="false" size="100"/> <column name="PROPERTY_DEF_ID" type="INTEGER" required="false" references="RHQ_CONFIG_PROP_DEF"/> </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 b477b09..70e4c46 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3240,7 +3240,12 @@ </statement> </schema-directSQL> </schemaSpec> - + + <schemaSpec version="2.98"> + <!-- Remove is_default field from simple prop def enums --> + <schema-deleteColumn ignoreError="true" table="RHQ_CONF_PROP_DEF_ENUM" column="IS_DEFAULT" /> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java index fbcabb4..4412cec 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionEnumeration.java @@ -64,6 +64,10 @@ public class PropertyDefinitionEnumeration implements Serializable { private int orderIndex = -1;
@Column(name = "IS_DEFAULT") + @Deprecated + /** + * @deprecated - not used; TODO: remove in dbsetup/dbupgrade scripts + */ private boolean isDefault;
@JoinColumn(name = "PROPERTY_DEF_ID") @@ -76,13 +80,8 @@ public class PropertyDefinitionEnumeration implements Serializable { }
public PropertyDefinitionEnumeration(@NotNull String name, String value) { - this(name, value, false); - } - - public PropertyDefinitionEnumeration(@NotNull String name, String value, boolean isDefault) { this.name = name; this.value = value; - this.isDefault = isDefault; }
// @PrePersist @@ -142,39 +141,27 @@ public class PropertyDefinitionEnumeration implements Serializable { this.orderIndex = orderIndex; }
- /** - * Two items are equal if they have the same name and share the same PropertyDefinitionSimple - */ @Override public boolean equals(Object o) { if (this == o) { return true; } - - if ((o == null) || (!(o instanceof PropertyDefinitionEnumeration))) { + if (o == null || getClass() != o.getClass()) { return false; }
- PropertyDefinitionEnumeration that = (PropertyDefinitionEnumeration) o; + PropertyDefinitionEnumeration that = (PropertyDefinitionEnumeration)o;
- if ((name != null) ? (!name.equals(that.name)) : (that.name != null)) { + if (!value.equals(that.value)) { return false; }
- /*if ((propertyDefinitionSimple != null) ? (!propertyDefinitionSimple.equals(that.propertyDefinitionSimple)) - : (that.propertyDefinitionSimple != null)) { - return false; - }*/ - return true; }
@Override public int hashCode() { - int result; - result = ((name != null) ? name.hashCode() : 0); - // result = (31 * result) + ((propertyDefinitionSimple != null) ? propertyDefinitionSimple.hashCode() : 0); - return result; + return value.hashCode(); }
@Override diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java index 782dc99..174aa8e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/configuration/definition/PropertyDefinitionSimple.java @@ -24,7 +24,6 @@ package org.rhq.core.domain.configuration.definition;
import java.util.ArrayList; import java.util.HashSet; -import java.util.LinkedHashSet; import java.util.List; import java.util.Set;
diff --git a/modules/plugins/apache/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/apache/src/main/resources/META-INF/rhq-plugin.xml index b3f5aa3..420aa01 100644 --- a/modules/plugins/apache/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/apache/src/main/resources/META-INF/rhq-plugin.xml @@ -150,7 +150,7 @@ UseCanonicalName DNS is intended for use with mass IP-based virtual hosting to support ancient clients that do not provide a Host: header. With this option Apache does a reverse DNS lookup on the server IP address that the client connected to in order to work out self-referential URLs. </c:description> <c:property-options> - <c:option value="Off" default="true"/> + <c:option value="Off"/> <c:option value="On"/> <c:option value="DNS"/> </c:property-options> @@ -163,7 +163,7 @@ In many situations Apache must construct a self-referential URL -- that is, a URL that refers back to the same server. With UseCanonicalPhysicalPort On Apache will, when constructing the canonical port for the server to honor the UseCanonicalName directive, provide the actual physical port number being used by this request as a potential port. With UseCanonicalPhysicalPort Off Apache will not ever use the actual physical port number, instead relying on all configured information to construct a valid port number. </c:description> <c:property-options> - <c:option value="Off" default="true"/> + <c:option value="Off"/> <c:option value="On"/> </c:property-options> </c:simple-property> @@ -175,16 +175,16 @@ The Options directive controls which server features are available in a particular directory. </c:description> <c:map-property name="Options"> - <c:simple-property name="Mode"> + <c:simple-property name="Mode" default="Set"> <c:property-options> - <c:option value="Set" default="true"/> + <c:option value="Set"/> <c:option value="Add"/> <c:option value="Remove"/> </c:property-options> </c:simple-property> - <c:simple-property name="Option"> + <c:simple-property name="Option" default="All"> <c:property-options> - <c:option value="All" default="true"/> + <c:option value="All"/> <c:option value="None"/> <c:option value="ExecCGI"/> <c:option value="FollowSymLinks"/> @@ -295,7 +295,7 @@ <c:simple-property name="augeasEnabled" displayName="Enable augeas support" description="Enable augeas support" default="no"> <c:property-options> <c:option value="yes" name="Yes"/> - <c:option value="no" name="No" default="true"/> + <c:option value="no" name="No"/> </c:property-options> </c:simple-property>
@@ -309,10 +309,11 @@ </c:group>
<c:group name="Virtual Hosts"> - <c:simple-property name="vhostCreationPolicy" displayName="Virtual Hosts Configuration Placement" description="How should the new virtual host definitions be put in the configuration" default="vhost-per-file"> + <c:simple-property name="vhostCreationPolicy" displayName="Virtual Hosts Configuration Placement" + description="How should the new virtual host definitions be put in the configuration" default="vhost-per-file"> <c:property-options> <c:option value="single-file" name="In the main configuration file"/> - <c:option value="vhost-per-file" name="Each Virtual Host in a standalone file" default="true"/> + <c:option value="vhost-per-file" name="Each Virtual Host in a standalone file"/> </c:property-options> </c:simple-property>
@@ -339,7 +340,7 @@ <c:option name="debug" value="debug"/> <c:option name="info" value="info"/> <c:option name="warn" value="warn"/> - <c:option name="error" value="error" default="true"/> + <c:option name="error" value="error"/> <c:option name="fatal" value="fatal"/> </c:property-options> </c:simple-property> 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 47ca3e0..473daf1 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 @@ -572,9 +572,9 @@ </c:description> <c:map-property name="config-property"> <c:simple-property name="name" description="The name of the configuration property." /> - <c:simple-property name="type" description="The type of the configuration property."> + <c:simple-property name="type" description="The type of the configuration property." default="java.lang.String"> <c:property-options> - <c:option value="java.lang.String" default="true"/> + <c:option value="java.lang.String"/> <c:option value="java.lang.Boolean"/> <c:option value="java.lang.Integer"/> <c:option value="java.lang.Double"/> @@ -1067,7 +1067,7 @@ <c:option name="debug" value="debug"/> <c:option name="info" value="info"/> <c:option name="warn" value="warn"/> - <c:option name="error" value="error" default="true"/> + <c:option name="error" value="error"/> <c:option name="fatal" value="fatal"/> </c:property-options> </c:simple-property> diff --git a/modules/plugins/jboss-as/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as/src/main/resources/META-INF/rhq-plugin.xml index b3ea3f5..19eed1e 100644 --- a/modules/plugins/jboss-as/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-as/src/main/resources/META-INF/rhq-plugin.xml @@ -62,7 +62,7 @@ description="The method used to execute the Shutdown operation; defaults to 'JMX MBean'."> <c:property-options> - <c:option value="JMX" name="JMX MBean" default="true"/> + <c:option value="JMX" name="JMX MBean"/> <c:option value="SCRIPT" name="shutdown script"/> </c:property-options> </c:simple-property> @@ -103,7 +103,7 @@ <c:option name="debug" value="debug"/> <c:option name="info" value="info"/> <c:option name="warn" value="warn"/> - <c:option name="error" value="error" default="true"/> + <c:option name="error" value="error"/> <c:option name="fatal" value="fatal"/> </c:property-options> </c:simple-property> @@ -443,10 +443,10 @@ <resource-configuration>
<c:group name="connection" displayName="Connection Information"> - <c:simple-property name="type"> + <c:simple-property name="type" default="local-tx-datasource"> <c:property-options> <c:option value="no-tx-datasource" name="No TX Datasource"/> - <c:option value="local-tx-datasource" name="Local TX Datasource" default="true"/> + <c:option value="local-tx-datasource" name="Local TX Datasource"/> <c:option value="xa-datasource" name="XA Datasource"/> </c:property-options> </c:simple-property> @@ -466,11 +466,11 @@ </c:group>
<c:group name="advanced" displayName="Advanced"> - <c:simple-property name="transaction-isolation" required="false" + <c:simple-property name="transaction-isolation" required="false" default="TRANSACTION_READ_COMMITTED" description="The Transaction Isolation level. The default setting is to use whichever isolation level is provided by default by the database."> <c:property-options> <c:option value="TRANSACTION_READ_UNCOMMITTED" name="Read Uncommitted"/> - <c:option value="TRANSACTION_READ_COMMITTED" default="true" name="Read Committed"/> + <c:option value="TRANSACTION_READ_COMMITTED" name="Read Committed"/> <c:option value="TRANSACTION_REPEATABLE_READ" name="Repeatable Read"/> <c:option value="TRANSACTION_SERIALIZABLE" name="Serializable"/> <c:option value="TRANSACTION_NONE" name="None"/> @@ -749,11 +749,11 @@ <c:simple-property name="transaction-type" type="string" displayName="Transaction Type" - default="true" + default="Local Transaction" description="Whether to use local or xa transactions. If nothing is specified, the default of local will be used." required="false"> <c:property-options> - <c:option value="Local Transaction" default="true"/> + <c:option value="Local Transaction"/> <c:option value="XA Transaction"/> </c:property-options> </c:simple-property> diff --git a/modules/plugins/jboss-cache/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-cache/src/main/resources/META-INF/rhq-plugin.xml index 2ef0f4f..61c4d08 100644 --- a/modules/plugins/jboss-cache/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jboss-cache/src/main/resources/META-INF/rhq-plugin.xml @@ -99,8 +99,8 @@ <c:simple-property name="Flavour" default="treecache" description="Is this going to be a Pojo Cache or a Tree Cache"> <c:property-options> - <c:option name="POJO Cache" value="cache" default="false"/> - <c:option name="Tree Cache" value="treecache" default="true"/> + <c:option name="POJO Cache" value="cache"/> + <c:option name="Tree Cache" value="treecache"/> </c:property-options> </c:simple-property> <c:simple-property name="TransactionManagerLookupClass" @@ -110,7 +110,7 @@ description="The isolation level for access to the cache"> <c:property-options> <c:option value="SERIALIZABLE"/> - <c:option value="REPEATABLE_READ" default="true"/> + <c:option value="REPEATABLE_READ"/> <c:option value="READ_COMMITTED"/> <c:option value="READ_UNCOMMITTED"/> <c:option value="NONE"/> @@ -119,12 +119,12 @@ <c:simple-property name="NodeLockingScheme" default="PESSIMISTIC"> <c:property-options> <c:option value="OPTIMISTIC"/> - <c:option value="PESSIMISTIC" default="true"/> + <c:option value="PESSIMISTIC"/> </c:property-options> </c:simple-property> <c:simple-property name="CacheMode" default="LOCAL"> <c:property-options> - <c:option value="LOCAL" default="true"/> + <c:option value="LOCAL"/> <c:option value="REPL_ASYNC"/> <c:option value="REPL_SYNC"/> </c:property-options> diff --git a/modules/plugins/jmx/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jmx/src/main/resources/META-INF/rhq-plugin.xml index dc5a4cf..b142a22 100644 --- a/modules/plugins/jmx/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/jmx/src/main/resources/META-INF/rhq-plugin.xml @@ -17,9 +17,10 @@ <!-- Properties are connection/lookup configurations. They are values that the plugin components need to connect and interact with the resource. --> <plugin-configuration> - <c:simple-property name="type" type="string" description="The EMS connection type for this JMX Server"> + <c:simple-property name="type" type="string" default="LocalVMTypeDescriptor" + description="The EMS connection type for this JMX Server"> <c:property-options> - <c:option value="LocalVMTypeDescriptor" name="Local" default="true"/> + <c:option value="LocalVMTypeDescriptor" name="Local"/> <c:option value="org.mc4j.ems.connection.support.metadata.JBossConnectionTypeDescriptor" name="JBoss"/> <c:option value="org.mc4j.ems.connection.support.metadata.Tomcat55ConnectionTypeDescriptor" name="Tomcat"/> <c:option value="org.mc4j.ems.connection.support.metadata.JDMKConnectionTypeDescriptor" name="JDMK"/> diff --git a/modules/plugins/lsof/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/lsof/src/main/resources/META-INF/rhq-plugin.xml index a280d27..0053a9d 100644 --- a/modules/plugins/lsof/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/lsof/src/main/resources/META-INF/rhq-plugin.xml @@ -17,9 +17,9 @@ supportsManualAdd="true">
<plugin-configuration> - <c:simple-property name="detectionMechanism" required="true" defaultValue="EXTERNAL" description="Determines how to perform network resource detection. 'external' means that an external executable tool (e.g. lsof) will be used; 'internal' means internal Java detection code provided by the RHQ plugin will be used."> + <c:simple-property name="detectionMechanism" required="true" default="EXTERNAL" description="Determines how to perform network resource detection. 'external' means that an external executable tool (e.g. lsof) will be used; 'internal' means internal Java detection code provided by the RHQ plugin will be used."> <c:property-options> - <c:option value="EXTERNAL" default="true" /> + <c:option value="EXTERNAL" /> <c:option value="INTERNAL" /> </c:property-options> </c:simple-property> diff --git a/modules/plugins/netservices/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/netservices/src/main/resources/META-INF/rhq-plugin.xml index 1db41e0..a3b869c 100644 --- a/modules/plugins/netservices/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/netservices/src/main/resources/META-INF/rhq-plugin.xml @@ -21,7 +21,7 @@ <c:simple-property name="validateResponseCode" type="boolean" default="false"/> <c:simple-property name="sslProtocol" default="none"> <c:property-options> - <c:option value="none" default="true"/> + <c:option value="none"/> <c:option value="SSL"/> <c:option value="TLS"/> </c:property-options> @@ -29,7 +29,7 @@ <c:simple-property name="method" default="GET"> <c:property-options> <c:option value="HEAD"/> - <c:option value="GET" default="true"/> + <c:option value="GET"/> </c:property-options> </c:simple-property> <c:simple-property name="followRedirects" type="boolean" default="false"/> diff --git a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml index 34a4e71..06900c8 100644 --- a/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/perftest/src/main/resources/META-INF/rhq-plugin.xml @@ -175,10 +175,10 @@ <c:simple-property name="file" type="file"/> <c:simple-property name="directory" type="directory"/>
- <c:simple-property name="enum"> + <c:simple-property name="enum" default="Blue"> <c:property-options> <c:option value="red" name="Red"/> - <c:option value="blue" name="Blue" default="true"/> + <c:option value="blue" name="Blue"/> <c:option value="green" name="Green"/> </c:property-options> </c:simple-property> diff --git a/modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml index 5a4a8a7..493382e 100644 --- a/modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/platform/src/main/resources/META-INF/rhq-plugin.xml @@ -156,13 +156,13 @@ <c:simple-property name="logTrackingMinimumSeverity" displayName="Minimum Severity" required="false" default="Warning" description="The minimum severity of log messages that will be collected. If not specified, there is no minimum severity (i.e. all will be collected)."> <c:property-options> <c:option value="Information"/> - <c:option value="Warning" default="true"/> + <c:option value="Warning"/> <c:option value="Error"/> </c:property-options> </c:simple-property> <c:simple-property name="logTrackingType" summary="true" required="true" default="file" description="Defines if the log messages are to be found by polling a file or listening to a TCP socket"> <c:property-options> - <c:option value="file" default="true"/> + <c:option value="file"/> <c:option value="listener"/> </c:property-options> </c:simple-property> @@ -220,7 +220,7 @@ <c:simple-property name="minimumSeverity" default="Warning" description="The minimum severity event that will be collected"> <c:property-options> <c:option value="Information"/> - <c:option value="Warning" default="true"/> + <c:option value="Warning"/> <c:option value="Error"/> </c:property-options> </c:simple-property> @@ -573,7 +573,7 @@ <plugin-configuration> <c:simple-property name="type" default="pidFile" description="Choice of using a pid file or a PIQL query to find the process to monitor"> <c:property-options> - <c:option value="pidFile" default="true" name="Pid File"/> + <c:option value="pidFile" name="Pid File"/> <c:option value="piql" name="Process Query"/> </c:property-options> </c:simple-property> 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 df799fe..d59b312 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 @@ -36,7 +36,7 @@ to determine if an event should be fired for that entry. If not specified, no filtering of log entries will be done based on their detail."/> - <c:simple-property name="minimumSeverity" required="false" default="error" + <c:simple-property name="minimumSeverity" required="false" default="ERROR" description="The minimum severity of log messages that should be collected for this source. If not specified, there is no minimum severity (i.e. all log messages will be collected)."> @@ -44,7 +44,7 @@ <c:option name="debug" value="DEBUG"/> <c:option name="info" value="INFO"/> <c:option name="warn" value="WARN"/> - <c:option name="error" value="ERROR" default="true"/> + <c:option name="error" value="ERROR"/> <c:option name="fatal" value="FATAL"/> </c:property-options> </c:simple-property> @@ -364,7 +364,7 @@ <c:description>Communication settings that define the endpoints of this RHQ Agent and its RHQ Server</c:description> <c:simple-property name="rhq.agent.server.transport" type="string" activationPolicy="restart" required="true" default="servlet" displayName="RHQ Server Transport Protocol" description="The transport protocol used to send commands to the RHQ Server. If you want secure communications, the RHQ Server must use an SSL-enabled transport"> <c:property-options> - <c:option name="servlet" value="servlet" default="true" /> + <c:option name="servlet" value="servlet" /> <c:option name="sslservlet" value="sslservlet" /> <c:option name="socket" value="socket" /> <c:option name="sslsocket" value="sslsocket" /> @@ -382,7 +382,7 @@ <c:simple-property name="rhq.agent.server.alias" type="string" activationPolicy="restart" required="false" default="rhqserver" displayName="RHQ Server Alias" description="If the RHQ Server IP address is not defined, this is the DNS alias name that will be looked up to determine the RHQ Server IP address." /> <c:simple-property name="rhq.communications.connector.transport" type="string" activationPolicy="restart" required="true" default="socket" displayName="Agent Transport Protocol" description="The transport protocol used to receive commands from the RHQ Server. e.g. socket, sslsocket. If you want secure communications, you must use an SSL-enabled transport"> <c:property-options> - <c:option name="socket" value="socket" default="true" /> + <c:option name="socket" value="socket" /> <c:option name="sslsocket" value="sslsocket" /> </c:property-options> </c:simple-property> @@ -399,7 +399,7 @@ <c:simple-property name="rhq.communications.connector.security.secure-socket-protocol" type="string" activationPolicy="restart" required="false" default="TLS" displayName="Incoming: Secure Socket Protocol"> <c:property-options allowCustomValue="true"> - <c:option name="TLS" value="TLS" default="true" /> + <c:option name="TLS" value="TLS" /> <c:option name="SSL_TLS" value="SSL_TLS" /> <c:option name="SSL" value="SSL" /> <c:option name="SSLv3" value="SSLv3" /> @@ -410,7 +410,7 @@ <c:simple-property name="rhq.communications.connector.security.keystore.algorithm" type="string" activationPolicy="restart" required="false" default="SunX509" displayName="Incoming: Keystore Algorithm" > <c:property-options allowCustomValue="true"> - <c:option name="SunX509" value="SunX509" default="true" /> + <c:option name="SunX509" value="SunX509" /> <c:option name="IbmX509" value="IbmX509" /> </c:property-options> </c:simple-property> @@ -432,14 +432,14 @@ <c:simple-property name="rhq.communications.connector.security.truststore.algorithm" type="string" activationPolicy="restart" required="false" default="SunX509" displayName="Incoming: Truststore Algorithm"> <c:property-options allowCustomValue="true"> - <c:option name="SunX509" value="SunX509" default="true" /> + <c:option name="SunX509" value="SunX509" /> <c:option name="IbmX509" value="IbmX509" /> </c:property-options> </c:simple-property> <c:simple-property name="rhq.communications.connector.security.truststore.type" type="string" activationPolicy="restart" required="false" default="JKS" displayName="Incoming: Truststore Type"> <c:property-options allowCustomValue="true"> - <c:option name="JKS" value="JKS" default="true" /> + <c:option name="JKS" value="JKS" /> <c:option name="PKCS12" value="PKCS12" /> </c:property-options> </c:simple-property> @@ -449,7 +449,7 @@ type="string" activationPolicy="restart" required="false" default="none" displayName="Incoming: Client Authentication Mode" description="Determines if the agent should authenticate a RHQ Server before accepting incoming commands from it"> <c:property-options> - <c:option name="none" value="none" default="true" /> + <c:option name="none" value="none" /> <c:option name="want" value="want" /> <c:option name="need" value="need" /> </c:property-options> @@ -458,7 +458,7 @@ <c:simple-property name="rhq.agent.client.security.secure-socket-protocol" type="string" activationPolicy="restart" required="false" default="TLS" displayName="Outgoing: Secure Socket Protocol"> <c:property-options allowCustomValue="true"> - <c:option name="TLS" value="TLS" default="true" /> + <c:option name="TLS" value="TLS" /> <c:option name="SSL_TLS" value="SSL_TLS" /> <c:option name="SSL" value="SSL" /> <c:option name="SSLv3" value="SSLv3" /> @@ -469,14 +469,14 @@ <c:simple-property name="rhq.agent.client.security.keystore.algorithm" type="string" activationPolicy="restart" required="false" default="SunX509" displayName="Outgoing: Keystore Algorithm"> <c:property-options allowCustomValue="true"> - <c:option name="SunX509" value="SunX509" default="true" /> + <c:option name="SunX509" value="SunX509" /> <c:option name="IbmX509" value="IbmX509" /> </c:property-options> </c:simple-property> <c:simple-property name="rhq.agent.client.security.keystore.type" type="string" activationPolicy="restart" required="false" default="JKS" displayName="Outgoing: Keystore Type"> <c:property-options allowCustomValue="true"> - <c:option name="JKS" value="JKS" default="true" /> + <c:option name="JKS" value="JKS" /> <c:option name="PKCS12" value="PKCS12" /> </c:property-options> </c:simple-property> @@ -491,14 +491,14 @@ <c:simple-property name="rhq.agent.client.security.truststore.algorithm" type="string" activationPolicy="restart" required="false" default="SunX509" displayName="Outgoing: Truststore Algorithm"> <c:property-options allowCustomValue="true"> - <c:option name="SunX509" value="SunX509" default="true" /> + <c:option name="SunX509" value="SunX509" /> <c:option name="IbmX509" value="IbmX509" /> </c:property-options> </c:simple-property> <c:simple-property name="rhq.agent.client.security.truststore.type" type="string" activationPolicy="restart" required="false" default="JKS" displayName="Outgoing: Truststore Type"> <c:property-options allowCustomValue="true"> - <c:option name="JKS" value="JKS" default="true" /> + <c:option name="JKS" value="JKS" /> <c:option name="PKCS12" value="PKCS12" /> </c:property-options> </c:simple-property> diff --git a/modules/plugins/sshd/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/sshd/src/main/resources/META-INF/rhq-plugin.xml index 06f359f..b5abbdf 100644 --- a/modules/plugins/sshd/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/sshd/src/main/resources/META-INF/rhq-plugin.xml @@ -64,7 +64,8 @@
<c:group name="Settings">
- <c:simple-property name="Protocol" required="false" description=" + <c:simple-property name="Protocol" required="false" default="2" + description=" Specifies the protocol versions sshd(8) supports. The possible values are `1' and `2'. Multiple versions must be comma-separat- ed. The default is ``2,1''. Note that the order of the protocol @@ -73,12 +74,13 @@ ing ``2,1'' is identical to ``1,2''."> <c:property-options> <c:option value="1" name="Version 1 Only"/> - <c:option value="2" default="true" name="Version 2 Only"/> + <c:option value="2" name="Version 2 Only"/> <c:option value="1,2" name="Both Version 1 and Version 2"/> </c:property-options> </c:simple-property>
- <c:simple-property name="LogLevel" required="false" description=" + <c:simple-property name="LogLevel" required="false" default="INFO" + description=" Gives the verbosity level that is used when logging messages from sshd(8). The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default is INFO. @@ -89,18 +91,18 @@ <c:option value="QUIET" name="QUIET"/> <c:option value="FATAL" name="FATAL"/> <c:option value="ERROR" name="ERROR"/> - <c:option value="INFO" default="true" name="INFO"/> + <c:option value="INFO" name="INFO"/> <c:option value="VERBOSE" name="VERBOSE"/> <c:option value="DEBUG" name="DEBUG"/> <c:option value="DEBUG1" name="DEBUG1"/> <c:option value="DEBUG2" name="DEBUG2"/> <c:option value="DEBUG3" name="DEBUG3"/> - </c:property-options> </c:simple-property>
- <c:simple-property name="PermitRootLogin" required="false" description=" + <c:simple-property name="PermitRootLogin" required="false" default="yes" + description=" Specifies whether root can log in using ssh(1). The argument must be ``yes'', ``without-password'', ``forced-commands-only'', or ``no''. The default is ``yes''. @@ -116,11 +118,10 @@
If this option is set to ``no'', root is not allowed to log in."> <c:property-options> - <c:option value="yes" name="Allow Login" default="true"/> + <c:option value="yes" name="Allow Login"/> <c:option value="no" name="Deny Login"/> <c:option value="without-password" name="Login without password"/> <c:option value="forced-commands-only" name="Allow commands only"/> - </c:property-options> </c:simple-property>
diff --git a/modules/plugins/tomcat/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/tomcat/src/main/resources/META-INF/rhq-plugin.xml index 4ba4d91..5d511cc 100644 --- a/modules/plugins/tomcat/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/tomcat/src/main/resources/META-INF/rhq-plugin.xml @@ -69,8 +69,7 @@ name="RPM System V init script" /> <c:option value="SCRIPT" - name="shutdown script" - default="true" /> + name="shutdown script" /> </c:property-options> </c:simple-property>
diff --git a/modules/plugins/twitter/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/twitter/src/main/resources/META-INF/rhq-plugin.xml index fc11bab..a066afc 100644 --- a/modules/plugins/twitter/src/main/resources/META-INF/rhq-plugin.xml +++ b/modules/plugins/twitter/src/main/resources/META-INF/rhq-plugin.xml @@ -1,4 +1,5 @@ <?xml version="1.0"?> + <plugin name="Twitter" displayName="Twitter Plugin" package="org.rhq.plugins.twitter" @@ -7,7 +8,6 @@ description="Monitor various timelines on Twitter" xmlns:c="urn:xmlns:rhq-configuration">
- <server name="Twitter" discovery="TwitterDiscovery" @@ -68,7 +68,7 @@ <plugin-configuration> <c:simple-property name="kind" default="user"> <c:property-options allowCustomValue="false"> - <c:option value="user" name="User timeline" default="true"/> + <c:option value="user" name="User timeline"/> <c:option value="search" name="Keyword search"/> </c:property-options> </c:simple-property> @@ -86,5 +86,4 @@
</server>
- </plugin>
commit f60319dfe12918ff42bcaada1d0f0fecbb3a346a Author: Ian Springer ian.springer@redhat.com Date: Wed Oct 6 18:31:29 2010 -0400
start of the group config editor component
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 ed165ea..d47f8e1 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 @@ -73,6 +73,7 @@ import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.form.validator.CustomValidator; import com.smartgwt.client.widgets.form.validator.FloatRangeValidator; import com.smartgwt.client.widgets.form.validator.IntegerRangeValidator; +import com.smartgwt.client.widgets.form.validator.LengthRangeValidator; import com.smartgwt.client.widgets.form.validator.RegExpValidator; import com.smartgwt.client.widgets.form.validator.Validator; import com.smartgwt.client.widgets.grid.ListGrid; @@ -147,6 +148,11 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; * @author Greg Hinkle * @author Ian Springer */ +// +// Note: There was a failed attempt at an editor composed with ListGrid components instead of DynamicForm components, +// but there were problems with having different editors active for different rows in the table at the same time. +// Smart says they're working on enhancing this area, but the DynamicForm might be a better option anyway. (ghinkle) +// @SuppressWarnings({"UnnecessarySemicolon"}) public class ConfigurationEditor extends LocatableVLayout { private static final String RHQ_PROPERTY_ATTRIBUTE_NAME = "rhq:property"; @@ -732,7 +738,7 @@ public class ConfigurationEditor extends LocatableVLayout { VLayout canvas = new VLayout(); canvas.addMember(propertyGrid);
- if (!isReadOnly(propertyDefinitionMap)) { + if (!isReadOnly(propertyDefinitionMap, propertyMap)) { // Map is not read-only - add footer with New and Delete buttons to allow user to add or remove members. ToolStrip footer = new ToolStrip(); footer.setPadding(5); @@ -1034,7 +1040,7 @@ public class ConfigurationEditor extends LocatableVLayout { membersItem.setValueMap(memberValueToIndexMap); listGrid.setItems(membersItem);
- if (!isReadOnly(propertyDefinitionList)) { + if (!isReadOnly(propertyDefinitionList, propertyList)) { // List is not read-only - add footer with New and Delete buttons to allow user to add or remove members. ToolStrip footer = new ToolStrip(); footer.setPadding(5); @@ -1199,8 +1205,8 @@ public class ConfigurationEditor extends LocatableVLayout { return memberValueToIndexMap; }
- private FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, - final PropertySimple propertySimple) { + protected FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, + final PropertySimple propertySimple) { Log.debug("Building simple field for " + propertySimple + "...");
FormItem valueItem = null; @@ -1267,7 +1273,8 @@ public class ConfigurationEditor extends LocatableVLayout { List<Validator> validators = buildValidators(propertyDefinitionSimple, propertySimple); valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
- valueItem.setDisabled(isReadOnly(propertyDefinitionSimple) || isUnset(propertyDefinitionSimple, propertySimple)); + valueItem.setDisabled(isReadOnly(propertyDefinitionSimple, propertySimple) + || isUnset(propertyDefinitionSimple, propertySimple)); /* Click handlers seem to be turned off for disabled fields... need an alternative valueItem.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { @@ -1301,14 +1308,14 @@ public class ConfigurationEditor extends LocatableVLayout { return currentProperty; }
- private FormItem buildUnsetItem(PropertyDefinitionSimple propertyDefinition, final PropertySimple property, + protected FormItem buildUnsetItem(PropertyDefinitionSimple propertyDefinition, final PropertySimple property, final FormItem valueItem) { FormItem item; if (!propertyDefinition.isRequired()) { CheckboxItem unsetItem = new CheckboxItem(); boolean unset = isUnset(propertyDefinition, property); unsetItem.setValue(unset); - unsetItem.setDisabled(isReadOnly(propertyDefinition)); + unsetItem.setDisabled(isReadOnly(propertyDefinition, property)); unsetItem.setShowLabel(false); unsetItem.setShowTitle(false); unsetItem.setLabelAsTitle(false); @@ -1339,15 +1346,38 @@ public class ConfigurationEditor extends LocatableVLayout { (propertySimple == null || propertySimple.getStringValue() == null)); }
- private boolean isReadOnly(PropertyDefinition propertyDefinition) { - return propertyDefinition.isReadOnly() || this.readOnly; + private boolean isReadOnly(PropertyDefinition propertyDefinition, Property property) { + boolean isInvalidRequiredProperty = false; + if (property instanceof PropertySimple) { + PropertySimple propertySimple = (PropertySimple)property; + String errorMessage = propertySimple.getErrorMessage(); + if ((null == propertySimple.getStringValue()) || "".equals(propertySimple.getStringValue()) + || ((null != errorMessage) && (!"".equals(errorMessage.trim())))) { + // Required properties with no value, or an invalid value (assumed if we see an error message) should + // never be set to read-only, otherwise the user will have no way to give the property a new value and + // thereby get things to a valid state. + isInvalidRequiredProperty = true; + } + } + return !isInvalidRequiredProperty && (propertyDefinition.isReadOnly() || this.readOnly); }
private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, Property property) { List<Validator> validators = new ArrayList<Validator>(); - if (propertyDefinition.getConstraints() != null) { - Set<Constraint> constraints = propertyDefinition.getConstraints();
+ switch (propertyDefinition.getType()) { + case STRING: + case LONG_STRING: + case FILE: + case DIRECTORY: + LengthRangeValidator validator = new LengthRangeValidator(); + validator.setMax(PropertySimple.MAX_VALUE_LENGTH); + validators.add(validator); + break; + } + + Set<Constraint> constraints = propertyDefinition.getConstraints(); + if (constraints != null) { for (Constraint constraint : constraints) { if (constraint instanceof IntegerRangeConstraint) { IntegerRangeConstraint integerConstraint = ((IntegerRangeConstraint) constraint); @@ -1376,11 +1406,13 @@ public class ConfigurationEditor extends LocatableVLayout { } } } + if (property.getErrorMessage() != null) { this.invalidPropertyNames.add(property.getName()); PluginReportedErrorValidator validator = new PluginReportedErrorValidator(property); validators.add(validator); } + return validators; }
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 new file mode 100644 index 0000000..a7150e1 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/GroupConfigurationEditor.java @@ -0,0 +1,201 @@ +/* + * RHQ Management Platform + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +package org.rhq.enterprise.gui.coregui.client.components.configuration; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.form.events.ItemChangedEvent; +import com.smartgwt.client.widgets.form.events.ItemChangedHandler; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; +import com.smartgwt.client.widgets.layout.HLayout; + +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.PropertyDefinitionSimple; +import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +/** + * A SmartGWT widget for editing a group of RHQ {@link Configuration}s that conform to the same + * {@link ConfigurationDefinition}. + * + * @author Ian Springer + */ +public class GroupConfigurationEditor extends ConfigurationEditor { + private Map<String, Configuration> memberConfigurations; + + public GroupConfigurationEditor(String locatorId, ConfigurationDefinition configurationDefinition, + Configuration aggregateConfiguration, + Map<String, Configuration> memberConfigurations) { + super(locatorId, configurationDefinition, aggregateConfiguration); + this.memberConfigurations = memberConfigurations; + } + + private void displayMemberValuesEditor(String locatorId, PropertyDefinitionSimple propertyDefinitionSimple, + final FormItem aggregateValueItem, + final PropertySimple aggregatePropertySimple, Integer index) { + LocatableVLayout layout = new LocatableVLayout(locatorId); + layout.setHeight100(); + + // TODO: Add 'Set All Values To' and 'Unset All' controls in a separate DynamicForm. + + final DynamicForm form = new DynamicForm(); + form.setHeight100(); + form.setColWidths("55%", "5%", "40%"); + layout.addMember(form); + + // Add header row. + List<FormItem> items = new ArrayList<FormItem>(); + StaticTextItem memberHeader = new StaticTextItem("memberHeader", "Member"); + items.add(memberHeader); + StaticTextItem unsetHeader = new StaticTextItem("unsetHeader", "Unset"); + items.add(unsetHeader); + StaticTextItem valueHeader = new StaticTextItem("valueHeader", "Value"); + valueHeader.setEndRow(true); + items.add(valueHeader); + + // Add data rows. + final Map<String, PropertySimple> memberProperties = new HashMap<String, PropertySimple>(this.memberConfigurations.size()); + final List<FormItem> valueItems = new ArrayList<FormItem>(this.memberConfigurations.size()); + for (String memberName : this.memberConfigurations.keySet()) { + StaticTextItem memberItem = new StaticTextItem("member", memberName); + items.add(memberItem); + Configuration memberConfiguration = this.memberConfigurations.get(memberName); + PropertySimple memberPropertySimple = getPropertySimple(memberConfiguration, propertyDefinitionSimple, index); + memberProperties.put(memberName, memberPropertySimple); + FormItem valueItem = buildSimpleField(propertyDefinitionSimple, memberPropertySimple); + valueItem.setAttribute("rhq:property", memberPropertySimple); + valueItems.add(valueItem); + FormItem unsetItem = buildUnsetItem(propertyDefinitionSimple, memberPropertySimple, valueItem); + items.add(unsetItem); + items.add(valueItem); + valueItem.setEndRow(true); + } + form.setItems(items.toArray(new FormItem[items.size()])); + + final Window popup = new Window(); + popup.setTitle("Member Values for Property '" + propertyDefinitionSimple.getName()); + popup.setWidth(800); + popup.setHeight(600); + popup.setIsModal(true); + popup.setShowModalMask(true); + popup.setShowCloseButton(false); + popup.centerInPage(); + + final IButton okButton = new IButton("OK"); + okButton.disable(); + okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + boolean valuesHomogeneous = true; + String firstValue = (String)valueItems.get(0).getValue(); + for (FormItem valueItem : valueItems) { + String value = (String)valueItem.getValue(); + if ((value != null && !value.equals(firstValue)) || firstValue != null) { + valuesHomogeneous = false; + } + PropertySimple memberPropertySimple = + (PropertySimple)valueItem.getAttributeAsObject("rhq:property"); + memberPropertySimple.setStringValue(value); + memberPropertySimple.setErrorMessage(null); + } + if (valuesHomogeneous) { + // Values are all the same, so update the value of the aggregate property and set its override flag to true. + aggregateValueItem.setValue(firstValue); + // TODO: Will this cause a value changed event to fire for the aggregate form item? + aggregatePropertySimple.setStringValue(firstValue); + aggregatePropertySimple.setErrorMessage(null); + aggregatePropertySimple.setOverride(true); + } + popup.destroy(); + } + }); + + // Only enable the OK button if all properties are valid. + form.addItemChangedHandler(new ItemChangedHandler() { + public void onItemChanged(ItemChangedEvent itemChangedEvent) { + okButton.setDisabled(!form.validate()); + } + }); + + final IButton cancelButton = new IButton("Cancel"); + cancelButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + popup.destroy(); + } + }); + + // TODO: Anchor the button bar at the bottom of the modal window, so it's always visible. + HLayout buttons = new HLayout(); + buttons.setAlign(Alignment.CENTER); + buttons.setMembersMargin(10); + buttons.setMembers(okButton, cancelButton); + layout.addMember(buttons); + + popup.addItem(layout); + + popup.show(); + } + + private PropertySimple getPropertySimple(Configuration configuration, + PropertyDefinitionSimple propertyDefinitionSimple, Integer index) { + LinkedList<PropertyDefinition> propertyDefinitionHierarchy = new LinkedList<PropertyDefinition>(); + PropertyDefinition currentPropertyDefinition = propertyDefinitionSimple; + do { + propertyDefinitionHierarchy.addFirst(currentPropertyDefinition); + if (currentPropertyDefinition.getParentPropertyMapDefinition() != null) { + currentPropertyDefinition = currentPropertyDefinition.getParentPropertyMapDefinition(); + } else if (currentPropertyDefinition.getParentPropertyListDefinition() != null) { + currentPropertyDefinition = currentPropertyDefinition.getParentPropertyListDefinition(); + } else if (currentPropertyDefinition.getConfigurationDefinition() == null) { + throw new IllegalStateException(currentPropertyDefinition + " has no parent."); + } + } + while (currentPropertyDefinition.getConfigurationDefinition() == null); + + Property property = configuration.get(propertyDefinitionHierarchy.get(0).getName()); + for (int i = 1, propertyDefinitionHierarchySize = propertyDefinitionHierarchy.size(); + i < propertyDefinitionHierarchySize; i++) { + PropertyDefinition propertyDefinition = propertyDefinitionHierarchy.get(i); + if (property instanceof PropertyMap) { + PropertyMap propertyMap = (PropertyMap)property; + property = propertyMap.get(propertyDefinition.getName()); + } else if (property instanceof PropertyList) { + PropertyList propertyList = (PropertyList)property; + property = propertyList.getList().get(index); + } + } + + return (PropertySimple)property; + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ListGridConfigurationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ListGridConfigurationEditor.java deleted file mode 100644 index 7136199..0000000 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ListGridConfigurationEditor.java +++ /dev/null @@ -1,255 +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.components.configuration; - -import org.rhq.core.domain.configuration.Configuration; -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.PropertyGroupDefinition; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.gwt.ConfigurationGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; - -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.types.Autofit; -import com.smartgwt.client.types.ListGridFieldType; -import com.smartgwt.client.types.Overflow; -import com.smartgwt.client.types.SelectionStyle; -import com.smartgwt.client.types.VisibilityMode; -import com.smartgwt.client.widgets.Canvas; -import com.smartgwt.client.widgets.Label; -import com.smartgwt.client.widgets.WidgetCanvas; -import com.smartgwt.client.widgets.form.fields.CanvasItem; -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.SectionStack; -import com.smartgwt.client.widgets.layout.SectionStackSection; -import com.smartgwt.client.widgets.layout.VLayout; - -import java.util.List; - -/** - * Note: This was a failed attempt at an editor composed with ListGrid components instead of DynamicForm components. - * I had problems with having different editors active for different rows in the table at the same time. Smart says - * they're working on enhancing this area... but the DynamicForm might be a better option anyway. - * @author Greg Hinkle - */ -public class ListGridConfigurationEditor extends VLayout { - - private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService(); - - private ConfigurationDefinition definition; - private Configuration configuration; - - public ListGridConfigurationEditor() { - - - setOverflow(Overflow.AUTO); - - - configurationService.getResourceConfiguration(10005, new AsyncCallback<Configuration>() { - public void onFailure(Throwable caught) { - // TODO: Implement this method. - } - - public void onSuccess(Configuration result) { - configuration = result; - com.allen_sauer.gwt.log.client.Log.info("Got config"); - reload(); - } - }); - - configurationService.getResourceConfigurationDefinition(10060, new AsyncCallback<ConfigurationDefinition>() { - public void onFailure(Throwable caught) { - // TODO: Implement this method. - } - - public void onSuccess(ConfigurationDefinition result) { - definition = result; - com.allen_sauer.gwt.log.client.Log.info("Got def"); - reload(); - } - - ; - }); - } - - - public void reload() { - if (definition == null || configuration == null) { - return; - } - - List<PropertyGroupDefinition> definitions = definition.getGroupDefinitions(); - - - final SectionStack sectionStack = new SectionStack(); - sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); - sectionStack.setWidth100(); - sectionStack.setOverflow(Overflow.VISIBLE); - - for (PropertyGroupDefinition definition : definitions) { - com.allen_sauer.gwt.log.client.Log.info("building: " + definition.getDisplayName()); - sectionStack.addSection(buildGroupSection(definition)); - } - - addMember(sectionStack); - - this.redraw(); - } - - - public SectionStackSection buildGroupSection(PropertyGroupDefinition group) { - SectionStackSection section = new SectionStackSection(group.getDisplayName() + "<div style='text-align: right; font-size: -2'>" + group.getDescription() + "</div>"); - section.setExpanded(true); - - - ListGrid grid = new ListGrid(); - grid.setAlternateRecordStyles(true); - grid.setSelectionType(SelectionStyle.NONE); - grid.setEditByCell(false); - - grid.setShowHover(false); - grid.setShowAllRecords(true); - grid.setShowAllRecords(true); - grid.setWrapCells(true); - grid.setOverflow(Overflow.VISIBLE); - grid.setBodyOverflow(Overflow.VISIBLE); - grid.setCanSort(false); - - grid.setFixedRecordHeights(false); - grid.setAutoFitMaxHeight(50); - grid.setAutoFitData(Autofit.VERTICAL); - - grid.setAlwaysShowEditors(true); - - - ListGridField nameField = new ListGridField("displayName", "Name", 180); - nameField.setCanEdit(false); - //nameField - - ListGridField unsetField = new ListGridField("unset", "unset", 25); - unsetField.setType(ListGridFieldType.BOOLEAN); - unsetField.setCanEdit(true); - - ListGridField valueField = new ListGridField("value", "Value", 160); - valueField.setCanEdit(true); -// valueField.setEditorType(new TextItem()); - valueField.setEditorType(new ConfigEditor()); - - - final ConfigEditor ce = new ConfigEditor(); - valueField.setCellFormatter(new CellFormatter() { - public String format(Object value, ListGridRecord record, int rowNum, int colNum) { - - - return ce.tc.getInnerHTML(); -// "<input type='radio' name='foo' checked='checked'/> alpha<br/>" + -// "<input type='radio' name='foo' /> beta<br/>" + -// "<input type='radio' name='foo' /> delta<br/>"; - - } - }); - ListGridField descriptionField = new ListGridField("description", "Description"); - descriptionField.setCanEdit(false); - grid.setFields(nameField, unsetField, valueField, descriptionField); - - - for (PropertyDefinition property : definition.getPropertiesInGroup(group.getName())) { - grid.addData(new PropertyRecord(property)); - } - - section.addItem(grid); - return section; - } - - - public class ConfigurationListGrid extends ListGrid { - - public ConfigurationListGrid() { - super(); // TODO: Implement this method. - - - } - - - // Crap, they didn't implement the override for getEditorType yet - - } - - - public class PropertyRecord extends ListGridRecord { - - PropertyDefinition propertyDefinition; - - public PropertyRecord(PropertyDefinition definition) { - this.propertyDefinition = definition; - setAttribute("name", definition.getName()); - setAttribute("displayName", definition.getDisplayName()); - - setAttribute("required", definition.isRequired()); - setAttribute("readOnly", definition.isReadOnly()); - - PropertySimple property = configuration.getSimple(definition.getName()); - - setAttribute("unset", property.getStringValue() == null); - setAttribute("value", property.getStringValue()); - - setAttribute("description", definition.getDescription()); - - } - } - - public class ConfigEditor extends CanvasItem { - - int x = 1; - TestCanvas tc = new TestCanvas(); - - public ConfigEditor() { - super(); - - setCanvas(new WidgetCanvas(new Label("testing"))); - } - - @Override - public Canvas getCanvas() { - - tc.val = "" + x++; - - return tc; - } - - - } - - public class TestCanvas extends Canvas { - - String val; - - - @Override - public String getInnerHTML() { - return val; - } - } - -} \ No newline at end of file
commit 5d3e86d97f8a49ab0a86d3a43b31c1f429602f7f Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Oct 7 10:02:51 2010 -0400
Fix a git merge problem
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index 7cb28a3..8096fcf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -38,8 +38,7 @@ 2. In hosted mode, the windows are not automatically closed, although you can easily close them manually in the usual way --> - <!-- - -- When enabled FireFox is hard to use due to excessive popup window generation + <!-- When enabled FireFox is hard to use due to excessive popup window generation
<set-property name="log_WindowLogger" value="ENABLED" /> -->
commit 59b91a699378df0cae55ea6575760e9f4ff6db2c Merge: 20c1c7a... 6d06818... Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Oct 7 09:32:46 2010 -0400
Merge branch 'master-jay'
commit 20c1c7a109ceebd892838e675ce807c169d70acf Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 18:03:28 2010 -0400
Initial Manual Add Work
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index d2c971a..ab4ae27 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@ -72,4 +72,4 @@ public interface ResourceGWTService extends RemoteService { List<ResourceError> findResourceErrors(int resourceId);
Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration); -} \ No newline at end of file +}
commit 214929db2b569587c45f8bb80c0484d61f38de32 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 15:06:46 2010 -0400
Disable the experimental browser window logging out of the box
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index 8096fcf..7cb28a3 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -38,7 +38,8 @@ 2. In hosted mode, the windows are not automatically closed, although you can easily close them manually in the usual way --> - <!-- When enabled FireFox is hard to use due to excessive popup window generation + <!-- + -- When enabled FireFox is hard to use due to excessive popup window generation
<set-property name="log_WindowLogger" value="ENABLED" /> -->
commit cc1e9af8efed88fa2a461031956e3baff2a5b2f3 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 28 12:35:44 2010 -0400
AutoGroup/ResourceTree work - Fix up breadcrumbs for AutoGroup selections and also fix up some path - issues that were happening when selecting AG resources.
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 2f8ac93..923b925 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 @@ -777,7 +777,6 @@ public class ResourceTreeView extends LocatableVLayout { String autoGroupIdString = currentViewId.getPath(); Integer autoGroupId = Integer.parseInt(autoGroupIdString); setSelectedAutoGroup(autoGroupId); - } else { String resourceIdString = currentViewId.getPath(); Integer resourceId = Integer.parseInt(resourceIdString);
commit b49eab1b564ded819319c3cbb90d0c7a16069742 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 09:57:45 2010 -0400
ResourceTree Authz work - support for locked nodes - support for autogroups for non-inventory managers. Now that AGs are backed by compat groups it's necessary for non-inv-managers to be able to create and access the private groups that they own. Private groups (aka subject-owned groups) are new, they are basically groups that are tagged with the creating subjectId. Those groups can be created (via a new slsb call) and fetched (via a new ResourceGroupCriteria filter) w/o inventory manager perms. - note: i had to move rhq_subject to auth-schema from authz-schema and slightly change the dbsetup order to make it ok for rhq_resource_group to reference rhq_subject. - schema spec bumped to 2.97 - added ResourceLineageComposite to combine Resource and locked/viewable info.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 473a257..861fe72 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -178,6 +178,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re return SerialUtility.prepare( resourceManager.getResourceLineageAndSiblings(getSessionSubject(), resourceId), "ResourceService.getResourceLineageAndSiblings"); + } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); }
commit 4f39c60546b521f109163ff1edc3ddc46b5fc397 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 28 12:35:44 2010 -0400
AutoGroup/ResourceTree work - Fix up breadcrumbs for AutoGroup selections and also fix up some path - issues that were happening when selecting AG resources.
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 923b925..2f8ac93 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 @@ -777,6 +777,7 @@ public class ResourceTreeView extends LocatableVLayout { String autoGroupIdString = currentViewId.getPath(); Integer autoGroupId = Integer.parseInt(autoGroupIdString); setSelectedAutoGroup(autoGroupId); + } else { String resourceIdString = currentViewId.getPath(); Integer resourceId = Integer.parseInt(resourceIdString);
commit 6d06818fbee4c424aa539baaed36634aa513c785 Merge: e7acef3... b1efc02... Author: Jay Shaughnessy jshaughn@redhat.com Date: Thu Oct 7 08:59:31 2010 -0400
Unfortunately ended up mixing a merge resolution with feature work: -- Fix ResourceTree rendering for direct nav to "deep" nodes (like JmsXA). There were a few issues here. So far there have been some changes to ensure proper ordering of tree nodes for parent-child relationships, and more protection against node duplication. This should fix the rendering but we have some other issues resulting in the attemot to add duplicate resource nodes, and also, I think, building the tree twice prior to rendering. I'll look into these issues now but at least the tree should render correctly. -- Merge branch 'master' into master-jay
Conflicts: modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
diff --cc .classpath index 0b4abf3,1a1236c..7d1cd22 --- a/.classpath +++ b/.classpath @@@ -252,10 -252,9 +252,9 @@@ <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-user/2.0.3/gwt-user-2.0.3.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/google/gwt/gwt-dev/2.0.3/gwt-dev-2.0.3.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/smartgwt/smartgwt/2.2/smartgwt-2.2.jar"/> -- <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/gwt-log/gwt-log/3.0.3/gwt-log-3.0.3.jar"/> -- <classpathentry exported="true" kind="var" path="M2_REPO/ca/nanometrics/gflot/1.0.0/gflot-1.0.0.jar"/> ++ <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/gwt-log/gwt-log/3.0.3/gwt-log-3.0.3.jar"/> ++ <classpathentry exported="true" kind="var" path="M2_REPO/ca/nanometrics/gflot/1.0.0/gflot-1.0.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-jxpath/commons-jxpath/1.3/commons-jxpath-1.3.jar"/> - <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/gwt-log/gwt-log/3.0.3/gwt-log-3.0.3.jar"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath> diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java index d577c4d,d577c4d..17012f8 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java @@@ -20,9 -20,9 +20,8 @@@ package org.rhq.enterprise.gui.coregui.
import java.util.ArrayList; import java.util.EnumSet; --import java.util.HashMap; ++import java.util.HashSet; import java.util.List; --import java.util.Map; import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; @@@ -38,7 -38,7 +37,6 @@@ import com.smartgwt.client.widgets.tree
import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.Resource; --import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceSubCategory; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.util.PageList; @@@ -132,7 -132,7 +130,8 @@@ public class ResourceTreeDatasource ext return;
} else { -- com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading Resource [" + parentResourceId + "]..."); ++ com.allen_sauer.gwt.log.client.Log.info("ResourceTreeDatasource: Loading Resource [" + parentResourceId ++ + "]...");
criteria.addFilterParentResourceId(Integer.parseInt(parentResourceId)); } @@@ -176,85 -176,85 +175,196 @@@ * @return */ public static TreeNode[] buildNodes(List<Resource> resources, List<Resource> lockedData) { -- ResourceTreeNode[] nodes = new ResourceTreeNode[resources.size()]; -- for (int i = 0; i < resources.size(); i++) { -- Resource resource = resources.get(i); ++ List<ResourceTreeNode> resourceNodes = new ArrayList<ResourceTreeNode>(resources.size()); ++ for (Resource resource : resources) { ResourceTreeNode node = new ResourceTreeNode(resource, lockedData.contains(resource)); -- nodes[i] = node; ++ resourceNodes.add(node); }
-- return introduceTypeAndCategoryNodes(nodes); ++ List<TreeNode> result = introduceTypeAndCategoryNodes(resourceNodes); ++ com.allen_sauer.gwt.log.client.Log.debug("\nSTARTING FINAL TREE\n"); ++ for (TreeNode node : result) { ++ com.allen_sauer.gwt.log.client.Log.debug("Final: " + node); ++ } ++ com.allen_sauer.gwt.log.client.Log.debug("\nENDING FINAL TREE\n"); ++ return result.toArray(new TreeNode[result.size()]); }
-- private static TreeNode[] introduceTypeAndCategoryNodes(ResourceTreeNode[] resourceNodes) { -- List<TreeNode> updatedNodes = new ArrayList<TreeNode>(); -- // Maps category node IDs to the corresponding category nodes. -- Map<String, SubCategoryTreeNode> subcategoryNodes = new HashMap<String, SubCategoryTreeNode>(); -- // Maps autogroup/type node IDs to the corresponding autogroup/type nodes. -- Map<String, AutoGroupTreeNode> autogroupNodes = new HashMap<String, AutoGroupTreeNode>(); ++ /** ++ * @param resourceNodes ordered such that referenced parent nodes have lower indexes than the referencing child. ++ * @return a new List, properly ordered and including AG and Subcategory nodes. ++ */ ++ private static List<TreeNode> introduceTypeAndCategoryNodes(final List<ResourceTreeNode> resourceNodes) { ++ // The resulting list of nodes, including AG and SC nodes. The list is ordered to ensure all ++ // referenced parent nodes have lower indexes than the referencing child. ++ List<TreeNode> allNodes = new ArrayList<TreeNode>(resourceNodes.size()); ++ // Keep track of the node IDs added so far to ensure we don't add the same node more than once. Note ++ // that the list of resourceNodes passed in may have duplicates as the caller may not be able to ++ // ensure a clean set. ++ Set<String> allNodeIds = new HashSet<String>(resourceNodes.size() * 2);
for (ResourceTreeNode resourceNode : resourceNodes) { -- updatedNodes.add(resourceNode); ++ if (allNodeIds.contains(resourceNode.getID())) { ++ com.allen_sauer.gwt.log.client.Log.debug("skipping duplicate resourceNode: " + resourceNode); ++ continue; ++ }
Resource resource = resourceNode.getResource(); -- ResourceType type = resource.getResourceType(); -- if (type.getCategory() != ResourceCategory.PLATFORM) { -- String autogroupNodeId = AutoGroupTreeNode.idOf(resource); -- if (!autogroupNodes.containsKey(autogroupNodeId)) { -- Resource parentResource = resource.getParentResource(); -- ResourceSubCategory subcategory = type.getSubCategory(); -- if (subcategory != null) { -- com.allen_sauer.gwt.log.client.Log.debug("Processing " + subcategory + "..."); -- do { -- String subcategoryNodeId = SubCategoryTreeNode.idOf(subcategory, parentResource); -- if (!subcategoryNodes.containsKey(subcategoryNodeId)) { -- SubCategoryTreeNode subcategoryNode = new SubCategoryTreeNode(subcategory, -- parentResource); -- subcategoryNodes.put(subcategoryNode.getID(), subcategoryNode); -- com.allen_sauer.gwt.log.client.Log.debug("Adding " + subcategoryNode + " to tree..."); -- updatedNodes.add(subcategoryNode); -- } -- } while ((subcategory = subcategory.getParentSubCategory()) != null); -- }
-- if (!type.isSingleton()) { -- AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource); -- autogroupNodes.put(autogroupNodeId, autogroupNode); -- com.allen_sauer.gwt.log.client.Log.debug("Adding " + autogroupNode + " to tree..."); -- updatedNodes.add(autogroupNode); ++ if (resourceNode.isParentSubCategory()) { ++ // If the parent node is a subcategory node, make sure the subcategory node is in the ++ // tree prior to the resource node. Note that it could itself be a tree of subcategories. ++ addSubCategoryNodes(allNodes, allNodeIds, resource); ++ ++ } else if (resourceNode.isParentAutoGroup()) { ++ ++ // If the parent node is an autogroup node, make sure the autogroup node is in the ++ // tree prior to the resource node. ++ ++ if (!allNodeIds.contains(resourceNode.getParentID())) { ++ AutoGroupTreeNode autogroupNode = new AutoGroupTreeNode(resource); ++ ++ if (autogroupNode.isParentSubcategory()) { ++ // If the parent node of the autogroup node is a subcategory node, make sure the subcategory ++ // node is in the tree prior to the autogroup node. Note that it could itself be a ++ // tree of subcategories. ++ addSubCategoryNodes(allNodes, allNodeIds, resource); ++ } ++ allNodeIds.add(resourceNode.getParentID()); ++ com.allen_sauer.gwt.log.client.Log.debug("Adding " + autogroupNode); ++ allNodes.add(autogroupNode); } } ++ ++ com.allen_sauer.gwt.log.client.Log.debug("Adding " + resourceNode + " to tree..."); ++ allNodeIds.add(resourceNode.getID()); ++ allNodes.add(resourceNode); ++ } ++ ++ return allNodes; ++ } ++ ++ // convenience routine to avoid code duplication ++ private static void addSubCategoryNodes(List<TreeNode> allNodes, Set<String> allNodeIds, Resource resource) { ++ Resource parentResource = resource.getParentResource(); ++ ResourceType type = resource.getResourceType(); ++ ResourceSubCategory subCategory = type.getSubCategory(); ++ String subCategoryNodeId = null; ++ int insertAt = allNodes.size(); ++ ++ do { ++ subCategoryNodeId = SubCategoryTreeNode.idOf(subCategory, parentResource); ++ ++ if (!allNodeIds.contains(subCategoryNodeId)) { ++ SubCategoryTreeNode subCategoryNode = new SubCategoryTreeNode(subCategory, parentResource); ++ allNodeIds.add(subCategoryNodeId); ++ com.allen_sauer.gwt.log.client.Log.debug("Adding " + subCategoryNode); ++ allNodes.add(insertAt, subCategoryNode); ++ } ++ } while ((subCategory = subCategory.getParentSubCategory()) != null); ++ } ++ ++ public static class ResourceTreeNode extends EnhancedTreeNode { ++ private Resource resource; ++ private boolean isLocked; ++ private boolean parentAutoGroup = false; ++ private boolean parentSubCategory = false; ++ ++ /** ++ * The parentID will be set to the parent resource at construction. It can be changed ++ * later (prior to tree linkage) if the resource node should logically be set to an ++ * autogroup or subcategory parent. ++ * @param resource ++ * @param isLocked ++ */ ++ private ResourceTreeNode(Resource resource, boolean isLocked) { ++ this.resource = resource; ++ this.isLocked = isLocked; ++ ++ String id = idOf(resource); ++ setID(id); ++ ++ // a resource node can have any of three different parent node types; resource, subcategory or autogroup. ++ // this can be determined at construction time so set it properly now and assume the proper node ++ // structure will be in place later. ++ Resource parentResource = resource.getParentResource(); ++ String parentId = null; ++ ++ if (null != parentResource) { ++ // non-singletons will always be autogrouped ++ if (!resource.getResourceType().isSingleton()) { ++ parentId = AutoGroupTreeNode.idOf(resource); ++ this.parentAutoGroup = true; ++ ++ } else { ++ ResourceSubCategory subCategory = resource.getResourceType().getSubCategory(); ++ if (null != subCategory) { ++ parentId = SubCategoryTreeNode.idOf(subCategory, parentResource); ++ this.parentSubCategory = true; ++ } else ++ parentId = ResourceTreeNode.idOf(parentResource); ++ } ++ } ++ this.setParentID(parentId); ++ ++ String name = resource.getName(); ++ setName(name); ++ ++ setAttribute(Attributes.DESCRIPTION, resource.getDescription()); ++ ++ Set<ResourceType> childTypes = resource.getResourceType().getChildResourceTypes(); ++ setIsFolder((childTypes != null && !childTypes.isEmpty())); ++ } ++ ++ public Resource getResource() { ++ return this.resource; ++ } ++ ++ public boolean isLocked() { ++ return isLocked; ++ } ++ ++ public boolean isParentAutoGroup() { ++ return parentAutoGroup; ++ } ++ ++ public boolean isParentSubCategory() { ++ return parentSubCategory; ++ } ++ ++ public static String idOf(Resource resource) { ++ return idOf(resource.getId()); }
-- return updatedNodes.toArray(new TreeNode[updatedNodes.size()]); ++ public static String idOf(int resourceId) { ++ return String.valueOf(resourceId); ++ } }
/** -- * The folder node for a Resource subcategory. ++ * The folder node for a Resource subCategory. */ public static class SubCategoryTreeNode extends EnhancedTreeNode { ++ public SubCategoryTreeNode(ResourceSubCategory category, Resource parentResource) { String id = idOf(category, parentResource); setID(id); -- setAttribute(Attributes.ID, id);
ResourceSubCategory parentCategory = category.getParentSubCategory(); String parentId = (parentCategory != null) ? SubCategoryTreeNode.idOf(parentCategory, parentResource) : ResourceTreeNode.idOf(parentResource); setParentID(parentId); -- setAttribute(Attributes.PARENT_ID, parentId);
-- // Note, subcategory names are typically already plural, so there's no need to pluralize them. ++ // Note, subCategory names are typically already plural, so there's no need to pluralize them. String name = category.getDisplayName(); setName(name); -- setAttribute(Attributes.NAME, name);
setAttribute(Attributes.DESCRIPTION, category.getDescription()); }
public static String idOf(ResourceSubCategory category, Resource parentResource) { -- return "subcat" + category.getId() + "_" + parentResource.getId(); ++ return "subcat_" + category.getId() + "_" + parentResource.getId(); } }
@@@ -265,6 -265,6 +375,7 @@@
private Resource parentResource; private ResourceType resourceType; ++ private boolean parentSubcategory = false;
/** * @param resource requires resourceType field be set. requires parentResource field be set (null for no parent) @@@ -276,15 -276,15 +387,21 @@@ String id = idOf(resource); setID(id);
-- String parentId = parentIdOf(resource); ++ // parent node is either a subCategory node or a resource node ++ String parentId; ++ ResourceSubCategory subcategory = this.resourceType.getSubCategory(); ++ if (subcategory != null) { ++ parentId = SubCategoryTreeNode.idOf(subcategory, this.parentResource); ++ this.parentSubcategory = true; ++ } else { ++ parentId = ResourceTreeNode.idOf(this.parentResource); ++ } setParentID(parentId);
-- ResourceType type = resource.getResourceType(); -- String name = StringUtility.pluralize(type.getName()); ++ String name = StringUtility.pluralize(this.resourceType.getName()); setName(name); -- setAttribute(Attributes.NAME, name);
-- setAttribute(Attributes.DESCRIPTION, type.getDescription()); ++ setAttribute(Attributes.DESCRIPTION, this.resourceType.getDescription()); }
public Resource getParentResource() { @@@ -306,6 -306,6 +423,10 @@@ return this.getParentResource().getName() + " ( " + this.getResourceType().getName() + " )"; }
++ public boolean isParentSubcategory() { ++ return parentSubcategory; ++ } ++ /** * Given a Resource, generate a unique ID for the AGNode. * @@@ -328,63 -328,63 +449,6 @@@ public static String idOf(Resource parentResource, ResourceType resourceType) { return (parentResource != null) ? "autogroup_" + resourceType.getId() + "_" + parentResource.getId() : null; } -- -- // parent node is either a subcategory node or a resouce node -- public static String parentIdOf(Resource resource) { -- ResourceType type = resource.getResourceType(); -- ResourceSubCategory parentCategory = type.getSubCategory(); -- return (parentCategory != null) ? SubCategoryTreeNode.idOf(parentCategory, resource.getParentResource()) -- : ResourceTreeNode.idOf(resource.getParentResource()); -- } }
-- public static class ResourceTreeNode extends EnhancedTreeNode { -- private Resource resource; -- private boolean isLocked; -- -- private ResourceTreeNode(Resource resource, boolean isLocked) { -- this.resource = resource; -- this.isLocked = isLocked; -- -- String id = idOf(resource); -- setID(id); -- setAttribute(Attributes.ID, id); -- -- Resource parentResource = resource.getParentResource(); -- String parentId; -- if (parentResource != null) { -- parentId = resource.getResourceType().isSingleton() ? AutoGroupTreeNode.parentIdOf(resource) -- : AutoGroupTreeNode.idOf(resource); -- } else { -- parentId = null; -- } -- setParentID(parentId); -- setAttribute(Attributes.PARENT_ID, parentId); -- -- String name = resource.getName(); -- setName(name); -- setAttribute(Attributes.NAME, name); -- -- setAttribute(Attributes.DESCRIPTION, resource.getDescription()); -- -- Set<ResourceType> childTypes = resource.getResourceType().getChildResourceTypes(); -- setIsFolder((childTypes != null && !childTypes.isEmpty())); -- } -- -- public Resource getResource() { -- return this.resource; -- } -- -- public boolean isLocked() { -- return isLocked; -- } -- -- public static String idOf(Resource resource) { -- return idOf(resource.getId()); -- } -- -- public static String idOf(int resourceId) { -- return String.valueOf(resourceId); -- } -- } } diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java index 97a7d2f,97a7d2f..aefb031 --- 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 @@@ -104,7 -104,7 +104,7 @@@ public class ResourceTreeView extends L private List<ResourceSelectListener> selectListeners = new ArrayList<ResourceSelectListener>();
// Maps autogroup/type backing group ids to the corresponding autogroup/type nodes. -- Map<Integer, AutoGroupTreeNode> autoGroupNodeMap = new HashMap<Integer, AutoGroupTreeNode>(); ++ private Map<Integer, AutoGroupTreeNode> autoGroupNodeMap = new HashMap<Integer, AutoGroupTreeNode>();
public ResourceTreeView(String locatorId) { super(locatorId);
commit fcc436196afd138e15c4813194bbbc2cc1fee6d3 Author: Lukas Krejci lkrejci@redhat.com Date: Thu Oct 7 11:41:01 2010 +0200
Fixing the pom so that there's no need to specify the -Dgwt.module=org.rhq.enterprise.gui.coregui.CoreGUI when running mvn gwt:debug. Note that this only works with maven 2.2.0 and later.
diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index c24aa4f..2b61393 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -264,12 +264,23 @@
<executions> <execution> + <id>gwt-goals</id> <goals> <goal>compile</goal> <goal>generateAsync</goal> <goal>i18n</goal> </goals> </execution> + <execution> + <!-- This id is what does the trick, don't change it. For this to work maven 2.2.0 and later is needed. --> + <id>default-cli</id> + <goals> + <goal>debug</goal> + </goals> + <configuration> + <module>org.rhq.enterprise.gui.coregui.CoreGUI</module> + </configuration> + </execution> </executions> </plugin>
commit 83f95657d84271fcf717cb2b9109b4ed0136a9cb Author: Ian Springer ian.springer@redhat.com Date: Wed Oct 6 13:08:59 2010 -0400
fix issue where URL history was not getting updated when switching between group tabs
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 33b22e9..74c5ca3 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 @@ -122,12 +122,10 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo }
public void onTabSelected(TwoLevelTabSelectedEvent tabSelectedEvent) { - //CoreGUI.printWidgetTree(); - if (getSelectedItemId() == null) { - // History.fireCurrentHistoryState(); + CoreGUI.goToView(History.getToken()); } else { - // Switch tabs directly, rather than letting the history framework do it, to avoid redrawing the outer views. + // selectSubTabByTitle(tabSelectedEvent.getId(), tabSelectedEvent.getSubTabId()); String tabPath = "/" + tabSelectedEvent.getId() + "/" + tabSelectedEvent.getSubTabId(); String path = this.baseViewPath + "/" + getSelectedItemId() + tabPath; @@ -136,9 +134,10 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo // 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.newItem(path, true); + CoreGUI.goToView(path); } } + // TODO?: Switch tabs directly, rather than letting the history framework do it, to avoid redrawing the outer views. }
public void renderView(final ViewPath viewPath) { 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 9e2442b..481354b 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 @@ -398,7 +398,8 @@ public class ResourceGroupTreeView extends LocatableVLayout implements Bookmarka public void renderView(ViewPath viewPath) { this.currentViewId = viewPath.getCurrent(); if (this.currentViewId != null) { - int groupId = Integer.parseInt(this.currentViewId.getPath()); + String groupIdString = this.currentViewId.getPath(); + int groupId = Integer.parseInt(groupIdString); setSelectedGroup(groupId); } } 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 97a7d2f..923b925 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 @@ -774,10 +774,12 @@ public class ResourceTreeView extends LocatableVLayout { if ("AutoGroup".equals(currentViewIdPath)) { // Move the currentViewId to the ID portion to play better with other code currentViewId = viewPath.getNext(); - Integer autoGroupId = Integer.parseInt(currentViewId.getPath()); + String autoGroupIdString = currentViewId.getPath(); + Integer autoGroupId = Integer.parseInt(autoGroupIdString); setSelectedAutoGroup(autoGroupId); } else { - Integer resourceId = Integer.parseInt(currentViewId.getPath()); + String resourceIdString = currentViewId.getPath(); + Integer resourceId = Integer.parseInt(resourceIdString); setSelectedResource(resourceId); } }
commit 860fa0aafec9718235c7224da73583431a6fe045 Author: Ian Springer ian.springer@redhat.com Date: Wed Oct 6 12:42:43 2010 -0400
fix group Monitor > Schedules subtab so it aggregates the schedules, rather than showing each of the member schedules (https://bugzilla.redhat.com/show_bug.cgi?id=640562)
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementScheduleComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementScheduleComposite.java index a3416d3..235082e 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementScheduleComposite.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/measurement/composite/MeasurementScheduleComposite.java @@ -46,6 +46,10 @@ public class MeasurementScheduleComposite implements Serializable { private Boolean collectionEnabled; // null flagged as "SOME" private long collectionInterval; // 0 flagged as "DIFFERENT"
+ // No-arg constructor required by GWT. + public MeasurementScheduleComposite() { + } + public MeasurementScheduleComposite(MeasurementDefinition measurementDefinition) { this.measurementDefinition = measurementDefinition; this.collectionEnabled = measurementDefinition.isDefaultOn(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java index 9e7ddb4..f1661c8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/tree/BundleTreeDataSource.java @@ -29,7 +29,6 @@ import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSourceField; -import com.smartgwt.client.data.fields.DataSourceImageField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.tree.TreeNode; @@ -55,7 +54,6 @@ public class BundleTreeDataSource extends RPCDataSource {
private BundleGWTServiceAsync bundleService = GWTServiceLookup.getBundleService();
- public BundleTreeDataSource() { DataSourceField idDataField = new DataSourceTextField("id", "ID"); idDataField.setPrimaryKey(true); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java index 9297d96..c6c44d8 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/MeasurementDataGWTService.java @@ -24,6 +24,8 @@ import java.util.Set; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
+import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria; import org.rhq.core.domain.criteria.MeasurementDefinitionCriteria; import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; @@ -35,6 +37,7 @@ import org.rhq.core.domain.measurement.MeasurementSchedule; import org.rhq.core.domain.measurement.calltime.CallTimeDataComposite; import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowComposite; import org.rhq.core.domain.measurement.composite.MeasurementOOBComposite; +import org.rhq.core.domain.measurement.composite.MeasurementScheduleComposite; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList;
@@ -58,6 +61,8 @@ public interface MeasurementDataGWTService extends RemoteService {
PageList<MeasurementSchedule> findMeasurementSchedulesByCriteria(MeasurementScheduleCriteria criteria);
+ PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context); + PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, String parentNameFilter, PageControl pc);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleCompositeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleCompositeDataSource.java new file mode 100644 index 0000000..7782c87 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleCompositeDataSource.java @@ -0,0 +1,218 @@ +/* + * RHQ Management Platform + * Copyright (C) 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.inventory.common; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.DataSourceField; +import com.smartgwt.client.data.fields.DataSourceBooleanField; +import com.smartgwt.client.data.fields.DataSourceIntegerField; +import com.smartgwt.client.data.fields.DataSourceTextField; +import com.smartgwt.client.rpc.RPCResponse; +import com.smartgwt.client.widgets.grid.ListGrid; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.common.EntityContext; +import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.measurement.composite.MeasurementScheduleComposite; +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.MeasurementDataGWTServiceAsync; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * A server-side SmartGWT DataSource for reading and updating {@link MeasurementScheduleComposite}s. + * + * @author Ian Springer + */ +public abstract class AbstractMeasurementScheduleCompositeDataSource extends RPCDataSource<MeasurementScheduleComposite> { + private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService(); + + protected AbstractMeasurementScheduleCompositeDataSource() { + super(); + + setCanMultiSort(true); + + List<DataSourceField> fields = createFields(); + addFields(fields); + } + + protected List<DataSourceField> createFields() { + List<DataSourceField> fields = new ArrayList<DataSourceField>(); + + DataSourceIntegerField idField = new DataSourceIntegerField(MeasurementScheduleCriteria.SORT_FIELD_DEFINITION_ID, + "Id"); + idField.setPrimaryKey(true); + idField.setHidden(true); + fields.add(idField); + + DataSourceTextField nameField = new DataSourceTextField(MeasurementScheduleCriteria.SORT_FIELD_DISPLAY_NAME, + "Metric"); + fields.add(nameField); + + DataSourceTextField descriptionField = new DataSourceTextField(MeasurementScheduleCriteria.SORT_FIELD_DESCRIPTION, + "Description"); + fields.add(descriptionField); + + DataSourceTextField typeField = new DataSourceTextField(MeasurementScheduleCriteria.SORT_FIELD_DATA_TYPE, + "Type"); + fields.add(typeField); + + DataSourceBooleanField enabledField = new DataSourceBooleanField(MeasurementScheduleCriteria.SORT_FIELD_ENABLED, + "Enabled?"); + fields.add(enabledField); + + DataSourceIntegerField intervalField = new DataSourceIntegerField(MeasurementScheduleCriteria.SORT_FIELD_INTERVAL, + "Collection Interval"); + fields.add(intervalField); + + return fields; + } + + protected void executeFetch(final DSRequest request, final DSResponse response) { + final EntityContext entityContext = getEntityContext(request); + + this.measurementService.getMeasurementScheduleCompositesByContext(entityContext, new AsyncCallback<PageList<MeasurementScheduleComposite>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to fetch measurement schedules for context " + entityContext, + caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + + public void onSuccess(PageList<MeasurementScheduleComposite> result) { + response.setData(buildRecords(result)); + // For paging to work, we have to specify size of full result set. + response.setTotalRows(result.getTotalSize()); + processResponse(request.getRequestId(), response); + } + }); + } + + protected EntityContext getEntityContext(DSRequest request) { + EntityContext entityContext = null; + + Criteria requestCriteria = request.getCriteria(); + if (requestCriteria != null) { + Map values = requestCriteria.getValues(); + for (Object key : values.keySet()) { + String fieldName = (String) key; + if (fieldName.equals(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_ID)) { + Integer resourceId = (Integer) values.get(fieldName); + entityContext = EntityContext.forResource(resourceId); + } else if (fieldName.equals(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_GROUP_ID)) { + Integer groupId = (Integer) values.get(fieldName); + entityContext = EntityContext.forGroup(groupId); + } + // TODO: Add support for other fields we need to filter by (e.g. resourceTypeId for metric templates). + } + } + + if (entityContext == null) { + throw new IllegalStateException("No support criteria fields were found."); + } + + return entityContext; + } + + @Override + public MeasurementScheduleComposite copyValues(ListGridRecord from) { + return null; + } + + @Override + public ListGridRecord copyValues(MeasurementScheduleComposite from) { + ListGridRecord record = new ListGridRecord(); + + MeasurementDefinition measurementDefinition = from.getMeasurementDefinition(); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_DEFINITION_ID, measurementDefinition.getId()); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_DISPLAY_NAME, measurementDefinition.getDisplayName()); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_DESCRIPTION, measurementDefinition.getDescription()); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_DATA_TYPE, + measurementDefinition.getDataType().name().toLowerCase()); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_ENABLED, from.getCollectionEnabled()); + record.setAttribute(MeasurementScheduleCriteria.SORT_FIELD_INTERVAL, from.getCollectionInterval()); + + // TODO: resourceId and resourceGroupId (in subclasses) + + return record; + } + + public void enableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView) { + int[] ids = getMeasurementDefinitionIds(measurementScheduleListView); + List<String> displayNames = getMeasurementDefinitionDisplayNames(measurementScheduleListView); + enableSchedules(measurementScheduleListView, ids, displayNames); + measurementScheduleListView.refresh(); + } + + protected abstract void enableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, + int[] measurementDefinitionIds, List<String> measurementDefinitionDisplayNames); + + public void disableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView) { + int[] ids = getMeasurementDefinitionIds(measurementScheduleListView); + List<String> displayNames = getMeasurementDefinitionDisplayNames(measurementScheduleListView); + disableSchedules(measurementScheduleListView, ids, displayNames); + measurementScheduleListView.refresh(); + } + + protected abstract void disableSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, + int[] measurementDefinitionIds, List<String> measurementDefinitionDisplayNames); + + public void updateSchedules(AbstractMeasurementScheduleListView measurementScheduleListView, long interval) { + int[] ids = getMeasurementDefinitionIds(measurementScheduleListView); + List<String> displayNames = getMeasurementDefinitionDisplayNames(measurementScheduleListView); + updateSchedules(measurementScheduleListView, ids, displayNames, interval); + measurementScheduleListView.refresh(); + } + + private int[] getMeasurementDefinitionIds(AbstractMeasurementScheduleListView measurementScheduleListView) { + ListGrid listGrid = measurementScheduleListView.getListGrid(); + ListGridRecord[] records = listGrid.getSelection(); + + int[] measurementDefinitionIds = new int[records.length]; + for (int i = 0, selectionLength = records.length; i < selectionLength; i++) { + ListGridRecord record = records[i]; + Integer measurementDefinitionId = record.getAttributeAsInt(MeasurementScheduleCriteria.SORT_FIELD_DEFINITION_ID); + measurementDefinitionIds[i] = measurementDefinitionId; + } + return measurementDefinitionIds; + } + + private List<String> getMeasurementDefinitionDisplayNames(AbstractMeasurementScheduleListView measurementScheduleListView) { + ListGrid listGrid = measurementScheduleListView.getListGrid(); + ListGridRecord[] records = listGrid.getSelection(); + List<String> displayNames = new ArrayList<String>(records.length); + for (ListGridRecord record : records) { + String displayName = record.getAttributeAsString(MeasurementScheduleCriteria.SORT_FIELD_DISPLAY_NAME); + displayNames.add(displayName); + } + return displayNames; + } + + protected abstract void updateSchedules(final AbstractMeasurementScheduleListView measurementScheduleListView, + final int[] measurementDefinitionIds, List<String> measurementDefinitionDisplayNames, final long interval); +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleDataSource.java index e1181ab..fac403e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleDataSource.java @@ -29,6 +29,7 @@ import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridRecord; + import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; import org.rhq.core.domain.measurement.MeasurementSchedule; import org.rhq.core.domain.util.PageList; @@ -44,8 +45,13 @@ import java.util.Map; /** * A server-side SmartGWT DataSource for reading and updating {@link MeasurementSchedule}s. * + * @deprecated this class has been replaced by {@link AbstractMeasurementScheduleCompositeDataSource}, but + * I'm keeping it around in case we want to switch back to fetching schedules via criteria at + * some point. (ips, 10/06/10) + * * @author Ian Springer */ +@Deprecated public abstract class AbstractMeasurementScheduleDataSource extends RPCDataSource<MeasurementSchedule> { private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java index c00175a..64b93e5 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementScheduleListView.java @@ -42,14 +42,14 @@ public abstract class AbstractMeasurementScheduleListView extends Table { MeasurementScheduleCriteria.SORT_FIELD_DISPLAY_NAME, SortDirection.ASCENDING) };
public AbstractMeasurementScheduleListView(String locatorId, String title, - AbstractMeasurementScheduleDataSource dataSource, Criteria criteria, String[] excludedFieldNames) { + AbstractMeasurementScheduleCompositeDataSource dataSource, Criteria criteria, String[] excludedFieldNames) { super(locatorId, title, criteria, SORT_SPECIFIERS, excludedFieldNames); setDataSource(dataSource); }
@Override - public AbstractMeasurementScheduleDataSource getDataSource() { - return (AbstractMeasurementScheduleDataSource) super.getDataSource(); + public AbstractMeasurementScheduleCompositeDataSource getDataSource() { + return (AbstractMeasurementScheduleCompositeDataSource) super.getDataSource(); }
protected void configureTable() { @@ -62,9 +62,9 @@ public abstract class AbstractMeasurementScheduleListView extends Table { listGrid.getField(MeasurementScheduleCriteria.SORT_FIELD_DATA_TYPE).setWidth("10%"); ListGridField enabledField = listGrid.getField(MeasurementScheduleCriteria.SORT_FIELD_ENABLED); enabledField.setWidth("10%"); - enabledField.setCellFormatter(new BooleanCellFormatter()); + enabledField.setCellFormatter(new CollectionEnabledCellFormatter()); ListGridField intervalField = listGrid.getField(MeasurementScheduleCriteria.SORT_FIELD_INTERVAL); - intervalField.setCellFormatter(new MillisecondsCellFormatter()); + intervalField.setCellFormatter(new CollectionIntervalCellFormatter()); intervalField.setWidth("25%");
// Add action buttons and widgets. @@ -81,15 +81,23 @@ public abstract class AbstractMeasurementScheduleListView extends Table { addExtraWidget(new UpdateCollectionIntervalWidget(this.getLocatorId(), this)); }
- class MillisecondsCellFormatter implements CellFormatter { + protected class CollectionEnabledCellFormatter extends BooleanCellFormatter { + @Override + public String format(Object value, ListGridRecord record, int rowNum, int colNum) { + String result = super.format(value, record, rowNum, colNum); + return ("".equals(result)) ? "mixed" : result; + } + } + + protected class CollectionIntervalCellFormatter implements CellFormatter { public String format(Object value, ListGridRecord record, int rowNum, int colNum) { if (value == null) { - return ""; + return "mixed"; }
long milliseconds = ((Number) value).longValue(); if (milliseconds == 0) { - return "0"; + return "mixed"; }
StringBuilder result = new StringBuilder(); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java index 7bf4903..158448b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/schedules/SchedulesDataSource.java @@ -19,15 +19,20 @@ package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.monitoring.schedules;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; -import org.rhq.core.domain.measurement.MeasurementSchedule; +import org.rhq.core.domain.measurement.composite.MeasurementScheduleComposite; 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.MeasurementDataGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleDataSource; +import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleCompositeDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleListView; import org.rhq.enterprise.gui.coregui.client.util.message.Message;
@@ -38,7 +43,7 @@ import java.util.List; * * @author Ian Springer */ -public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource { +public class SchedulesDataSource extends AbstractMeasurementScheduleCompositeDataSource { private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService(); private int resourceGroupId;
@@ -57,7 +62,20 @@ public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource { }
@Override - public ListGridRecord copyValues(MeasurementSchedule from) { + protected void executeFetch(DSRequest request, DSResponse response) { + super.executeFetch(request, response); + + } + + @Override + protected EntityContext getEntityContext(DSRequest request) { + Criteria requestCriteria = request.getCriteria(); + Integer groupId = requestCriteria.getAttributeAsInt(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_GROUP_ID); + return EntityContext.forGroup(groupId); + } + + @Override + public ListGridRecord copyValues(MeasurementScheduleComposite from) { ListGridRecord record = super.copyValues(from); record.setAttribute(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_GROUP_ID, this.resourceGroupId); return record; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java index 35eb2d6..ddda348 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeDataSource.java @@ -54,7 +54,10 @@ import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTyp
/** * @author Greg Hinkle + * + * @deprecated {@link ResourceTreeDatasource} is used instead */ +@Deprecated public class NewResourceTreeDataSource extends DataSource {
int rootId; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java index da08c04..6fef545 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/NewResourceTreeView.java @@ -72,7 +72,10 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** * @author Greg Hinkle + * + * @deprecated {@link ResourceTreeView} is used instead */ +@Deprecated public class NewResourceTreeView extends LocatableVLayout { private Resource selectedResource; private Resource rootResource; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/schedules/SchedulesDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/schedules/SchedulesDataSource.java index 4dd6710..21fe764 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/schedules/SchedulesDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/schedules/SchedulesDataSource.java @@ -19,15 +19,19 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.schedules;
import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; -import org.rhq.core.domain.measurement.MeasurementSchedule; +import org.rhq.core.domain.measurement.composite.MeasurementScheduleComposite; 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.MeasurementDataGWTServiceAsync; -import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleDataSource; +import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleCompositeDataSource; import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementScheduleListView; import org.rhq.enterprise.gui.coregui.client.util.message.Message;
@@ -38,7 +42,7 @@ import java.util.List; * * @author Ian Springer */ -public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource { +public class SchedulesDataSource extends AbstractMeasurementScheduleCompositeDataSource { private MeasurementDataGWTServiceAsync measurementService = GWTServiceLookup.getMeasurementDataService(); private int resourceId;
@@ -57,7 +61,14 @@ public class SchedulesDataSource extends AbstractMeasurementScheduleDataSource { }
@Override - public ListGridRecord copyValues(MeasurementSchedule from) { + protected EntityContext getEntityContext(DSRequest request) { + Criteria requestCriteria = request.getCriteria(); + Integer resourceId = requestCriteria.getAttributeAsInt(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_ID); + return EntityContext.forResource(resourceId); + } + + @Override + public ListGridRecord copyValues(MeasurementScheduleComposite from) { ListGridRecord record = super.copyValues(from); record.setAttribute(MeasurementScheduleCriteria.FILTER_FIELD_RESOURCE_ID, this.resourceId); return record; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBDataSource.java index 0df9e99..6a31020 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/measurement/MeasurementOOBDataSource.java @@ -23,12 +23,10 @@ package org.rhq.enterprise.gui.coregui.client.report.measurement;
import java.util.Collection; -import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; -import com.smartgwt.client.data.fields.DataSourceLinkField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.grid.ListGridRecord; diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java index 1cc9170..8f5c9be 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/MeasurementDataGWTServiceImpl.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt; import java.util.List; import java.util.Set;
+import org.rhq.core.domain.common.EntityContext; import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria; import org.rhq.core.domain.criteria.MeasurementDefinitionCriteria; import org.rhq.core.domain.criteria.MeasurementScheduleCriteria; @@ -32,6 +33,7 @@ import org.rhq.core.domain.measurement.MeasurementSchedule; import org.rhq.core.domain.measurement.calltime.CallTimeDataComposite; import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowComposite; import org.rhq.core.domain.measurement.composite.MeasurementOOBComposite; +import org.rhq.core.domain.measurement.composite.MeasurementScheduleComposite; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.exception.ThrowableUtil; @@ -114,6 +116,16 @@ public class MeasurementDataGWTServiceImpl extends AbstractGWTServiceImpl implem } }
+ public PageList<MeasurementScheduleComposite> getMeasurementScheduleCompositesByContext(EntityContext context) { + try { + return SerialUtility.prepare(scheduleManager.getMeasurementScheduleCompositesByContext(getSessionSubject(), + context, PageControl.getUnlimitedInstance()), + "MeasurementDataService.getMeasurementScheduleCompositesByContext"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } + public PageList<MeasurementOOBComposite> getSchedulesWithOOBs(String metricNameFilter, String resourceNameFilter, String parentNameFilter, PageControl pc) { try {
commit 9929d400b0558c8cc65c30438db650b876e9bf72 Author: Ian Springer ian.springer@redhat.com Date: Tue Oct 5 19:36:41 2010 -0400
set order field on propdefs in test config in order to verify that the config editor renders the props according to the specified order
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 ded34ef..ed165ea 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 @@ -497,13 +497,6 @@ public class ConfigurationEditor extends LocatableVLayout {
private DynamicForm buildPropertiesForm(String locatorId, Collection<PropertyDefinition> propertyDefinitions, AbstractPropertyMap propertyMap, boolean firePropertyChangedEvents) { - List<PropertyDefinition> propertyDefinitionsList; - if (!(propertyDefinitions instanceof List)) { - propertyDefinitionsList = new ArrayList<PropertyDefinition>(propertyDefinitions); - } else { - propertyDefinitionsList = (List<PropertyDefinition>)propertyDefinitions; - } - Collections.sort(propertyDefinitionsList, new PropertyDefinitionComparator());
LocatableDynamicForm form = new LocatableDynamicForm(locatorId); form.setValuesManager(valuesManager); @@ -524,7 +517,7 @@ public class ConfigurationEditor extends LocatableVLayout { form.setColWidths(190, 28, 210);
List<FormItem> fields = new ArrayList<FormItem>(); - addItemsForPropertiesRecursively(locatorId, propertyDefinitionsList, propertyMap, fields, firePropertyChangedEvents); + addItemsForPropertiesRecursively(locatorId, propertyDefinitions, propertyMap, fields, firePropertyChangedEvents); form.setFields(fields.toArray(new FormItem[fields.size()]));
return form; @@ -534,7 +527,9 @@ public class ConfigurationEditor extends LocatableVLayout { AbstractPropertyMap propertyMap, List<FormItem> fields, boolean firePropertyChangedEvents) { boolean odd = true; - for (PropertyDefinition propertyDefinition : propertyDefinitions) { + List<PropertyDefinition> sortedPropertyDefinitions = new ArrayList<PropertyDefinition>(propertyDefinitions); + Collections.sort(sortedPropertyDefinitions, new PropertyDefinitionComparator()); + for (PropertyDefinition propertyDefinition : sortedPropertyDefinitions) { Property property = propertyMap.get(propertyDefinition.getName()); if (property == null) { if (propertyDefinition instanceof PropertyDefinitionSimple) { @@ -864,11 +859,11 @@ public class ConfigurationEditor extends LocatableVLayout { });
List<ListGridField> fieldsList = new ArrayList<ListGridField>(); - List<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(memberPropertyDefinitionMap + List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(memberPropertyDefinitionMap .getPropertyDefinitions().values()); - Collections.sort(definitions, new PropertyDefinitionComparator()); + Collections.sort(propertyDefinitions, new PropertyDefinitionComparator());
- for (PropertyDefinition subDef : definitions) { + for (PropertyDefinition subDef : propertyDefinitions) { if (subDef.isSummary()) { ListGridField field = new ListGridField(subDef.getName(), subDef.getDisplayName(), 90);
@@ -885,7 +880,7 @@ public class ConfigurationEditor extends LocatableVLayout {
if (fieldsList.isEmpty()) { // An extra "feature of the config system". If no fields are labeled summary, all are considered summary. - for (PropertyDefinition subDef : definitions) { + for (PropertyDefinition subDef : propertyDefinitions) { ListGridField field = new ListGridField(subDef.getName(), subDef.getDisplayName()); fieldsList.add(field); PropertyDefinitionSimple defSimple = (PropertyDefinitionSimple) subDef; @@ -948,7 +943,7 @@ public class ConfigurationEditor extends LocatableVLayout { summaryTable.setFields(fieldsList.toArray(new ListGridField[fieldsList.size()]));
// Now add rows containing the actual data (i.e. member property values). - ListGridRecord[] rows = buildSummaryRecords(propertyList, definitions); + ListGridRecord[] rows = buildSummaryRecords(propertyList, propertyDefinitions); summaryTable.setData(rows);
VLayout summaryTableHolder = new LocatableVLayout(locatorId); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java index 0ad4e0a..4bddff6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java @@ -48,36 +48,38 @@ public abstract class TestConfigurationFactory { Map<String, PropertyDefinition> propertyDefinitions = new HashMap<String, PropertyDefinition>(); configurationDefinition.setPropertyDefinitions(propertyDefinitions);
+ int orderIndex = 0; + PropertyDefinitionSimple simplePropDef;
simplePropDef = createStringPropDef1(); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = createStringPropDef2(); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("LongString", "a Long String simple prop", false, PropertySimpleType.LONG_STRING); simplePropDef.setDisplayName(simplePropDef.getName()); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("Password", "a Password simple prop", false, PropertySimpleType.PASSWORD); simplePropDef.setDisplayName(simplePropDef.getName()); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("Boolean", "a required Boolean simple prop", true, PropertySimpleType.BOOLEAN); simplePropDef.setDisplayName(simplePropDef.getName()); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++); simplePropDef.setRequired(true);
simplePropDef = createIntegerPropDef(); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("Float", "a Float simple prop", false, PropertySimpleType.FLOAT); simplePropDef.setDisplayName(simplePropDef.getName()); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("StringEnum1", "a String enum prop with <=5 items - should be rendered as radio buttons", false, @@ -88,7 +90,7 @@ public abstract class TestConfigurationFactory { propDefEnums.add(new PropertyDefinitionEnumeration("NJ", "NJ", true)); propDefEnums.add(new PropertyDefinitionEnumeration("PA", "PA")); simplePropDef.setEnumeratedValues(propDefEnums, false); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
simplePropDef = new PropertyDefinitionSimple("StringEnum2", "a String enum prop with >5 items - should be rendered as a popup menu", false, PropertySimpleType.STRING); @@ -101,31 +103,31 @@ public abstract class TestConfigurationFactory { propDefEnums.add(new PropertyDefinitionEnumeration("blue", "blue")); propDefEnums.add(new PropertyDefinitionEnumeration("purple", "purple")); simplePropDef.setEnumeratedValues(propDefEnums, false); - propertyDefinitions.put(simplePropDef.getName(), simplePropDef); + addPropertyDefinition(propertyDefinitions, simplePropDef, orderIndex++);
PropertyDefinitionMap mapPropDef = new PropertyDefinitionMap("MapOfSimples", "a map of simples", false); mapPropDef.put(createStringPropDef1()); mapPropDef.put(createStringPropDef2()); mapPropDef.put(createIntegerPropDef()); mapPropDef.setDisplayName(mapPropDef.getName()); - propertyDefinitions.put(mapPropDef.getName(), mapPropDef); + addPropertyDefinition(propertyDefinitions, mapPropDef, orderIndex++);
PropertyDefinitionMap openMapPropDef = new PropertyDefinitionMap("OpenMapOfSimples", "an open map of simples", false); openMapPropDef.setDisplayName(openMapPropDef.getName()); - propertyDefinitions.put(openMapPropDef.getName(), openMapPropDef); + addPropertyDefinition(propertyDefinitions, openMapPropDef, orderIndex++);
PropertyDefinitionMap readOnlyOpenMapPropDef = new PropertyDefinitionMap("ReadOnlyOpenMapOfSimples", "a read-only open map of simples", false); readOnlyOpenMapPropDef.setDisplayName(readOnlyOpenMapPropDef.getName()); readOnlyOpenMapPropDef.setReadOnly(true); - propertyDefinitions.put(readOnlyOpenMapPropDef.getName(), readOnlyOpenMapPropDef); + addPropertyDefinition(propertyDefinitions, readOnlyOpenMapPropDef, orderIndex++);
PropertyDefinitionList listOfSimplesPropDef = new PropertyDefinitionList("ListOfSimples", "a list of Integer simples", true, new PropertyDefinitionSimple("integer", "an integer", false, PropertySimpleType.INTEGER)); listOfSimplesPropDef.setDisplayName(listOfSimplesPropDef.getName()); - propertyDefinitions.put(listOfSimplesPropDef.getName(), listOfSimplesPropDef); + addPropertyDefinition(propertyDefinitions, listOfSimplesPropDef, orderIndex++);
PropertyDefinitionMap mapInListPropDef = new PropertyDefinitionMap("MapOfSimplesInList", "a map of simples in a list", false); @@ -137,7 +139,7 @@ public abstract class TestConfigurationFactory { PropertyDefinitionList listPropDef = new PropertyDefinitionList("ListOfMaps", "a list of maps", true, mapInListPropDef); listPropDef.setDisplayName(listPropDef.getName()); - propertyDefinitions.put(listPropDef.getName(), listPropDef); + addPropertyDefinition(propertyDefinitions, listPropDef, orderIndex++);
PropertyDefinitionMap mapInReadOnlyListPropDef = new PropertyDefinitionMap("MapOfSimplesInReadOnlyList", "a map of simples in a list", false); @@ -150,7 +152,7 @@ public abstract class TestConfigurationFactory { "a read-only list of maps", true, mapInReadOnlyListPropDef); readOnlyListPropDef.setDisplayName(readOnlyListPropDef.getName()); readOnlyListPropDef.setReadOnly(true); - propertyDefinitions.put(readOnlyListPropDef.getName(), readOnlyListPropDef); + addPropertyDefinition(propertyDefinitions, readOnlyListPropDef, orderIndex++);
PropertyGroupDefinition propertyGroupDefinition = new PropertyGroupDefinition("myGroup"); propertyGroupDefinition.setDisplayName(propertyGroupDefinition.getName()); @@ -160,14 +162,14 @@ public abstract class TestConfigurationFactory { PropertySimpleType.STRING); myString.setDisplayName(myString.getName()); myString.setSummary(true); - propertyDefinitions.put(myString.getName(), myString); + addPropertyDefinition(propertyDefinitions, myString, orderIndex++); myString.setPropertyGroupDefinition(propertyGroupDefinition);
PropertyDefinitionSimple myString2 = new PropertyDefinitionSimple("myString2", "my other little string", true, PropertySimpleType.STRING); myString2.setDisplayName(myString2.getName()); myString2.setSummary(true); - propertyDefinitions.put(myString2.getName(), myString2); + addPropertyDefinition(propertyDefinitions, myString2, orderIndex++); myString2.setPropertyGroupDefinition(propertyGroupDefinition);
PropertyGroupDefinition propertyGroupDefinition2 = new PropertyGroupDefinition("myGroup2"); @@ -178,7 +180,7 @@ public abstract class TestConfigurationFactory { PropertySimpleType.STRING); myString3.setDisplayName((myString3.getName())); myString3.setSummary(true); - propertyDefinitions.put(myString3.getName(), myString3); + addPropertyDefinition(propertyDefinitions, myString3, orderIndex++); myString3.setPropertyGroupDefinition(propertyGroupDefinition2);
PropertyDefinitionSimple enumExample = new PropertyDefinitionSimple("myEnum", @@ -189,16 +191,22 @@ public abstract class TestConfigurationFactory { myEnums.add(new PropertyDefinitionEnumeration("Camden", "Camden", true)); myEnums.add(new PropertyDefinitionEnumeration("Gloucester", "Gloucester")); enumExample.setEnumeratedValues(myEnums, false); - propertyDefinitions.put(enumExample.getName(), enumExample); + addPropertyDefinition(propertyDefinitions, enumExample, orderIndex++); enumExample.setPropertyGroupDefinition(propertyGroupDefinition2);
return configurationDefinition; }
+ private static void addPropertyDefinition(Map<String, PropertyDefinition> propertyDefinitions, + PropertyDefinition propDef, int orderIndex) { + propDef.setOrder(orderIndex); + propertyDefinitions.put(propDef.getName(), propDef); + } + public static Configuration createConfiguration() { Configuration configuration = new Configuration(); configuration.setNotes("a test config"); - configuration.setVersion(1); + configuration.setVersion(1);
configuration.put(new PropertySimple("String1", "blah")); configuration.put(new PropertySimple("String2",
commit 3fce691f6843509313f3dcb36da95a6c55c105b6 Author: Ian Springer ian.springer@redhat.com Date: Tue Oct 5 18:58:06 2010 -0400
add support for lists-of-simples to config editor and make other miscellaneous fixes and improvements to config editor
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 fc63830..ded34ef 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 @@ -25,6 +25,7 @@ import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -36,6 +37,7 @@ import com.smartgwt.client.data.Record; import com.smartgwt.client.types.Alignment; import com.smartgwt.client.types.Autofit; import com.smartgwt.client.types.ListGridFieldType; +import com.smartgwt.client.types.MultipleAppearance; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.TreeModelType; import com.smartgwt.client.types.VisibilityMode; @@ -140,7 +142,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** - * A SmartGWT widget for editing an RHQ {@link Configuration}, which conforms to a {@link ConfigurationDefinition}. + * A SmartGWT widget for editing an RHQ {@link Configuration} that conforms to a {@link ConfigurationDefinition}. * * @author Greg Hinkle * @author Ian Springer @@ -253,7 +255,7 @@ public class ConfigurationEditor extends LocatableVLayout {
public void onSuccess(Configuration result) { configuration = result; - com.allen_sauer.gwt.log.client.Log.info("Config retreived in: " + (System.currentTimeMillis() - start)); + Log.info("Config retreived in: " + (System.currentTimeMillis() - start)); reload(); } }); @@ -288,7 +290,7 @@ public class ConfigurationEditor extends LocatableVLayout { EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { - com.allen_sauer.gwt.log.client.Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); + Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); configurationDefinition = types.get(resourceTypeId).getPluginConfigurationDefinition(); if (configurationDefinition == null) { showError("Connection settings are not supported by this Resource."); @@ -487,14 +489,14 @@ public class ConfigurationEditor extends LocatableVLayout { List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(((group == null) ? configurationDefinition .getNonGroupedProperties() : configurationDefinition.getPropertiesInGroup(group.getName())));
- DynamicForm form = buildPropertiesForm(locatorId + "_Props", propertyDefinitions, configuration); + DynamicForm form = buildPropertiesForm(locatorId + "_Props", propertyDefinitions, configuration, true);
section.addItem(form); return section; }
private DynamicForm buildPropertiesForm(String locatorId, Collection<PropertyDefinition> propertyDefinitions, - AbstractPropertyMap propertyMap) { + AbstractPropertyMap propertyMap, boolean firePropertyChangedEvents) { List<PropertyDefinition> propertyDefinitionsList; if (!(propertyDefinitions instanceof List)) { propertyDefinitionsList = new ArrayList<PropertyDefinition>(propertyDefinitions); @@ -522,14 +524,15 @@ public class ConfigurationEditor extends LocatableVLayout { form.setColWidths(190, 28, 210);
List<FormItem> fields = new ArrayList<FormItem>(); - addItemsForPropertiesRecursively(locatorId, propertyDefinitionsList, propertyMap, fields); + addItemsForPropertiesRecursively(locatorId, propertyDefinitionsList, propertyMap, fields, firePropertyChangedEvents); form.setFields(fields.toArray(new FormItem[fields.size()]));
return form; }
private void addItemsForPropertiesRecursively(String locatorId, Collection<PropertyDefinition> propertyDefinitions, - AbstractPropertyMap propertyMap, List<FormItem> fields) { + AbstractPropertyMap propertyMap, List<FormItem> fields, + boolean firePropertyChangedEvents) { boolean odd = true; for (PropertyDefinition propertyDefinition : propertyDefinitions) { Property property = propertyMap.get(propertyDefinition.getName()); @@ -540,7 +543,7 @@ public class ConfigurationEditor extends LocatableVLayout { } } addItemsForPropertyRecursively(locatorId + "_" + propertyDefinition.getName(), propertyDefinition, property, - odd, fields); + odd, fields, firePropertyChangedEvents); odd = !odd; } } @@ -548,7 +551,7 @@ public class ConfigurationEditor extends LocatableVLayout { public void addItemsForPropertyRecursively(String locatorId, PropertyDefinition propertyDefinition, Property property, boolean oddRow, - List<FormItem> fields) { + List<FormItem> fields, final boolean firePropertyChangedEvents) { List<FormItem> fieldsForThisProperty = new ArrayList<FormItem>();
StaticTextItem nameItem = new StaticTextItem(); @@ -562,12 +565,24 @@ public class ConfigurationEditor extends LocatableVLayout { fieldsForThisProperty.add(nameItem); fields.add(nameItem);
- FormItem valueItem; + final FormItem valueItem; if (propertyDefinition instanceof PropertyDefinitionSimple) { - PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple)propertyDefinition; - PropertySimple propertySimple = (PropertySimple)property; + final PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple)propertyDefinition; + final PropertySimple propertySimple = (PropertySimple)property;
valueItem = buildSimpleField(propertyDefinitionSimple, propertySimple); + valueItem.addChangedHandler(new ChangedHandler() { + public void onChanged(ChangedEvent changedEvent) { + propertySimple.setErrorMessage(null); + boolean isValid = changedEvent.getItem().validate(); + if (isValid) { + propertySimple.setValue(changedEvent.getValue()); + } + if (firePropertyChangedEvents) { + firePropertyChangedEvent(propertySimple, propertyDefinitionSimple, isValid); + } + } + });
FormItem unsetItem = buildUnsetItem(propertyDefinitionSimple, propertySimple, valueItem); fieldsForThisProperty.add(unsetItem); @@ -583,15 +598,44 @@ public class ConfigurationEditor extends LocatableVLayout { fieldsForThisProperty.add(descriptionItem); fields.add(descriptionItem); } else if (propertyDefinition instanceof PropertyDefinitionList) { - if (((PropertyDefinitionList) propertyDefinition).getMemberDefinition() instanceof PropertyDefinitionMap) { + PropertyDefinitionList propertyDefinitionList = (PropertyDefinitionList)propertyDefinition; + PropertyDefinition memberDefinition = propertyDefinitionList.getMemberDefinition(); + PropertyList propertyList = (PropertyList)property; + if (memberDefinition instanceof PropertyDefinitionMap) { // List of Maps is a specially supported case with summary fields as columns in a table // Note: This field spans 3 columns. + PropertyDefinitionMap memberDefinitionMap = (PropertyDefinitionMap)memberDefinition; CanvasItem listOfMapsItem = buildListOfMapsField(locatorId, - (PropertyDefinitionMap)((PropertyDefinitionList)propertyDefinition).getMemberDefinition(), - oddRow, (PropertyList)property); + memberDefinitionMap, + propertyList, oddRow); + fieldsForThisProperty.add(listOfMapsItem); fields.add(listOfMapsItem); + } else if (memberDefinition instanceof PropertyDefinitionSimple) { + SpacerItem unsetItem = new SpacerItem(); + fieldsForThisProperty.add(unsetItem); + fields.add(unsetItem); + + CanvasItem listOfSimplesItem = buildListOfSimplesField(locatorId, propertyDefinitionList, propertyList, + oddRow); + fieldsForThisProperty.add(listOfSimplesItem); + fields.add(listOfSimplesItem); + + StaticTextItem descriptionItem = new StaticTextItem(); + descriptionItem.setValue(propertyDefinition.getDescription()); + descriptionItem.setShowTitle(false); + descriptionItem.setEndRow(true); + fieldsForThisProperty.add(descriptionItem); + fields.add(descriptionItem); + } else { + Log.error("List " + propertyList + " has unsupported member type: " + memberDefinition); + Canvas canvas = new Canvas(); + // TODO: Add label with error message to canvas. + CanvasItem canvasItem = buildComplexPropertyField(canvas); + canvasItem.setColSpan(3); + canvasItem.setEndRow(true); + fieldsForThisProperty.add(canvasItem); + fields.add(canvasItem); } - // TODO (ips): Add support for lists of simples. } else if (propertyDefinition instanceof PropertyDefinitionMap) { // Note: This field spans 3 columns. FormItem mapField = @@ -605,6 +649,27 @@ public class ConfigurationEditor extends LocatableVLayout { } }
+ private void firePropertyChangedEvent(Property property, + PropertyDefinition propertyDefinition, + boolean isValid) { + boolean wasValidBefore = this.invalidPropertyNames.isEmpty(); + Property topLevelProperty = getTopLevelProperty(property); + validate(); + if (isValid) { + this.invalidPropertyNames.remove(topLevelProperty.getName()); + } else { + this.invalidPropertyNames.add(topLevelProperty.getName()); + } + boolean isValidNow = this.invalidPropertyNames.isEmpty(); + + boolean validationStateChanged = (isValidNow != wasValidBefore); + for (PropertyValueChangeListener propertyValueChangeListener : this.propertyValueChangeListeners) { + PropertyValueChangeEvent event = new PropertyValueChangeEvent(property, propertyDefinition, + validationStateChanged, this.invalidPropertyNames); + propertyValueChangeListener.propertyValueChanged(event); + } + } + public Set<String> getInvalidPropertyNames() { return this.invalidPropertyNames; } @@ -620,6 +685,8 @@ public class ConfigurationEditor extends LocatableVLayout { canvas = buildStaticMapField(locatorId, propertyDefinitionMap, propertyMap); } CanvasItem canvasItem = buildComplexPropertyField(canvas); + canvasItem.setColSpan(3); + canvasItem.setEndRow(true);
return canvasItem; } @@ -627,8 +694,6 @@ public class ConfigurationEditor extends LocatableVLayout { private CanvasItem buildComplexPropertyField(Canvas canvas) { CanvasItem canvasItem = new CanvasItem(); canvasItem.setCanvas(canvas); - canvasItem.setColSpan(3); - canvasItem.setEndRow(true); canvasItem.setShowTitle(false); return canvasItem; } @@ -672,15 +737,14 @@ public class ConfigurationEditor extends LocatableVLayout { VLayout canvas = new VLayout(); canvas.addMember(propertyGrid);
- // Footer - ToolStrip footer = new ToolStrip(); - footer.setPadding(5); - footer.setWidth100(); - footer.setMembersMargin(15); - canvas.addMember(footer); + if (!isReadOnly(propertyDefinitionMap)) { + // Map is not read-only - add footer with New and Delete buttons to allow user to add or remove members. + ToolStrip footer = new ToolStrip(); + footer.setPadding(5); + footer.setWidth100(); + footer.setMembersMargin(15); + canvas.addMember(footer);
- // Properties can only be added to or deleted from non-read-only dynamic maps. - if (!propertyDefinitionMap.isReadOnly()) { final IButton deleteButton = new LocatableIButton(extendLocatorId(propertyMap.getName()), "Delete"); deleteButton.setDisabled(true); deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { @@ -765,13 +829,14 @@ public class ConfigurationEditor extends LocatableVLayout { PropertyMap propertyMap) { Log.debug("Building static map field for " + propertyMap + "...");
- return buildPropertiesForm(parentLocatorId, propertyDefinitionMap.getPropertyDefinitions().values(), propertyMap); - + return buildPropertiesForm(parentLocatorId, propertyDefinitionMap.getPropertyDefinitions().values(), + propertyMap, true); }
private CanvasItem buildListOfMapsField(final String locatorId, - final PropertyDefinitionMap memberPropertyDefinitionMap, boolean oddRow, - final PropertyList propertyList) { + final PropertyDefinitionMap memberPropertyDefinitionMap, + final PropertyList propertyList, boolean oddRow + ) { Log.debug("Building list-of-maps field for " + propertyList + "...");
final ListGrid summaryTable = new ListGrid(); @@ -845,7 +910,7 @@ public class ConfigurationEditor extends LocatableVLayout { Log.info("You want to edit: " + recordClickEvent.getRecord()); PropertyMap memberPropertyMap = (PropertyMap)recordClickEvent.getRecord().getAttributeAsObject( RHQ_PROPERTY_ATTRIBUTE_NAME); - displayMapEditor(locatorId + "_MapEdit", summaryTable, recordClickEvent.getRecord(), + displayMapEditor(extendLocatorId("MapEdit"), summaryTable, recordClickEvent.getRecord(), memberPropertyDefinitionMap, propertyList, memberPropertyMap); } }); @@ -894,7 +959,7 @@ public class ConfigurationEditor extends LocatableVLayout { addRowButton.setIcon(Window.getImgURL("[SKIN]/actions/add.png")); addRowButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { - displayMapEditor(locatorId + "_MapEdit", summaryTable, null, memberPropertyDefinitionMap, propertyList, null); + displayMapEditor(extendLocatorId("MapEdit"), summaryTable, null, memberPropertyDefinitionMap, propertyList, null); } });
@@ -902,9 +967,11 @@ public class ConfigurationEditor extends LocatableVLayout {
summaryTableHolder.setMembers(summaryTable, toolStrip);
- CanvasItem item = buildComplexPropertyField(summaryTableHolder); + CanvasItem canvasItem = buildComplexPropertyField(summaryTableHolder); + canvasItem.setColSpan(3); + canvasItem.setEndRow(true);
- return item; + return canvasItem; }
private ListGridRecord[] buildSummaryRecords(PropertyList propertyList, List<PropertyDefinition> definitions) { @@ -947,25 +1014,206 @@ public class ConfigurationEditor extends LocatableVLayout { record.setAttribute(subDefSimple.getName(), propertySimple.getStringValue()); break; }*/ - } else { - } } record.setAttribute(RHQ_PROPERTY_ATTRIBUTE_NAME, memberPropertyMap); return record; }
- private FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinition, + private CanvasItem buildListOfSimplesField(String locatorId, final PropertyDefinitionList propertyDefinitionList, + final PropertyList propertyList, boolean oddRow) { + Log.debug("Building list-of-simples field for " + propertyList + "..."); + + LocatableVLayout vLayout = new LocatableVLayout(locatorId); + + final DynamicForm listGrid = new DynamicForm(); + vLayout.addMember(listGrid); + + final SelectItem membersItem = new SelectItem(propertyList.getName()); + membersItem.setShowTitle(false); + membersItem.setMultiple(true); + membersItem.setMultipleAppearance(MultipleAppearance.GRID); + membersItem.setWidth(220); + membersItem.setHeight(60); + LinkedHashMap<String, String> memberValueToIndexMap = buildValueMap(propertyList); + membersItem.setValueMap(memberValueToIndexMap); + listGrid.setItems(membersItem); + + if (!isReadOnly(propertyDefinitionList)) { + // List is not read-only - add footer with New and Delete buttons to allow user to add or remove members. + ToolStrip footer = new ToolStrip(); + footer.setPadding(5); + footer.setWidth100(); + footer.setMembersMargin(15); + vLayout.addMember(footer); + + final IButton deleteButton = new LocatableIButton(extendLocatorId("Delete")); + deleteButton.setIcon(Window.getImgURL("[SKIN]/actions/remove.png")); + deleteButton.setTooltip("Delete the selected items from the list."); + deleteButton.setDisabled(true); + deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + final String[] selectedValues = membersItem.getValues(); + final String noun = (selectedValues.length == 1) ? "item" : "items"; + String message = "Are you sure you want to delete the " + selectedValues.length + " selected " + + noun + "?"; + SC.ask(message, new BooleanCallback() { + public void execute(Boolean confirmed) { + if (confirmed) { + for (int i = selectedValues.length - 1; i >= 0; i--) { + String selectedValue = selectedValues[i]; + int index = Integer.valueOf(selectedValue); + propertyList.getList().remove(index); + + // Rebuild the select item options. + LinkedHashMap<String, String> memberValueToIndexMap = buildValueMap(propertyList); + membersItem.setValueMap(memberValueToIndexMap); + + deleteButton.disable(); + + firePropertyChangedEvent(propertyList, propertyDefinitionList, true); + CoreGUI.getMessageCenter().notify(new Message(selectedValues.length + " " + noun + + " deleted from list.", + EnumSet.of( + Message.Option.Transient))); + } + } + } + }); + } + }); + footer.addMember(deleteButton); + + membersItem.addChangedHandler(new ChangedHandler() { + @Override + public void onChanged(ChangedEvent changedEvent) { + String[] selectedValues = membersItem.getValues(); + int count = selectedValues.length; + deleteButton.setDisabled(count < 1); + } + }); + + final IButton newButton = new LocatableIButton(extendLocatorId("New")); + newButton.setIcon(Window.getImgURL("[SKIN]/actions/add.png")); + newButton.setTooltip("Add an item to the list."); + newButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + final Window popup = new Window(); + popup.setTitle("Add Item to List"); + popup.setWidth(300); + popup.setHeight(110); + popup.setIsModal(true); + popup.setShowModalMask(true); + popup.setShowCloseButton(false); + popup.centerInPage(); + + VLayout vLayout = new VLayout(); + vLayout.setMargin(10); + + final DynamicForm form = new DynamicForm(); + + PropertyDefinitionSimple memberPropertyDefinitionSimple = + (PropertyDefinitionSimple)propertyDefinitionList.getMemberDefinition(); + final String propertyName = memberPropertyDefinitionSimple.getName(); + final PropertySimple newMemberPropertySimple = new PropertySimple(propertyName, null); + + FormItem simpleField = + buildSimpleField(memberPropertyDefinitionSimple, newMemberPropertySimple); + simpleField.setAlign(Alignment.CENTER); + simpleField.setDisabled(false); + simpleField.setRequired(true); + simpleField.setEndRow(true); + + SpacerItem spacer = new SpacerItem(); + spacer.setHeight(9); + + form.setItems(simpleField, spacer); + vLayout.addMember(form); + + final IButton okButton = new IButton("OK"); + okButton.disable(); + // saveButton.setID("config_structured_button_save"); + okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + propertyList.add(newMemberPropertySimple); + + // Rebuild the select item options. + LinkedHashMap<String, String> memberValueToIndexMap = buildValueMap(propertyList); + membersItem.setValueMap(memberValueToIndexMap); + + firePropertyChangedEvent(propertyList, propertyDefinitionList, true); + CoreGUI.getMessageCenter().notify(new Message("Item added to list.", EnumSet.of( + Message.Option.Transient))); + + popup.destroy(); + } + }); + + form.addItemChangedHandler(new ItemChangedHandler() { + public void onItemChanged(ItemChangedEvent itemChangedEvent) { + newMemberPropertySimple.setStringValue((String)itemChangedEvent.getNewValue()); + + // Only enable the OK button, allowing the user to add the property to the map, if the + // property is valid. + boolean isValid = form.validate(); + okButton.setDisabled(!isValid); + } + }); + + final IButton cancelButton = new IButton("Cancel"); + cancelButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + public void onClick(ClickEvent clickEvent) { + popup.destroy(); + } + }); + + HLayout buttons = new HLayout(); + buttons.setAlign(Alignment.CENTER); + buttons.setTop(10); + buttons.setMembersMargin(10); + buttons.setMembers(okButton, cancelButton); + vLayout.addMember(buttons); + + popup.addItem(vLayout); + popup.show(); + + simpleField.focusInItem(); + } + }); + footer.addMember(newButton); + } + + return buildComplexPropertyField(vLayout); + } + + private LinkedHashMap<String, String> buildValueMap(PropertyList propertyList) { + LinkedHashMap<String, String> memberValueToIndexMap = new LinkedHashMap<String, String>(); + List<Property> memberProperties = propertyList.getList(); + int index = 0; + for (Iterator<Property> iterator = memberProperties.iterator(); iterator.hasNext();) { + Property memberProperty = iterator.next(); + PropertySimple memberPropertySimple = (PropertySimple)memberProperty; + String memberValue = memberPropertySimple.getStringValue(); + if (memberValue == null) { + Log.error("List " + propertyList + " contains property with null value - removing and skipping..."); + iterator.remove(); + continue; + } + memberValueToIndexMap.put(String.valueOf(index++), memberValue); + } + return memberValueToIndexMap; + } + + private FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinitionSimple, final PropertySimple propertySimple) { Log.debug("Building simple field for " + propertySimple + "...");
FormItem valueItem = null;
- List<PropertyDefinitionEnumeration> enumeratedValues = propertyDefinition.getEnumeratedValues(); + List<PropertyDefinitionEnumeration> enumeratedValues = propertyDefinitionSimple.getEnumeratedValues(); if (enumeratedValues != null && !enumeratedValues.isEmpty()) { - LinkedHashMap<String, String> valueOptions = new LinkedHashMap<String, String>(); - for (PropertyDefinitionEnumeration option : propertyDefinition.getEnumeratedValues()) { + for (PropertyDefinitionEnumeration option : propertyDefinitionSimple.getEnumeratedValues()) { valueOptions.put(option.getValue(), option.getName()); }
@@ -979,7 +1227,7 @@ public class ConfigurationEditor extends LocatableVLayout { valueItem.setValue(propertySimple.getStringValue()); } } else { - switch (propertyDefinition.getType()) { + switch (propertyDefinitionSimple.getType()) {
case STRING: case FILE: @@ -1019,12 +1267,12 @@ public class ConfigurationEditor extends LocatableVLayout { } }
- valueItem.setRequired(propertyDefinition.isRequired()); + valueItem.setRequired(propertyDefinitionSimple.isRequired());
- List<Validator> validators = buildValidators(propertyDefinition, propertySimple); + List<Validator> validators = buildValidators(propertyDefinitionSimple, propertySimple); valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
- valueItem.setDisabled(isReadOnly(propertyDefinition) || isUnset(propertyDefinition, propertySimple)); + valueItem.setDisabled(isReadOnly(propertyDefinitionSimple) || isUnset(propertyDefinitionSimple, propertySimple)); /* Click handlers seem to be turned off for disabled fields... need an alternative valueItem.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { @@ -1040,36 +1288,11 @@ public class ConfigurationEditor extends LocatableVLayout { valueItem.setShowTitle(false); valueItem.setWidth(220);
- final FormItem finalValueItem = valueItem; - - finalValueItem.addChangedHandler(new ChangedHandler() { - public void onChanged(ChangedEvent changedEvent) { - propertySimple.setErrorMessage(null); - - boolean wasValidBefore = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); - Property topLevelProperty = getTopLevelProperty(propertySimple); - if (changedEvent.getItem().validate()) { - ConfigurationEditor.this.invalidPropertyNames.remove(topLevelProperty.getName()); - propertySimple.setValue(changedEvent.getValue()); - } else { - ConfigurationEditor.this.invalidPropertyNames.add(topLevelProperty.getName()); - } - boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); - - boolean validationStateChanged = (isValidNow != wasValidBefore); - for (PropertyValueChangeListener propertyValueChangeListener : ConfigurationEditor.this.propertyValueChangeListeners) { - PropertyValueChangeEvent event = new PropertyValueChangeEvent(propertySimple, propertyDefinition, - validationStateChanged, ConfigurationEditor.this.invalidPropertyNames); - propertyValueChangeListener.propertyValueChanged(event); - } - } - }); - return valueItem; }
- private static Property getTopLevelProperty(PropertySimple propertySimple) { - Property currentProperty = propertySimple; + private static Property getTopLevelProperty(Property property) { + Property currentProperty = property; while (currentProperty.getConfiguration() == null) { if (currentProperty.getParentList() != null) { currentProperty = currentProperty.getParentList(); @@ -1167,24 +1390,20 @@ public class ConfigurationEditor extends LocatableVLayout { }
private void displayMapEditor(String locatorId, final ListGrid summaryTable, final Record existingRecord, - PropertyDefinitionMap definition, final PropertyList list, PropertyMap map) { + PropertyDefinitionMap definition, final PropertyList list, final PropertyMap map) {
final List<PropertyDefinition> memberDefinitions = new ArrayList<PropertyDefinition>(definition .getPropertyDefinitions().values()); Collections.sort(memberDefinitions, new PropertyDefinitionComparator());
- final boolean newRow = map == null; - if (newRow) { - map = new PropertyMap(definition.getName()); - } - - final PropertyMap finalMap = map; - final PropertyMap copy = finalMap.deepCopy(true); + final boolean newRow = (map == null); + final PropertyMap workingMap = newRow ? new PropertyMap(definition.getName()) : map.deepCopy(true);
LocatableVLayout layout = new LocatableVLayout(locatorId); layout.setHeight100();
- final DynamicForm childForm = buildPropertiesForm(locatorId + "_Child", memberDefinitions, finalMap); + final DynamicForm childForm = buildPropertiesForm(extendLocatorId("Editor"), memberDefinitions, workingMap, + false); childForm.setHeight100(); layout.addMember(childForm);
@@ -1203,22 +1422,26 @@ public class ConfigurationEditor extends LocatableVLayout { okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { if (newRow) { - list.add(finalMap); - ListGridRecord record = buildSummaryRecord(memberDefinitions, finalMap); + list.add(workingMap); + ListGridRecord record = buildSummaryRecord(memberDefinitions, workingMap); try { summaryTable.addData(record); } catch (Exception e) { e.printStackTrace(); } } else { + // TODO: Pass in the map's index, rather than using indexOf(), which is not 100% reliable, + // since a list could contain two or more identical maps. + //list.getList().set(list.getList().indexOf(map), workingMap); for (PropertyDefinition subDef : memberDefinitions) { PropertyDefinitionSimple subDefSimple = (PropertyDefinitionSimple) subDef; - PropertySimple propertySimple = ((PropertySimple) finalMap.get(subDefSimple.getName())); + PropertySimple propertySimple = ((PropertySimple) workingMap.get(subDefSimple.getName())); existingRecord.setAttribute(subDefSimple.getName(), propertySimple != null ? propertySimple .getStringValue() : null); } summaryTable.updateData(existingRecord); } + firePropertyChangedEvent(list, null, true); summaryTable.redraw();
// ListGridRecord[] rows = buildSummaryRecords(list, definitions); @@ -1239,9 +1462,6 @@ public class ConfigurationEditor extends LocatableVLayout { final IButton cancelButton = new IButton("Cancel"); cancelButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { - if (!newRow) { - list.getList().set(list.getList().indexOf(finalMap), copy); - } popup.destroy(); } }); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java index 3f9f225..d616f81 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.configuration;
import java.util.EnumSet; +import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; @@ -130,13 +131,15 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P MessageCenter messageCenter = CoreGUI.getMessageCenter(); Message message; if (event.isValidationStateChanged()) { - if (event.getInvalidPropertyNames().isEmpty()) { - this.saveButton.enable(); - message = new Message("All configuration properties now have valid values, so the configuration can now be saved.", - Message.Severity.Info, EnumSet.of(Message.Option.Transient)); + Set<String> invalidPropertyNames = event.getInvalidPropertyNames(); + if (invalidPropertyNames.isEmpty()) { + this.saveButton.enable(); + message = new Message("All configuration properties have valid values, so the configuration can now be saved.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); } else { this.saveButton.disable(); - message = new Message("One or more configuration properties have invalid values. The values must be corrected before the configuration can be saved.", + message = new Message("The following configuration properties have invalid values: " + + invalidPropertyNames + ". The values must be corrected before the configuration can be saved.", Message.Severity.Error, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); } messageCenter.notify(message); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java index 1f1cc52..703f9d4 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.inventory;
import java.util.EnumSet; +import java.util.Set;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.Overflow; @@ -129,13 +130,15 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro MessageCenter messageCenter = CoreGUI.getMessageCenter(); Message message; if (event.isValidationStateChanged()) { - if (event.getInvalidPropertyNames().isEmpty()) { + Set<String> invalidPropertyNames = event.getInvalidPropertyNames(); + if (invalidPropertyNames.isEmpty()) { this.saveButton.enable(); - message = new Message("All connection settings now have valid values, so the settings can now be saved.", - Message.Severity.Info, EnumSet.of(Message.Option.Transient)); + message = new Message("All connection settings have valid values, so the settings can now be saved.", + Message.Severity.Info, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); } else { this.saveButton.disable(); - message = new Message("One or more connection settings have invalid values. The values must be corrected before the settings can be saved.", + message = new Message("The following connection settings have invalid values: " + invalidPropertyNames + + ". The values must be corrected before the settings can be saved.", Message.Severity.Error, EnumSet.of(Message.Option.Transient, Message.Option.Sticky)); } messageCenter.notify(message); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java index cc71a2c..0ad4e0a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java @@ -121,9 +121,9 @@ public abstract class TestConfigurationFactory { readOnlyOpenMapPropDef.setReadOnly(true); propertyDefinitions.put(readOnlyOpenMapPropDef.getName(), readOnlyOpenMapPropDef);
- PropertyDefinitionList listOfSimplesPropDef = new PropertyDefinitionList("ListOfStrings", - "another list of Strings", true, new PropertyDefinitionSimple("note", "a note", false, - PropertySimpleType.STRING)); + PropertyDefinitionList listOfSimplesPropDef = new PropertyDefinitionList("ListOfSimples", + "a list of Integer simples", true, new PropertyDefinitionSimple("integer", "an integer", false, + PropertySimpleType.INTEGER)); listOfSimplesPropDef.setDisplayName(listOfSimplesPropDef.getName()); propertyDefinitions.put(listOfSimplesPropDef.getName(), listOfSimplesPropDef);
@@ -230,15 +230,15 @@ public abstract class TestConfigurationFactory { openPropMap2.put(new PropertySimple("ANT_OPTS", "-Xms128M -Xmx256M")); configuration.put(openPropMap2);
- configuration.put(new PropertyList("ListOfStrings", new PropertySimple("note", "Do"), new PropertySimple( - "note", "Re"), new PropertySimple("note", "Mi"), new PropertySimple("note", "Fa"), new PropertySimple( - "note", "So"), new PropertySimple("note", "La"), new PropertySimple("note", "Ti"))); + configuration.put(new PropertyList("ListOfSimples", new PropertySimple("integer", "18"), new PropertySimple( + "integer", "127"), new PropertySimple("integer", "311"), new PropertySimple("integer", "2"), new PropertySimple( + "integer", "301"), new PropertySimple("integer", "79"), new PropertySimple("integer", "62")));
- PropertyMap propMap2 = new PropertyMap("MapOfSimples"); + PropertyMap propMap2 = new PropertyMap("MapOfSimplesInList"); propMap2.put(new PropertySimple("String1", "Uno")); propMap2.put(new PropertySimple("String2", "Dos")); propMap2.put(new PropertySimple("Integer", Integer.MIN_VALUE)); - PropertyMap propMap3 = new PropertyMap("MapOfSimples"); + PropertyMap propMap3 = new PropertyMap("MapOfSimplesInList"); propMap3.put(new PropertySimple("String1", "Un")); propMap3.put(new PropertySimple("String2", "Deux")); propMap3.put(new PropertySimple("Integer", Integer.MAX_VALUE)); 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 6b356ae..04fceff 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 @@ -38,7 +38,7 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout; */ public class MessageBar extends LocatableHLayout implements MessageCenter.MessageListener { private static final String LOCATOR_ID = "MessageBar"; - private static final int AUTO_HIDE_DELAY_MILLIS = 30000; // 30 seconds + private static final int AUTO_HIDE_DELAY_MILLIS = 15000; // 15 seconds
private static final Map<Message.Severity, String> SEVERITY_TO_STYLE_NAME_MAP = new HashMap<Message.Severity, String>(); static { @@ -56,6 +56,7 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag }
private Label label; + private Message stickyMessage;
public MessageBar() { super(LOCATOR_ID); @@ -79,19 +80,20 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag public void onMessage(Message message) { if (!message.isBackgroundJobResult()) { // First clear any previous message. - clearMessage(); + clearMessage(message.isSticky()); + displayMessage(message);
- this.label = createLabel(message); - - addMember(this.label); - markForRedraw(); - - // Auto-clear the message after 30 seconds unless it's been designated as sticky. - if (!message.isSticky()) { + // Auto-clear the message after 15 seconds unless it's been designated as sticky. + if (message.isSticky()) { + this.stickyMessage = message; + } else { Timer hideTimer = new Timer() { @Override - public void run() { - clearMessage(); + public void run() { + clearMessage(false); + if (stickyMessage != null) { + displayMessage(stickyMessage); + } } }; hideTimer.schedule(AUTO_HIDE_DELAY_MILLIS); @@ -100,11 +102,24 @@ public class MessageBar extends LocatableHLayout implements MessageCenter.Messag }
public void clearMessage() { + clearMessage(true); + } + + private void displayMessage(Message message) { + this.label = createLabel(message); + addMember(this.label); + markForRedraw(); + } + + private void clearMessage(boolean clearSticky) { if (this.label != null) { this.label.destroy(); removeMember(this.label); markForRedraw(); } + if (clearSticky) { + this.stickyMessage = null; + } }
private Label createLabel(Message message) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/LocatableIButton.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/LocatableIButton.java index f265697..359abfd 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/LocatableIButton.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/selenium/LocatableIButton.java @@ -9,7 +9,11 @@ import com.smartgwt.client.widgets.IButton; */ public class LocatableIButton extends IButton {
- /** + public LocatableIButton(String locatorId) { + this(locatorId, null); + } + + /** * <pre> * ID Format: "simpleClassname_locatorId" * </pre>
commit e72bec6073b058f6dc33ab5b5e9713592ed64fde Author: Filip Drabek fdrabek@dhcp-lab-136.englab.brq.redhat.com Date: Tue Oct 5 23:05:46 2010 +0200
Cobertura xml report
diff --git a/modules/enterprise/server/container/pom.xml b/modules/enterprise/server/container/pom.xml index 793e85b..831ec5e 100644 --- a/modules/enterprise/server/container/pom.xml +++ b/modules/enterprise/server/container/pom.xml @@ -415,7 +415,9 @@
Pattern sourceCodeFolder = Pattern.compile(".*/src/main/java") Pattern sourceCodeFile = Pattern.compile('.*/src/main/java/(.*.java)') - + + list.add("--format") + list.add("xml") list.add("--datafile") list.add("${project.build.directory}/cobertura/cobertura.ser") list.add("--destination")
commit 91afe1dcdc446bf9a1a9219f9fa4630792a3ef96 Merge: dd1eab3... 26dfcd6... Author: Filip Drabek fdrabek@dhcp-lab-136.englab.brq.redhat.com Date: Tue Oct 5 18:27:41 2010 +0200
Merge branch 'master' of ssh://git.fedorahosted.org/git/rhq/rhq
commit 26dfcd67680366513e1820bd18219a614437fb88 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 17:34:16 2010 +0200
Removing the dependency on GWT from the core/domain. The RHQDomain GWT module is now defined within the coregui and pulls the sources from the core/domain during the build.
diff --git a/modules/core/domain/pom.xml b/modules/core/domain/pom.xml index 0806490..d033ae3 100644 --- a/modules/core/domain/pom.xml +++ b/modules/core/domain/pom.xml @@ -219,27 +219,6 @@ <version>2.8.1</version> <scope>test</scope> </dependency> - - - <dependency> - <groupId>com.google.gwt</groupId> - <artifactId>gwt-user</artifactId> - <version>2.0.3</version> - </dependency> - - <dependency> - <groupId>com.google.gwt</groupId> - <artifactId>gwt-dev</artifactId> - <version>2.0.3</version> - <scope>provided</scope> - </dependency> - - <!--<dependency> - <groupId>com.smartgwt</groupId> - <artifactId>smartgwt</artifactId> - <version>2.0</version> - </dependency>--> - </dependencies>
<build> @@ -265,32 +244,20 @@
<plugins>
- <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>gwt-maven-plugin</artifactId> - <version>1.2</version> - - <configuration> - <noServer>true</noServer> - <inplace>false</inplace> - <logLevel>INFO</logLevel> - <extraJvmArgs>-Xmx512m</extraJvmArgs> - <localWorkers>2</localWorkers> - <draftCompile>true</draftCompile> - <buildOutputDirectory>target/gwtclasses</buildOutputDirectory> - <hostedWebapp>target/hostedwar</hostedWebapp> - <debugSuspend>false</debugSuspend> - </configuration> - - <executions> - <execution> - <goals> - <goal>compile</goal> - </goals> - </execution> - </executions> - </plugin> - + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-source-plugin</artifactId> + <version>2.1.2</version> + <executions> + <execution> + <id>attach-sources</id> + <phase>verify</phase> + <goals> + <goal>jar-no-fork</goal> + </goals> + </execution> + </executions> + </plugin>
<plugin> <artifactId>maven-surefire-plugin</artifactId> diff --git a/modules/core/domain/src/main/java/org/rhq/core/RHQDomain.gwt.xml b/modules/core/domain/src/main/java/org/rhq/core/RHQDomain.gwt.xml deleted file mode 100644 index a9a94a9..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/RHQDomain.gwt.xml +++ /dev/null @@ -1,18 +0,0 @@ -<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.6//EN" - "http://google-web-toolkit.googlecode.com/svn/releases/1.6/distro-source/core/src/gwt-module.dtd"> -<module> - - <inherits name='com.google.gwt.user.User'/> - - <entry-point class='org.rhq.core.client.RHQDomain'/> - - <source path="client"/> - <source path="domain"/> - - - <!--<generate-with class="org.rhq.core.rebind.RecordBuilderGenerator"> - <when-type-assignable class="org.rhq.core.domain.util.Recordizable"/> - </generate-with>--> - - -</module> \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/client/RHQDomain.java b/modules/core/domain/src/main/java/org/rhq/core/client/RHQDomain.java deleted file mode 100644 index 9669149..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/client/RHQDomain.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * RHQ Management Platform - * Copyright (C) 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, 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.client; - -import com.google.gwt.core.client.EntryPoint; -import com.google.gwt.user.client.ui.*; - -public class RHQDomain implements EntryPoint { - public void onModuleLoad() { - } -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.css b/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.css deleted file mode 100644 index a111f82..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.css +++ /dev/null @@ -1,7 +0,0 @@ -body { - background-color: white; - color: black; - font-family: Arial, sans-serif; - font-size: small; - margin: 8px; -} diff --git a/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.html b/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.html deleted file mode 100644 index 3878eb5..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/public/RHQDomain.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<head> - <title>RHQDomain Application</title> - <link rel="stylesheet" href="RHQDomain.css"> -</head> -<body> -<script type="text/javascript" language="javascript" src="org.rhq.core.RHQDomain.nocache.js"></script> -<h1>RHQDomain Application</h1> -</body> -</html> diff --git a/modules/core/domain/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java b/modules/core/domain/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java deleted file mode 100644 index ca6a5ab..0000000 --- a/modules/core/domain/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java +++ /dev/null @@ -1,172 +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.core.rebind; - -import com.google.gwt.core.ext.Generator; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.NotFoundException; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; -import com.google.gwt.user.rebind.SourceWriter; - -import javax.persistence.Entity; - -import java.io.PrintWriter; - - -/** - * This is the start to a rebinder for our domain entities to allow for the - * easy generation of Smart's Record objecgts. I have not yet gotten this working. - * - * - * @author Greg Hinkle - */ -public class RecordBuilderGenerator extends Generator { - - - - - protected TreeLogger logger; - private String packageName; - private String qualifiedStubClassName; - private JClassType requestedClass; - private String simpleStubClassName; - private SourceWriter sourceWriter; - private TypeOracle typeOracle; - - /** - * Create a new type that satisfies the rebind request. - */ - @Override - public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { - - System.out.println("classType " + typeName); - - if (!init(logger, context, typeName)) { - return null; - } - - writeSource(); - sourceWriter.commit(logger); - - return qualifiedStubClassName; - } - - protected JClassType getRequestedClass() { - return requestedClass; - } - - protected SourceWriter getSourceWriter() { - return sourceWriter; - } - - protected TypeOracle getTypeOracle() { - return typeOracle; - } - - @SuppressWarnings("unused") - protected void writeSource() throws UnableToCompleteException { - - - - JField[] fields = requestedClass.getFields(); - - writeBuildRecordMethod(fields, sourceWriter); - } - - /** - * Gets the name of the native stub class. - */ - private String getSimpleStubClassName(JClassType baseClass) { - return "__" + baseClass.getSimpleSourceName() + "_RecordBuilder"; - } - - private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx, - String packageName, String className, String superclassName) { - - PrintWriter printWriter = ctx.tryCreate(logger, packageName, className); - if (printWriter == null) { - return null; - } - - ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( - packageName, className); - - composerFactory.setSuperclass(superclassName); - - return composerFactory.createSourceWriter(ctx, printWriter); - } - - private boolean init(TreeLogger logger, GeneratorContext context, - String typeName) throws UnableToCompleteException { - this.logger = logger; - typeOracle = context.getTypeOracle(); - assert typeOracle != null; - - try { - requestedClass = typeOracle.getType(typeName); - } catch (NotFoundException e) { - logger.log( - TreeLogger.ERROR, - "Could not find type '" - + typeName - + "'; please see the log, as this usually indicates a previous error ", - e); - throw new UnableToCompleteException(); - } - - if (requestedClass.getAnnotation(Entity.class) == null) { - System.out.println("Not an entity: " + typeName); - return false; - } - - System.out.println("$$$$$$$$Making a record builder for: "+ typeName); - - // Get the stub class name, and see if its source file exists. - // - simpleStubClassName = getSimpleStubClassName(requestedClass); - packageName = requestedClass.getPackage().getName(); - qualifiedStubClassName = packageName + "." + simpleStubClassName; - - sourceWriter = getSourceWriter(logger, context, packageName, - simpleStubClassName, requestedClass.getQualifiedSourceName()); - - return sourceWriter != null; - } - - private void writeBuildRecordMethod(JField[] fields, SourceWriter sw) { - sw.println(); - sw.println("protected final com.smartgwt.client.data.Record buildRecord(" + requestedClass.getQualifiedSourceName() + " entity) throws Throwable {"); - sw.indent(); - - sw.println("com.smartgwt.client.data.Record record = new com.smartgwt.client.data.Record();"); - - for (JField field :fields) { - sw.println("record.setAttribute("" + field.getName() + "", " + field.getName() + ");"); - } - sw.println("return record;"); - sw.outdent(); - sw.println("}"); - } - -} diff --git a/modules/enterprise/gui/coregui/pom.xml b/modules/enterprise/gui/coregui/pom.xml index 21dd681..c24aa4f 100644 --- a/modules/enterprise/gui/coregui/pom.xml +++ b/modules/enterprise/gui/coregui/pom.xml @@ -63,8 +63,7 @@ <scope>provided</scope> <!-- by rhq.ear --> </dependency> - - + <!-- =============== 3rd Party Deps =============== -->
<dependency> @@ -80,6 +79,13 @@ <scope>provided</scope> </dependency>
+ <dependency> + <groupId>com.google.gwt</groupId> + <artifactId>gwt-dev</artifactId> + <scope>provided</scope> + <version>${gwt.version}</version> + </dependency> + <!--<dependency> <groupId>com.google.gwt</groupId> <artifactId>gwt-incubator</artifactId> @@ -253,6 +259,7 @@ <debugSuspend>false</debugSuspend> <servicePattern>**/gwt/*GWTService.java</servicePattern> <i18nMessagesBundle>org.rhq.enterprise.gui.coregui.client.Messages</i18nMessagesBundle> + <compileSourcesArtifacts>org.rhq:rhq-core-domain</compileSourcesArtifacts> </configuration>
<executions> diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/RHQDomain.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/RHQDomain.gwt.xml new file mode 100644 index 0000000..4d702c2 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/RHQDomain.gwt.xml @@ -0,0 +1,15 @@ +<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.6//EN" + "http://google-web-toolkit.googlecode.com/svn/releases/1.6/distro-source/core/src/gwt-module.dtd"> +<module> + <inherits name='com.google.gwt.user.User'/> + + <entry-point class='org.rhq.core.client.RHQDomain'/> + + <source path="client"/> + <source path="domain"/> + + <!--<generate-with class="org.rhq.core.rebind.RecordBuilderGenerator"> + <when-type-assignable class="org.rhq.core.domain.util.Recordizable"/> + </generate-with>--> + +</module> \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/client/RHQDomain.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/client/RHQDomain.java new file mode 100644 index 0000000..9669149 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/client/RHQDomain.java @@ -0,0 +1,31 @@ +/* + * RHQ Management Platform + * Copyright (C) 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, 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.client; + +import com.google.gwt.core.client.EntryPoint; +import com.google.gwt.user.client.ui.*; + +public class RHQDomain implements EntryPoint { + public void onModuleLoad() { + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java new file mode 100644 index 0000000..ca6a5ab --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/core/rebind/RecordBuilderGenerator.java @@ -0,0 +1,172 @@ +/* + * 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.core.rebind; + +import com.google.gwt.core.ext.Generator; +import com.google.gwt.core.ext.GeneratorContext; +import com.google.gwt.core.ext.TreeLogger; +import com.google.gwt.core.ext.UnableToCompleteException; +import com.google.gwt.core.ext.typeinfo.JClassType; +import com.google.gwt.core.ext.typeinfo.JField; +import com.google.gwt.core.ext.typeinfo.NotFoundException; +import com.google.gwt.core.ext.typeinfo.TypeOracle; +import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; +import com.google.gwt.user.rebind.SourceWriter; + +import javax.persistence.Entity; + +import java.io.PrintWriter; + + +/** + * This is the start to a rebinder for our domain entities to allow for the + * easy generation of Smart's Record objecgts. I have not yet gotten this working. + * + * + * @author Greg Hinkle + */ +public class RecordBuilderGenerator extends Generator { + + + + + protected TreeLogger logger; + private String packageName; + private String qualifiedStubClassName; + private JClassType requestedClass; + private String simpleStubClassName; + private SourceWriter sourceWriter; + private TypeOracle typeOracle; + + /** + * Create a new type that satisfies the rebind request. + */ + @Override + public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { + + System.out.println("classType " + typeName); + + if (!init(logger, context, typeName)) { + return null; + } + + writeSource(); + sourceWriter.commit(logger); + + return qualifiedStubClassName; + } + + protected JClassType getRequestedClass() { + return requestedClass; + } + + protected SourceWriter getSourceWriter() { + return sourceWriter; + } + + protected TypeOracle getTypeOracle() { + return typeOracle; + } + + @SuppressWarnings("unused") + protected void writeSource() throws UnableToCompleteException { + + + + JField[] fields = requestedClass.getFields(); + + writeBuildRecordMethod(fields, sourceWriter); + } + + /** + * Gets the name of the native stub class. + */ + private String getSimpleStubClassName(JClassType baseClass) { + return "__" + baseClass.getSimpleSourceName() + "_RecordBuilder"; + } + + private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx, + String packageName, String className, String superclassName) { + + PrintWriter printWriter = ctx.tryCreate(logger, packageName, className); + if (printWriter == null) { + return null; + } + + ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( + packageName, className); + + composerFactory.setSuperclass(superclassName); + + return composerFactory.createSourceWriter(ctx, printWriter); + } + + private boolean init(TreeLogger logger, GeneratorContext context, + String typeName) throws UnableToCompleteException { + this.logger = logger; + typeOracle = context.getTypeOracle(); + assert typeOracle != null; + + try { + requestedClass = typeOracle.getType(typeName); + } catch (NotFoundException e) { + logger.log( + TreeLogger.ERROR, + "Could not find type '" + + typeName + + "'; please see the log, as this usually indicates a previous error ", + e); + throw new UnableToCompleteException(); + } + + if (requestedClass.getAnnotation(Entity.class) == null) { + System.out.println("Not an entity: " + typeName); + return false; + } + + System.out.println("$$$$$$$$Making a record builder for: "+ typeName); + + // Get the stub class name, and see if its source file exists. + // + simpleStubClassName = getSimpleStubClassName(requestedClass); + packageName = requestedClass.getPackage().getName(); + qualifiedStubClassName = packageName + "." + simpleStubClassName; + + sourceWriter = getSourceWriter(logger, context, packageName, + simpleStubClassName, requestedClass.getQualifiedSourceName()); + + return sourceWriter != null; + } + + private void writeBuildRecordMethod(JField[] fields, SourceWriter sw) { + sw.println(); + sw.println("protected final com.smartgwt.client.data.Record buildRecord(" + requestedClass.getQualifiedSourceName() + " entity) throws Throwable {"); + sw.indent(); + + sw.println("com.smartgwt.client.data.Record record = new com.smartgwt.client.data.Record();"); + + for (JField field :fields) { + sw.println("record.setAttribute("" + field.getName() + "", " + field.getName() + ");"); + } + sw.println("return record;"); + sw.outdent(); + sw.println("}"); + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index 040fc16..8096fcf 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -5,7 +5,7 @@
<inherits name='com.google.gwt.user.User'/> <inherits name='com.google.gwt.i18n.I18N'/> - <inherits name='org.rhq.core.RHQDomain'/> + <inherits name='org.rhq.core.RHQDomain'/>
<inherits name='com.smartgwt.SmartGwt' /> <inherits name="com.smartgwt.tools.SmartGwtTools"/> diff --git a/modules/plugins/hadoop/src/main/java/org/rhq/plugins/hadoop/HadoopComponent.java b/modules/plugins/hadoop/src/main/java/org/rhq/plugins/hadoop/HadoopComponent.java index a568de9..848d560 100644 --- a/modules/plugins/hadoop/src/main/java/org/rhq/plugins/hadoop/HadoopComponent.java +++ b/modules/plugins/hadoop/src/main/java/org/rhq/plugins/hadoop/HadoopComponent.java @@ -18,8 +18,6 @@ */ package org.rhq.plugins.hadoop;
-import com.google.gwt.user.client.ui.ResizeComposite; - import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; import org.rhq.core.pluginapi.inventory.ResourceComponent;
commit dd1eab3b377362ee5c3461f5b492d958ae7afe18 Author: Filip Drabek fdrabek@dhcp-lab-136.englab.brq.redhat.com Date: Tue Oct 5 16:52:12 2010 +0200
Cobertura settings
diff --git a/modules/cli-tests/pom.xml b/modules/cli-tests/pom.xml index 6eed8b4..37068b2 100644 --- a/modules/cli-tests/pom.xml +++ b/modules/cli-tests/pom.xml @@ -140,7 +140,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/common/ant-bundle/pom.xml b/modules/common/ant-bundle/pom.xml index 0833b2a..d8fe9bc 100644 --- a/modules/common/ant-bundle/pom.xml +++ b/modules/common/ant-bundle/pom.xml @@ -31,7 +31,7 @@ <artifactId>rhq-core-domain</artifactId> <version>${project.version}</version> </dependency> - + <dependency> <groupId>${project.groupId}</groupId> <artifactId>rhq-core-util</artifactId> @@ -121,4 +121,91 @@ </plugins> </build>
+ <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> </project> diff --git a/modules/common/filetemplate-bundle/pom.xml b/modules/common/filetemplate-bundle/pom.xml index 7f7127c..b157e77 100644 --- a/modules/common/filetemplate-bundle/pom.xml +++ b/modules/common/filetemplate-bundle/pom.xml @@ -31,7 +31,7 @@ <artifactId>getopt</artifactId> <!-- NOTE: The version is defined in the root POM's dependencyManagement section. --> </dependency> - + <dependency> <groupId>${project.groupId}</groupId> <artifactId>rhq-core-native-system</artifactId> @@ -50,4 +50,91 @@ </dependency> </dependencies>
+ <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> </project> \ No newline at end of file diff --git a/modules/common/jboss-as/pom.xml b/modules/common/jboss-as/pom.xml index b60da0b..a54012e 100644 --- a/modules/common/jboss-as/pom.xml +++ b/modules/common/jboss-as/pom.xml @@ -31,7 +31,6 @@ <artifactId>ant</artifactId> <version>1.6.5</version> </dependency> - <dependency> <groupId>jboss</groupId> <artifactId>jbpm</artifactId> @@ -97,5 +96,97 @@ </plugins> </build> --> - + <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <path id="cobertura.classpath"> + <fileset dir="${user.home}/.m2/repository/net/sourceforge/cobertura/cobertura/1.9.4.1/"> + <include name="cobertura*.jar" /> + <include name="lib/**/*.jar" /> + </fileset> + </path> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> </project> \ No newline at end of file diff --git a/modules/core/client-api/pom.xml b/modules/core/client-api/pom.xml index ae391f8..4617b45 100644 --- a/modules/core/client-api/pom.xml +++ b/modules/core/client-api/pom.xml @@ -192,7 +192,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 4035ed5..4cf8ae1 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -458,6 +458,91 @@ </plugins> </build> </profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
<pluginRepositories> diff --git a/modules/core/domain/pom.xml b/modules/core/domain/pom.xml index 0806490..c3a2f08 100644 --- a/modules/core/domain/pom.xml +++ b/modules/core/domain/pom.xml @@ -436,7 +436,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/core/native-system/pom.xml b/modules/core/native-system/pom.xml index b3a20e2..63feda4 100644 --- a/modules/core/native-system/pom.xml +++ b/modules/core/native-system/pom.xml @@ -27,7 +27,7 @@ </properties>
<dependencies> - + <dependency> <groupId>${rhq.groupId}</groupId> <artifactId>rhq-core-util</artifactId> @@ -46,7 +46,6 @@ <!-- NOTE: The version is defined in the root POM's dependencyManagement section. --> <type>zip</type> </dependency> - </dependencies>
<build> @@ -106,7 +105,94 @@
</plugins> </build> - + <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> <repositories> <!-- This is for SIGAR 1.6.4. --> <repository> diff --git a/modules/core/plugin-api/pom.xml b/modules/core/plugin-api/pom.xml index d9c8d4c..092b730 100644 --- a/modules/core/plugin-api/pom.xml +++ b/modules/core/plugin-api/pom.xml @@ -71,7 +71,7 @@ <!-- NOTE: The version is defined in the root POM's dependencyManagement section. --> <!--<scope>test</scope> not sure about this --> </dependency> - + </dependencies>
<pluginRepositories> @@ -97,5 +97,91 @@ </snapshots> </repository> </repositories> - + <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> </project> diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index 4d6e753..c3e939b 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -359,6 +359,93 @@ </repository>
</repositories> - + <profiles> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> + </project>
diff --git a/modules/core/pom.xml b/modules/core/pom.xml index b895d04..5853b59 100644 --- a/modules/core/pom.xml +++ b/modules/core/pom.xml @@ -23,9 +23,17 @@ <properties> <scm.module.path>modules/core/</scm.module.path> </properties> - + + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> <profiles> - + <profile> <id>default</id> <activation> diff --git a/modules/core/util/pom.xml b/modules/core/util/pom.xml index 458c635..5f84103 100644 --- a/modules/core/util/pom.xml +++ b/modules/core/util/pom.xml @@ -127,7 +127,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/comm/pom.xml b/modules/enterprise/comm/pom.xml index dcd5bed..3ccab17 100644 --- a/modules/enterprise/comm/pom.xml +++ b/modules/enterprise/comm/pom.xml @@ -224,7 +224,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/gui/installer-war/pom.xml b/modules/enterprise/gui/installer-war/pom.xml index b3ccdca..0ad00e4 100644 --- a/modules/enterprise/gui/installer-war/pom.xml +++ b/modules/enterprise/gui/installer-war/pom.xml @@ -302,7 +302,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
<repositories> diff --git a/modules/enterprise/gui/portal-war/pom.xml b/modules/enterprise/gui/portal-war/pom.xml index f802053..048b66a 100644 --- a/modules/enterprise/gui/portal-war/pom.xml +++ b/modules/enterprise/gui/portal-war/pom.xml @@ -587,7 +587,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/enterprise/pom.xml b/modules/enterprise/pom.xml index 89f283c..f90816a 100644 --- a/modules/enterprise/pom.xml +++ b/modules/enterprise/pom.xml @@ -23,7 +23,16 @@ <properties> <scm.module.path>modules/enterprise/</scm.module.path> </properties> - + + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <profiles>
<profile> diff --git a/modules/enterprise/remoting/cli/pom.xml b/modules/enterprise/remoting/cli/pom.xml index b118a9e..250ee16 100644 --- a/modules/enterprise/remoting/cli/pom.xml +++ b/modules/enterprise/remoting/cli/pom.xml @@ -81,7 +81,7 @@ <artifactId>commons-lang</artifactId> <version>2.4</version> <scope>test</scope> - </dependency> + </dependency> </dependencies>
<build> @@ -335,7 +335,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/container/pom.xml b/modules/enterprise/server/container/pom.xml index d51c61d..793e85b 100644 --- a/modules/enterprise/server/container/pom.xml +++ b/modules/enterprise/server/container/pom.xml @@ -110,7 +110,11 @@ <type>zip</type> <!-- NOTE: The version is defined in the root POM's dependencyManagement section. --> </dependency> - + <dependency> + <groupId>org.codehaus.groovy</groupId> + <artifactId>groovy-all</artifactId> + <version>1.7.3</version> + </dependency> </dependencies>
<build> @@ -347,11 +351,109 @@
</executions> </plugin> - - </plugins> - </build> + </plugins> + </build> </profile> - + + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-merge</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-merge datafile="${project.build.directory}/cobertura/cobertura.ser"> + <fileset dir="../../../../"> + <include name="**/cobertura.ser"/> + </fileset> + </cobertura-merge> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.codehaus.groovy.maven</groupId> + <artifactId>gmaven-plugin</artifactId> + <executions> + <execution> + <phase>post-integration-test</phase> + <goals> + <goal>execute</goal> + </goals> + <configuration> + <source> + import java.util.regex.Pattern + import java.util.regex.Matcher + + def repClos + def list = new ArrayList() + + Pattern sourceCodeFolder = Pattern.compile(".*/src/main/java") + Pattern sourceCodeFile = Pattern.compile('.*/src/main/java/(.*.java)') + + list.add("--datafile") + list.add("${project.build.directory}/cobertura/cobertura.ser") + list.add("--destination") + list.add("${project.build.directory}/site/cobertura") + + repClosFile = { + Matcher matcher = sourceCodeFile.matcher(it.canonicalPath) + if (matcher.matches()){ + list.add(matcher[0][1]) + } + + if (it.isDirectory()){ + it.eachFile(repClosFile) + } + } + + repClosDir = { + Matcher matcher = sourceCodeFolder.matcher(it.canonicalPath) + if (matcher.matches()){ + list.add("--basedir") + list.add(it.canonicalPath) + it.eachFile(repClosFile) + } + it.eachDir(repClosDir); + } + + def ear = new File("${project.build.directory}/../../../../") + repClosDir(ear) + + net.sourceforge.cobertura.reporting.Main.main((String[]) list) + </source> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/jar/pom.xml b/modules/enterprise/server/jar/pom.xml index b54dfd8..697056a 100644 --- a/modules/enterprise/server/jar/pom.xml +++ b/modules/enterprise/server/jar/pom.xml @@ -349,7 +349,7 @@ <version>${jboss-embeddable-ejb3.version}</version> <scope>test</scope> </dependency> - + <!-- NOTE: The remaining test deps correspond to the classes contained in hibernate-all.jar and thirdparty-all.jar. -->
<dependency> @@ -407,7 +407,7 @@ <version>1.3</version> <scope>test</scope> </dependency> - + </dependencies>
<build> @@ -483,10 +483,10 @@ Build-OS-Version=${os.version} </executions> </plugin>
- <plugin> - <artifactId>maven-surefire-plugin</artifactId> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> <!-- Everything but the web service tests, this is the standard test execution --> - <configuration> + <configuration> <excludes> <exclude>com/**/*.java</exclude> </excludes> @@ -496,9 +496,9 @@ Build-OS-Version=${os.version} <deploymentDirectory>target/classes</deploymentDirectory> <hibernate.dialect>${rhq.test.ds.hibernate-dialect}</hibernate.dialect> </systemPropertyVariables> - <additionalClasspathElements> + <additionalClasspathElements> <!-- The below is required for tests to run against Oracle. --> - <additionalClasspathElement>${settings.localRepository}/com/oracle/ojdbc5/${ojdbc5.version}/ojdbc5-${ojdbc5.version}.jar</additionalClasspathElement> + <additionalClasspathElement>${settings.localRepository}/com/oracle/ojdbc5/${ojdbc5.version}/ojdbc5-${ojdbc5.version}.jar</additionalClasspathElement> </additionalClasspathElements> </configuration> </plugin> @@ -693,7 +693,93 @@ Build-OS-Version=${os.version} </build>
</profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + <exclude name="**/DynamicConfigurationPropertyLocal.class" /> + <exclude name="**/DynamicConfigurationPropertyBean.class" /> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/plugins/alert-operations/pom.xml b/modules/enterprise/server/plugins/alert-operations/pom.xml index e6019b8..5946922 100644 --- a/modules/enterprise/server/plugins/alert-operations/pom.xml +++ b/modules/enterprise/server/plugins/alert-operations/pom.xml @@ -35,7 +35,6 @@ </exclusion> </exclusions> </dependency> - </dependencies>
<build> @@ -187,7 +186,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/plugins/groovy-script/pom.xml b/modules/enterprise/server/plugins/groovy-script/pom.xml index 1abb9b3..e382b3e 100644 --- a/modules/enterprise/server/plugins/groovy-script/pom.xml +++ b/modules/enterprise/server/plugins/groovy-script/pom.xml @@ -216,7 +216,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/groovy"> + <include name="**/*.groovy" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
<repositories> diff --git a/modules/enterprise/server/plugins/jboss-software/pom.xml b/modules/enterprise/server/plugins/jboss-software/pom.xml index 8d1e368..3f65589 100644 --- a/modules/enterprise/server/plugins/jboss-software/pom.xml +++ b/modules/enterprise/server/plugins/jboss-software/pom.xml @@ -147,7 +147,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>runtime</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/plugins/rhnhosted/pom.xml b/modules/enterprise/server/plugins/rhnhosted/pom.xml index 6634e78..b1b201d 100644 --- a/modules/enterprise/server/plugins/rhnhosted/pom.xml +++ b/modules/enterprise/server/plugins/rhnhosted/pom.xml @@ -88,7 +88,8 @@ <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>${jaxb-impl.version}</version> - </dependency> + </dependency> + </dependencies>
@@ -260,7 +261,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>runtime</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/enterprise/server/plugins/url/pom.xml b/modules/enterprise/server/plugins/url/pom.xml index 9ada86c..9dd8df4 100644 --- a/modules/enterprise/server/plugins/url/pom.xml +++ b/modules/enterprise/server/plugins/url/pom.xml @@ -152,7 +152,92 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/enterprise/server/xml-schemas/pom.xml b/modules/enterprise/server/xml-schemas/pom.xml index 5990106..8577a40 100644 --- a/modules/enterprise/server/xml-schemas/pom.xml +++ b/modules/enterprise/server/xml-schemas/pom.xml @@ -25,7 +25,6 @@ </properties>
<dependencies> - <dependency> <groupId>${rhq.groupId}</groupId> <artifactId>rhq-core-domain</artifactId> @@ -227,7 +226,91 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>prepare-package</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/helpers/pom.xml b/modules/helpers/pom.xml index a26b7f2..b5fc339 100644 --- a/modules/helpers/pom.xml +++ b/modules/helpers/pom.xml @@ -24,12 +24,16 @@ <scm.module.path>modules/helpers/</scm.module.path> </properties>
- <dependencies> - - - + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> </dependencies>
+ <modules>
<!-- plugins that are used by both enterprise and embedded --> diff --git a/modules/plugins/JBossOSGi/pom.xml b/modules/plugins/JBossOSGi/pom.xml index 38828c4..8debc52 100644 --- a/modules/plugins/JBossOSGi/pom.xml +++ b/modules/plugins/JBossOSGi/pom.xml @@ -165,7 +165,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -192,7 +193,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -210,7 +211,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/aliases/pom.xml b/modules/plugins/aliases/pom.xml index 4a4c20c..d670a77 100644 --- a/modules/plugins/aliases/pom.xml +++ b/modules/plugins/aliases/pom.xml @@ -222,7 +222,7 @@ </build> </profile>
- <profile> + <profile> <id>cobertura</id> <activation> <activeByDefault>false</activeByDefault> @@ -230,7 +230,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -257,14 +258,14 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> <include name="**/*.class"/> </fileset> </cobertura-instrument> - </tasks> + </tasks> </configuration> <goals> <goal>run</goal> @@ -275,7 +276,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> @@ -305,9 +306,6 @@ </plugin> </plugins> </build> - </profile> - - + </profile> </profiles> - </project> diff --git a/modules/plugins/ant-bundle/pom.xml b/modules/plugins/ant-bundle/pom.xml index 812bba1..96a571a 100644 --- a/modules/plugins/ant-bundle/pom.xml +++ b/modules/plugins/ant-bundle/pom.xml @@ -281,7 +281,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -308,7 +309,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -326,7 +327,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/apache/pom.xml b/modules/plugins/apache/pom.xml index ef266c1..96814b5 100644 --- a/modules/plugins/apache/pom.xml +++ b/modules/plugins/apache/pom.xml @@ -108,15 +108,14 @@ <profiles> <profile> <id>integration-tests</id> - <!-- + <activation> <property> <name>maven.test.skip</name> <value>!true</value> </property> </activation> - --> - + <build> <plugins> <!-- Integration testing voodoo to load and test this plugin with its plugin dependencies --> @@ -128,7 +127,7 @@ <configuration> <tasks> <echo>Setting up plugin dependencies for ${project.artifactId}-${project.version}.jar...</echo> - <property name="settings.localRepository" location="${user.home}/.m2/repository/net/sourceforge/cobertura/cobertura/1.9.4.1/" /> + <property name="settings.localRepository" location="${user.home}/.m2/repository/" /> <mkdir dir="target/itest" /> <mkdir dir="target/itest/plugins" /> <mkdir dir="target/itest/lib" /> @@ -287,7 +286,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -314,7 +314,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -332,7 +332,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/byteman/pom.xml b/modules/plugins/byteman/pom.xml index edae303..2888195 100644 --- a/modules/plugins/byteman/pom.xml +++ b/modules/plugins/byteman/pom.xml @@ -247,7 +247,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -274,7 +275,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -292,7 +293,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/cobbler/pom.xml b/modules/plugins/cobbler/pom.xml index d4ea9bb..f239545 100644 --- a/modules/plugins/cobbler/pom.xml +++ b/modules/plugins/cobbler/pom.xml @@ -33,6 +33,7 @@ <artifactId>rhq-augeas-plugin</artifactId> <version>${project.version}</version> </dependency> + <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> @@ -256,7 +257,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -283,7 +285,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -301,7 +303,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/cron/pom.xml b/modules/plugins/cron/pom.xml index 3869f7f..3ad74be 100644 --- a/modules/plugins/cron/pom.xml +++ b/modules/plugins/cron/pom.xml @@ -220,7 +220,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -247,7 +248,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -265,7 +266,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/database/pom.xml b/modules/plugins/database/pom.xml index d4b383a..6bdbfcb 100644 --- a/modules/plugins/database/pom.xml +++ b/modules/plugins/database/pom.xml @@ -102,7 +102,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -129,7 +130,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -147,7 +148,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/filetemplate-bundle/pom.xml b/modules/plugins/filetemplate-bundle/pom.xml index e7134fe..55b7b7d 100644 --- a/modules/plugins/filetemplate-bundle/pom.xml +++ b/modules/plugins/filetemplate-bundle/pom.xml @@ -255,6 +255,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -281,7 +282,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -299,7 +300,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/grub/pom.xml b/modules/plugins/grub/pom.xml index 787131c..257f174 100644 --- a/modules/plugins/grub/pom.xml +++ b/modules/plugins/grub/pom.xml @@ -220,6 +220,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -246,7 +247,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -264,7 +265,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/hadoop/pom.xml b/modules/plugins/hadoop/pom.xml index fb74b41..e74609a 100644 --- a/modules/plugins/hadoop/pom.xml +++ b/modules/plugins/hadoop/pom.xml @@ -128,7 +128,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -155,7 +156,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -173,7 +174,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/hibernate/pom.xml b/modules/plugins/hibernate/pom.xml index f852671..e6cea36 100644 --- a/modules/plugins/hibernate/pom.xml +++ b/modules/plugins/hibernate/pom.xml @@ -247,7 +247,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -274,7 +275,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -292,7 +293,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/hosts/pom.xml b/modules/plugins/hosts/pom.xml index e7d4d5b..c1f68e8 100644 --- a/modules/plugins/hosts/pom.xml +++ b/modules/plugins/hosts/pom.xml @@ -230,7 +230,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -257,7 +258,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -275,7 +276,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/iis/pom.xml b/modules/plugins/iis/pom.xml index e2f2c75..fa03477 100644 --- a/modules/plugins/iis/pom.xml +++ b/modules/plugins/iis/pom.xml @@ -206,7 +206,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -233,7 +234,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -251,7 +252,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/irc/pom.xml b/modules/plugins/irc/pom.xml index d56d15a..b949586 100644 --- a/modules/plugins/irc/pom.xml +++ b/modules/plugins/irc/pom.xml @@ -140,7 +140,7 @@ </build>
</profile> - <profile> + <profile> <id>cobertura</id> <activation> <activeByDefault>false</activeByDefault> @@ -148,7 +148,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -175,7 +176,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -193,7 +194,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jboss-as-5/pom.xml b/modules/plugins/jboss-as-5/pom.xml index ef4aff1..e788ecb 100644 --- a/modules/plugins/jboss-as-5/pom.xml +++ b/modules/plugins/jboss-as-5/pom.xml @@ -637,7 +637,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -664,7 +665,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -682,7 +683,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jboss-as/pom.xml b/modules/plugins/jboss-as/pom.xml index 77e628e..e39c240 100644 --- a/modules/plugins/jboss-as/pom.xml +++ b/modules/plugins/jboss-as/pom.xml @@ -358,6 +358,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -384,7 +385,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -402,7 +403,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jboss-cache-v3/pom.xml b/modules/plugins/jboss-cache-v3/pom.xml index 1c024f7..8c64a30 100644 --- a/modules/plugins/jboss-cache-v3/pom.xml +++ b/modules/plugins/jboss-cache-v3/pom.xml @@ -568,7 +568,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -595,7 +596,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -613,7 +614,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jboss-cache/pom.xml b/modules/plugins/jboss-cache/pom.xml index e5a2f5b..6344b88 100644 --- a/modules/plugins/jboss-cache/pom.xml +++ b/modules/plugins/jboss-cache/pom.xml @@ -222,7 +222,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -249,7 +250,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -267,7 +268,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jdbctrace/pom.xml b/modules/plugins/jdbctrace/pom.xml index 6601d08..6b918f4 100644 --- a/modules/plugins/jdbctrace/pom.xml +++ b/modules/plugins/jdbctrace/pom.xml @@ -276,7 +276,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -303,7 +304,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -321,7 +322,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jira/pom.xml b/modules/plugins/jira/pom.xml index 8551a65..ba59116 100644 --- a/modules/plugins/jira/pom.xml +++ b/modules/plugins/jira/pom.xml @@ -325,6 +325,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -351,7 +352,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -369,7 +370,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/jmx/pom.xml b/modules/plugins/jmx/pom.xml index 0d9c538..55b5fdb 100644 --- a/modules/plugins/jmx/pom.xml +++ b/modules/plugins/jmx/pom.xml @@ -262,7 +262,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -289,7 +290,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -307,7 +308,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/kickstart/pom.xml b/modules/plugins/kickstart/pom.xml index c8a04aa..2831c16 100644 --- a/modules/plugins/kickstart/pom.xml +++ b/modules/plugins/kickstart/pom.xml @@ -116,7 +116,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -143,7 +144,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -161,7 +162,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/lsof/pom.xml b/modules/plugins/lsof/pom.xml index df802e2..7cf372b 100644 --- a/modules/plugins/lsof/pom.xml +++ b/modules/plugins/lsof/pom.xml @@ -248,6 +248,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -274,7 +275,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -292,7 +293,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/mysql/pom.xml b/modules/plugins/mysql/pom.xml index ad260d7..ba3514a 100644 --- a/modules/plugins/mysql/pom.xml +++ b/modules/plugins/mysql/pom.xml @@ -250,6 +250,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -276,7 +277,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -294,7 +295,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/netservices/pom.xml b/modules/plugins/netservices/pom.xml index 66e1ec5..913afcb 100644 --- a/modules/plugins/netservices/pom.xml +++ b/modules/plugins/netservices/pom.xml @@ -256,7 +256,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -283,7 +284,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -301,7 +302,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/nss/pom.xml b/modules/plugins/nss/pom.xml index b63e10f..1cfe880 100644 --- a/modules/plugins/nss/pom.xml +++ b/modules/plugins/nss/pom.xml @@ -99,7 +99,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -126,7 +127,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -144,7 +145,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/onewire/pom.xml b/modules/plugins/onewire/pom.xml index 3fa0f08..16165d5 100644 --- a/modules/plugins/onewire/pom.xml +++ b/modules/plugins/onewire/pom.xml @@ -160,7 +160,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -187,7 +188,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -205,7 +206,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/oracle/pom.xml b/modules/plugins/oracle/pom.xml index 6551f7f..b425488 100644 --- a/modules/plugins/oracle/pom.xml +++ b/modules/plugins/oracle/pom.xml @@ -255,7 +255,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -282,7 +283,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -300,7 +301,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/platform/pom.xml b/modules/plugins/platform/pom.xml index 5e5c810..c688558 100644 --- a/modules/plugins/platform/pom.xml +++ b/modules/plugins/platform/pom.xml @@ -205,7 +205,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -232,7 +233,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -250,7 +251,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/postfix/pom.xml b/modules/plugins/postfix/pom.xml index 059f197..837e1e4 100644 --- a/modules/plugins/postfix/pom.xml +++ b/modules/plugins/postfix/pom.xml @@ -228,7 +228,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -255,7 +256,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -273,7 +274,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/postgres/pom.xml b/modules/plugins/postgres/pom.xml index b227b4a..145ae59 100644 --- a/modules/plugins/postgres/pom.xml +++ b/modules/plugins/postgres/pom.xml @@ -248,7 +248,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -275,7 +276,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -293,7 +294,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/rhq-agent/pom.xml b/modules/plugins/rhq-agent/pom.xml index df376e9..afd2a38 100644 --- a/modules/plugins/rhq-agent/pom.xml +++ b/modules/plugins/rhq-agent/pom.xml @@ -221,6 +221,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -247,7 +248,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -265,7 +266,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/rhq-server/pom.xml b/modules/plugins/rhq-server/pom.xml index 1b50ec5..40a19c5 100644 --- a/modules/plugins/rhq-server/pom.xml +++ b/modules/plugins/rhq-server/pom.xml @@ -247,6 +247,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -273,7 +274,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -291,7 +292,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/samba/pom.xml b/modules/plugins/samba/pom.xml index 0a4becf..1208f7f 100644 --- a/modules/plugins/samba/pom.xml +++ b/modules/plugins/samba/pom.xml @@ -229,6 +229,7 @@ <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -255,7 +256,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -273,7 +274,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/script/pom.xml b/modules/plugins/script/pom.xml index c61942f..242913a 100644 --- a/modules/plugins/script/pom.xml +++ b/modules/plugins/script/pom.xml @@ -200,7 +200,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -227,7 +228,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -245,7 +246,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/script2/pom.xml b/modules/plugins/script2/pom.xml index 5a76049..4666ae1 100644 --- a/modules/plugins/script2/pom.xml +++ b/modules/plugins/script2/pom.xml @@ -179,7 +179,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -206,7 +207,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -224,7 +225,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/services/pom.xml b/modules/plugins/services/pom.xml index e48e3d7..f27b3ec 100644 --- a/modules/plugins/services/pom.xml +++ b/modules/plugins/services/pom.xml @@ -123,7 +123,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -150,7 +151,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -168,7 +169,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/snmptrapd/pom.xml b/modules/plugins/snmptrapd/pom.xml index 035eaba..072985e 100644 --- a/modules/plugins/snmptrapd/pom.xml +++ b/modules/plugins/snmptrapd/pom.xml @@ -160,7 +160,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -187,7 +188,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -205,7 +206,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/sshd/pom.xml b/modules/plugins/sshd/pom.xml index f05a21e..08a2ef1 100644 --- a/modules/plugins/sshd/pom.xml +++ b/modules/plugins/sshd/pom.xml @@ -220,7 +220,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -247,7 +248,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -265,7 +266,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/sudoers/pom.xml b/modules/plugins/sudoers/pom.xml index 8aaf25c..251d7f3 100644 --- a/modules/plugins/sudoers/pom.xml +++ b/modules/plugins/sudoers/pom.xml @@ -217,7 +217,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -244,7 +245,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -262,7 +263,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/tomcat/pom.xml b/modules/plugins/tomcat/pom.xml index 8d53a0a..88c9156 100644 --- a/modules/plugins/tomcat/pom.xml +++ b/modules/plugins/tomcat/pom.xml @@ -214,7 +214,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -241,7 +242,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -259,7 +260,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/twitter/pom.xml b/modules/plugins/twitter/pom.xml index f94b21b..ba123b3 100644 --- a/modules/plugins/twitter/pom.xml +++ b/modules/plugins/twitter/pom.xml @@ -140,7 +140,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -167,7 +168,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -185,7 +186,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/plugins/virt/pom.xml b/modules/plugins/virt/pom.xml index 35082d0..757207c 100644 --- a/modules/plugins/virt/pom.xml +++ b/modules/plugins/virt/pom.xml @@ -288,7 +288,8 @@ <build> <plugins> <plugin> - <artifactId>maven-antrun-plugin</artifactId> + <artifactId>maven-antrun-plugin</artifactId> + <version>1.1</version> <dependencies> <dependency> <groupId>net.sourceforge.cobertura</groupId> @@ -315,7 +316,7 @@ <!-- create a properties file and save there location of cobertura data file--> <touch file="target/classes/cobertura.properties"/> <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- instrument all classes in target/classes directory --> <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> <fileset dir="${project.build.directory}/classes"> @@ -333,7 +334,7 @@ <phase>post-integration-test</phase> <configuration> <tasks> - <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <taskdef classpathref="maven.plugin.classpath" resource="tasks.properties" /> <!-- prepare directory structure for cobertura--> <mkdir dir="target/cobertura" /> <mkdir dir="target/site/cobertura" /> diff --git a/modules/test-utils/pom.xml b/modules/test-utils/pom.xml index 5f96131..c873303 100644 --- a/modules/test-utils/pom.xml +++ b/modules/test-utils/pom.xml @@ -27,5 +27,11 @@ <artifactId>commons-beanutils</artifactId> <version>1.8.2</version> </dependency> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/pom.xml b/pom.xml index 497a520..686608a 100644 --- a/pom.xml +++ b/pom.xml @@ -146,7 +146,7 @@
<!-- NOTE: The below line is a workaround for a Maven bug, where it does not expand settings.* properties used in the distributionManagement section of the POM. --> - <localRepository>${user.home}/.m2/repository</localRepository> + <localRepository>${user.home}/.m2/repository</localRepository> </properties>
@@ -413,7 +413,6 @@ <artifactId>jna</artifactId> <version>${jna.version}</version> </dependency> - </dependencies>
</dependencyManagement> @@ -457,6 +456,13 @@ <scope>provided</scope> </dependency>
+ <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies>
@@ -1144,12 +1150,7 @@ <inherited>true</inherited> </plugin> --> - <plugin> - <groupId>org.codehaus.mojo</groupId> - <artifactId>cobertura-maven-plugin</artifactId> - <version>2.4</version> - <inherited>true</inherited> - </plugin> + <plugin> <!-- must be last plugin in the list --> <groupId>org.codehaus.mojo</groupId>
commit 34846f927d07ee5e90182f4594fa0468a7c08c69 Author: Filip Drabek fdrabek@dhcp-lab-136.englab.brq.redhat.com Date: Thu Sep 23 13:28:48 2010 +0200
Settings of cobertura for rhq plugins.
diff --git a/modules/plugins/JBossOSGi/pom.xml b/modules/plugins/JBossOSGi/pom.xml index fa6dde6..38828c4 100644 --- a/modules/plugins/JBossOSGi/pom.xml +++ b/modules/plugins/JBossOSGi/pom.xml @@ -157,6 +157,90 @@ </plugins> </build> </profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/aliases/pom.xml b/modules/plugins/aliases/pom.xml index 0370302..4a4c20c 100644 --- a/modules/plugins/aliases/pom.xml +++ b/modules/plugins/aliases/pom.xml @@ -222,6 +222,92 @@ </build> </profile>
+ <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + + </profiles>
</project> diff --git a/modules/plugins/ant-bundle/pom.xml b/modules/plugins/ant-bundle/pom.xml index d7e6d8a..812bba1 100644 --- a/modules/plugins/ant-bundle/pom.xml +++ b/modules/plugins/ant-bundle/pom.xml @@ -273,6 +273,90 @@ </build> </profile>
+ <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/apache/pom.xml b/modules/plugins/apache/pom.xml index 9f46fc9..ef266c1 100644 --- a/modules/plugins/apache/pom.xml +++ b/modules/plugins/apache/pom.xml @@ -128,7 +128,7 @@ <configuration> <tasks> <echo>Setting up plugin dependencies for ${project.artifactId}-${project.version}.jar...</echo> - <property name="settings.localRepository" location="${user.home}/.m2/repository" /> + <property name="settings.localRepository" location="${user.home}/.m2/repository/net/sourceforge/cobertura/cobertura/1.9.4.1/" /> <mkdir dir="target/itest" /> <mkdir dir="target/itest/plugins" /> <mkdir dir="target/itest/lib" /> @@ -279,6 +279,90 @@ </build> </profile>
+ <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/byteman/pom.xml b/modules/plugins/byteman/pom.xml index cb324cc..edae303 100644 --- a/modules/plugins/byteman/pom.xml +++ b/modules/plugins/byteman/pom.xml @@ -239,7 +239,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/cobbler/pom.xml b/modules/plugins/cobbler/pom.xml index 1082bb3..d4ea9bb 100644 --- a/modules/plugins/cobbler/pom.xml +++ b/modules/plugins/cobbler/pom.xml @@ -248,7 +248,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/cron/pom.xml b/modules/plugins/cron/pom.xml index 9371766..3869f7f 100644 --- a/modules/plugins/cron/pom.xml +++ b/modules/plugins/cron/pom.xml @@ -212,7 +212,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/database/pom.xml b/modules/plugins/database/pom.xml index c72f79a..d4b383a 100644 --- a/modules/plugins/database/pom.xml +++ b/modules/plugins/database/pom.xml @@ -94,7 +94,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/filetemplate-bundle/pom.xml b/modules/plugins/filetemplate-bundle/pom.xml index 0b85a57..e7134fe 100644 --- a/modules/plugins/filetemplate-bundle/pom.xml +++ b/modules/plugins/filetemplate-bundle/pom.xml @@ -246,7 +246,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/grub/pom.xml b/modules/plugins/grub/pom.xml index d783ffc..787131c 100644 --- a/modules/plugins/grub/pom.xml +++ b/modules/plugins/grub/pom.xml @@ -211,7 +211,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/hadoop/pom.xml b/modules/plugins/hadoop/pom.xml index 7fc2837..fb74b41 100644 --- a/modules/plugins/hadoop/pom.xml +++ b/modules/plugins/hadoop/pom.xml @@ -120,6 +120,90 @@ </build>
</profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/hibernate/pom.xml b/modules/plugins/hibernate/pom.xml index a7bac31..f852671 100644 --- a/modules/plugins/hibernate/pom.xml +++ b/modules/plugins/hibernate/pom.xml @@ -239,7 +239,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/hosts/pom.xml b/modules/plugins/hosts/pom.xml index ef32374..e7d4d5b 100644 --- a/modules/plugins/hosts/pom.xml +++ b/modules/plugins/hosts/pom.xml @@ -222,7 +222,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/hudson/pom.xml b/modules/plugins/hudson/pom.xml index 68eae1a..ed2fffc 100644 --- a/modules/plugins/hudson/pom.xml +++ b/modules/plugins/hudson/pom.xml @@ -72,9 +72,7 @@ </execution> </executions> </plugin> - </plugins> </build> - </project>
diff --git a/modules/plugins/iis/pom.xml b/modules/plugins/iis/pom.xml index ad90e83..e2f2c75 100644 --- a/modules/plugins/iis/pom.xml +++ b/modules/plugins/iis/pom.xml @@ -198,7 +198,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/irc/pom.xml b/modules/plugins/irc/pom.xml index ab18766..d56d15a 100644 --- a/modules/plugins/irc/pom.xml +++ b/modules/plugins/irc/pom.xml @@ -140,6 +140,90 @@ </build>
</profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/jboss-as-5/pom.xml b/modules/plugins/jboss-as-5/pom.xml index 2766efd..ef4aff1 100644 --- a/modules/plugins/jboss-as-5/pom.xml +++ b/modules/plugins/jboss-as-5/pom.xml @@ -629,7 +629,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/jboss-as/pom.xml b/modules/plugins/jboss-as/pom.xml index 31d5fbc..77e628e 100644 --- a/modules/plugins/jboss-as/pom.xml +++ b/modules/plugins/jboss-as/pom.xml @@ -349,7 +349,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/jboss-cache-v3/pom.xml b/modules/plugins/jboss-cache-v3/pom.xml index b09a9aa..1c024f7 100644 --- a/modules/plugins/jboss-cache-v3/pom.xml +++ b/modules/plugins/jboss-cache-v3/pom.xml @@ -560,7 +560,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/jboss-cache/pom.xml b/modules/plugins/jboss-cache/pom.xml index e9dca27..e5a2f5b 100644 --- a/modules/plugins/jboss-cache/pom.xml +++ b/modules/plugins/jboss-cache/pom.xml @@ -214,7 +214,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/jdbctrace/pom.xml b/modules/plugins/jdbctrace/pom.xml index c7ab30c..6601d08 100644 --- a/modules/plugins/jdbctrace/pom.xml +++ b/modules/plugins/jdbctrace/pom.xml @@ -268,7 +268,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/jira/pom.xml b/modules/plugins/jira/pom.xml index 8e0a879..8551a65 100644 --- a/modules/plugins/jira/pom.xml +++ b/modules/plugins/jira/pom.xml @@ -316,7 +316,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/jmx/pom.xml b/modules/plugins/jmx/pom.xml index 83e3030..0d9c538 100644 --- a/modules/plugins/jmx/pom.xml +++ b/modules/plugins/jmx/pom.xml @@ -254,7 +254,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/kickstart/pom.xml b/modules/plugins/kickstart/pom.xml index a1a61cf..c8a04aa 100644 --- a/modules/plugins/kickstart/pom.xml +++ b/modules/plugins/kickstart/pom.xml @@ -108,6 +108,89 @@ </plugins> </build> </profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles> - </project> diff --git a/modules/plugins/lsof/pom.xml b/modules/plugins/lsof/pom.xml index 0667659..df802e2 100644 --- a/modules/plugins/lsof/pom.xml +++ b/modules/plugins/lsof/pom.xml @@ -239,7 +239,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/mysql/pom.xml b/modules/plugins/mysql/pom.xml index 5152236..ad260d7 100644 --- a/modules/plugins/mysql/pom.xml +++ b/modules/plugins/mysql/pom.xml @@ -241,7 +241,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/netservices/pom.xml b/modules/plugins/netservices/pom.xml index 9f35dbf..66e1ec5 100644 --- a/modules/plugins/netservices/pom.xml +++ b/modules/plugins/netservices/pom.xml @@ -248,7 +248,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/nss/pom.xml b/modules/plugins/nss/pom.xml index 0b8578a..b63e10f 100644 --- a/modules/plugins/nss/pom.xml +++ b/modules/plugins/nss/pom.xml @@ -91,6 +91,90 @@ </plugins> </build> </profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/onewire/pom.xml b/modules/plugins/onewire/pom.xml index 8b2fa39..3fa0f08 100644 --- a/modules/plugins/onewire/pom.xml +++ b/modules/plugins/onewire/pom.xml @@ -152,7 +152,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/oracle/pom.xml b/modules/plugins/oracle/pom.xml index be37d2b..6551f7f 100644 --- a/modules/plugins/oracle/pom.xml +++ b/modules/plugins/oracle/pom.xml @@ -247,7 +247,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/perftest/pom.xml b/modules/plugins/perftest/pom.xml index 136770c..4f56cf4 100644 --- a/modules/plugins/perftest/pom.xml +++ b/modules/plugins/perftest/pom.xml @@ -138,5 +138,5 @@ <layout>legacy</layout> </pluginRepository> </pluginRepositories> - + </project> diff --git a/modules/plugins/platform/pom.xml b/modules/plugins/platform/pom.xml index 5597a30..5e5c810 100644 --- a/modules/plugins/platform/pom.xml +++ b/modules/plugins/platform/pom.xml @@ -197,7 +197,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/pom.xml b/modules/plugins/pom.xml index 880254c..6220581 100644 --- a/modules/plugins/pom.xml +++ b/modules/plugins/pom.xml @@ -76,6 +76,12 @@ <scope>provided</scope> <!-- by RHQ container --> </dependency>
+ <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> </dependencies>
<!-- !!! --> diff --git a/modules/plugins/postfix/pom.xml b/modules/plugins/postfix/pom.xml index 2130abe..059f197 100644 --- a/modules/plugins/postfix/pom.xml +++ b/modules/plugins/postfix/pom.xml @@ -220,7 +220,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/postgres/pom.xml b/modules/plugins/postgres/pom.xml index beab355..b227b4a 100644 --- a/modules/plugins/postgres/pom.xml +++ b/modules/plugins/postgres/pom.xml @@ -240,7 +240,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/rhq-agent/pom.xml b/modules/plugins/rhq-agent/pom.xml index 3aa3bb6..df376e9 100644 --- a/modules/plugins/rhq-agent/pom.xml +++ b/modules/plugins/rhq-agent/pom.xml @@ -212,6 +212,89 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles> </project> \ No newline at end of file diff --git a/modules/plugins/rhq-server/pom.xml b/modules/plugins/rhq-server/pom.xml index d0ef9fe..1b50ec5 100644 --- a/modules/plugins/rhq-server/pom.xml +++ b/modules/plugins/rhq-server/pom.xml @@ -238,6 +238,89 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles> </project> \ No newline at end of file diff --git a/modules/plugins/samba/pom.xml b/modules/plugins/samba/pom.xml index a338a98..0a4becf 100644 --- a/modules/plugins/samba/pom.xml +++ b/modules/plugins/samba/pom.xml @@ -220,7 +220,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/script/pom.xml b/modules/plugins/script/pom.xml index 05cb816..c61942f 100644 --- a/modules/plugins/script/pom.xml +++ b/modules/plugins/script/pom.xml @@ -192,7 +192,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/script2/pom.xml b/modules/plugins/script2/pom.xml index ed7473b..5a76049 100644 --- a/modules/plugins/script2/pom.xml +++ b/modules/plugins/script2/pom.xml @@ -171,6 +171,90 @@ </build>
</profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/services/pom.xml b/modules/plugins/services/pom.xml index f6b8556..e48e3d7 100644 --- a/modules/plugins/services/pom.xml +++ b/modules/plugins/services/pom.xml @@ -115,6 +115,90 @@ </build>
</profile> + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/snmptrapd/pom.xml b/modules/plugins/snmptrapd/pom.xml index 93bb45a..035eaba 100644 --- a/modules/plugins/snmptrapd/pom.xml +++ b/modules/plugins/snmptrapd/pom.xml @@ -152,7 +152,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/sshd/pom.xml b/modules/plugins/sshd/pom.xml index a68e444..f05a21e 100644 --- a/modules/plugins/sshd/pom.xml +++ b/modules/plugins/sshd/pom.xml @@ -212,7 +212,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/sudoers/pom.xml b/modules/plugins/sudoers/pom.xml index 0353f4f..8aaf25c 100644 --- a/modules/plugins/sudoers/pom.xml +++ b/modules/plugins/sudoers/pom.xml @@ -209,7 +209,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> diff --git a/modules/plugins/tomcat/pom.xml b/modules/plugins/tomcat/pom.xml index 4c93bb3..8d53a0a 100644 --- a/modules/plugins/tomcat/pom.xml +++ b/modules/plugins/tomcat/pom.xml @@ -206,7 +206,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project> \ No newline at end of file diff --git a/modules/plugins/twitter/pom.xml b/modules/plugins/twitter/pom.xml index a6fdf4f..f94b21b 100644 --- a/modules/plugins/twitter/pom.xml +++ b/modules/plugins/twitter/pom.xml @@ -131,6 +131,91 @@ </build>
</profile> + + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
diff --git a/modules/plugins/virt/pom.xml b/modules/plugins/virt/pom.xml index c2550aa..35082d0 100644 --- a/modules/plugins/virt/pom.xml +++ b/modules/plugins/virt/pom.xml @@ -280,7 +280,90 @@ </plugins> </build> </profile> - + <profile> + <id>cobertura</id> + <activation> + <activeByDefault>false</activeByDefault> + </activation> + <build> + <plugins> + <plugin> + <artifactId>maven-antrun-plugin</artifactId> + <dependencies> + <dependency> + <groupId>net.sourceforge.cobertura</groupId> + <artifactId>cobertura</artifactId> + <version>1.9.4.1</version> + <scope>test</scope> + </dependency> + </dependencies> + <executions> + <execution> + <id>cobertura-instrument</id> + <phase>pre-integration-test</phase> + <configuration> + <tasks> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/cobertura/backup"/> + <!-- backup all classes so that we can instrument the original classes--> + <copy toDir="target/cobertura/backup" verbose="true" overwrite="true"> + <fileset dir="target/classes"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- create a properties file and save there location of cobertura data file--> + <touch file="target/classes/cobertura.properties"/> + <echo file="target/classes/cobertura.properties">net.sourceforge.cobertura.datafile=${project.build.directory}/cobertura/cobertura.ser</echo> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- instrument all classes in target/classes directory --> + <cobertura-instrument datafile="${project.build.directory}/cobertura/cobertura.ser" todir="${project.build.directory}/classes"> + <fileset dir="${project.build.directory}/classes"> + <include name="**/*.class"/> + </fileset> + </cobertura-instrument> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>cobertura-report</id> + <phase>post-integration-test</phase> + <configuration> + <tasks> + <taskdef classpathref="maven.runtime.classpath" resource="tasks.properties" /> + <!-- prepare directory structure for cobertura--> + <mkdir dir="target/cobertura" /> + <mkdir dir="target/site/cobertura" /> + <!-- restore classes from backup folder to classes folder --> + <copy toDir="target/classes" verbose="true" overwrite="true"> + <fileset dir="target/cobertura/backup"> + <include name="**/*.class" /> + </fileset> + </copy> + <!-- delete backup folder--> + <delete dir="target/cobertura/backup"/> + <!-- create a code coverage report --> + <cobertura-report format="html" datafile="${project.build.directory}/cobertura/cobertura.ser" destdir="${project.build.directory}/site/cobertura"> + <fileset dir="${basedir}/src/main/java"> + <include name="**/*.java" /> + </fileset> + </cobertura-report> + <!-- delete cobertura.properties file --> + <delete file="target/classes/cobertura.properties"/> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> </profiles>
</project>
commit b1efc0296a80ed58d317466a78e141b285290fb1 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 18:03:28 2010 -0400
Initial Manual Add Work
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index 69fed11..d2c971a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@ -68,7 +68,8 @@ public interface ResourceGWTService extends RemoteService { void ignoreResources(Integer[] resourceIds);
void unignoreResources(Integer[] resourceIds); - + List<ResourceError> findResourceErrors(int resourceId);
-} + Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration); +} \ No newline at end of file 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 d6cfdba..97a7d2f 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 @@ -300,9 +300,11 @@ public class ResourceTreeView extends LocatableVLayout { // Update breadcrumbs if (currentViewId != null) { currentViewId.getBreadcrumbs().clear(); - for (int i = parents.length - 1; i >= 0; i--) { - TreeNode n = parents[i]; - adjustBreadcrumb(n, currentViewId); + if (null != parents) { + for (int i = parents.length - 1; i >= 0; i--) { + TreeNode n = parents[i]; + adjustBreadcrumb(n, currentViewId); + } } adjustBreadcrumb(selectedNode, currentViewId); CoreGUI.refreshBreadCrumbTrail(); @@ -456,13 +458,15 @@ public class ResourceTreeView extends LocatableVLayout { for (final ResourceType childType : resourceType.getChildResourceTypes()) { if (childType.isCreatable()) { MenuItem createItem = new MenuItem(childType.getName()); - createChildSubMenu.addItem(createItem); + createItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { ResourceFactoryCreateWizard.showCreateWizard(resource, childType); } });
+ createChildSubMenu.addItem(createItem); + } } createChildMenu.setSubmenu(createChildSubMenu); @@ -472,21 +476,30 @@ public class ResourceTreeView extends LocatableVLayout { // Manually Add Menu MenuItem importChildMenu = new MenuItem("Import"); Menu importChildSubMenu = new Menu(); - for (ResourceType childType : resourceType.getChildResourceTypes()) { + for (final ResourceType childType : resourceType.getChildResourceTypes()) { if (childType.isSupportsManualAdd()) { - importChildSubMenu.addItem(new MenuItem(childType.getName())); - //todo action + MenuItem importItem = new MenuItem(childType.getName()); + + importItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + ResourceFactoryCreateWizard.showImportWizard(resource, childType); + } + }); + + importChildSubMenu.addItem(importItem); } } + if (resourceType.getCategory() == ResourceCategory.PLATFORM) { - loadManuallyAddServersToPlatforms(importChildSubMenu); + loadManuallyAddServersToPlatforms(importChildSubMenu, resource); } + importChildMenu.setSubmenu(importChildSubMenu); importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); resourceContextMenu.addItem(importChildMenu); }
- private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) { + private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu, final Resource resource) { ResourceTypeGWTServiceAsync rts = GWTServiceLookup.getResourceTypeGWTService();
ResourceTypeCriteria criteria = new ResourceTypeCriteria(); @@ -498,9 +511,16 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(PageList<ResourceType> result) { - for (ResourceType type : result) { + for (final ResourceType type : result) { if (type.getParentResourceTypes() == null || type.getParentResourceTypes().isEmpty()) { MenuItem item = new MenuItem(type.getName()); + + item.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + ResourceFactoryCreateWizard.showImportWizard(resource, type); + } + }); + manuallyAddMenu.addItem(item); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java index 84c6b55..5d7fbdc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java @@ -49,6 +49,7 @@ public class ConfigurationStep extends AbstractWizardStep { }
public boolean nextPage() { + wizard.execute(); return true; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java index 0db5af8..a588010 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.factory;
import java.util.Map;
+import com.smartgwt.client.types.TitleOrientation; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.SelectItem; @@ -49,10 +50,17 @@ public class ConfigurationTemplateStep extends AbstractWizardStep {
form = new LocatableDynamicForm("ResFactConfigTemplate");
- TextItem nameItem = new TextItem("resourceName", "Resource Name"); - nameItem.setRequired(true); + TextItem nameItem = null;
- SelectItem templateSelect = new SelectItem("template", "Template"); + if (!this.wizard.isImport()) { + nameItem = new TextItem("resourceName", "New Resource Name"); + nameItem.setWidth(300); + nameItem.setRequired(true); + } + + SelectItem templateSelect = new SelectItem("template", "Connection Property Templates (Choose One)"); + templateSelect.setTitleOrientation(TitleOrientation.TOP); + templateSelect.setWidth(300);
ConfigurationDefinition definition = wizard.getConfigurationDefinition();
@@ -64,9 +72,14 @@ public class ConfigurationTemplateStep extends AbstractWizardStep { templateSelect.setDisabled(true); }
- form.setItems(nameItem, templateSelect); + if (null != nameItem) { + form.setItems(nameItem, templateSelect); + } else { + form.setItems(templateSelect); + }
} + return form; }
@@ -75,7 +88,7 @@ public class ConfigurationTemplateStep extends AbstractWizardStep { }
public String getName() { - return "New Resource"; + return "Resource Information"; }
public Configuration getConfiguration() { 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 bad2058..7968635 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,14 +19,9 @@ 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.List;
import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.widgets.IButton; -import com.smartgwt.client.widgets.events.ClickEvent; -import com.smartgwt.client.widgets.events.ClickHandler;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @@ -48,6 +43,7 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { private ConfigurationDefinition configurationDefinition; private Resource parentResource; private ResourceType createType; + private boolean isImport; // manual add vs. create new child
private WizardView view;
@@ -55,10 +51,11 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { private ConfigurationStep configurationStep;
public ResourceFactoryCreateWizard(Resource parentResource, ResourceType createType, - ConfigurationDefinition configurationDefinition) { + ConfigurationDefinition configurationDefinition, boolean isImport) { this.parentResource = parentResource; this.createType = createType; this.configurationDefinition = configurationDefinition; + this.isImport = isImport;
assert parentResource != null; assert createType != null; @@ -66,8 +63,12 @@ public class ResourceFactoryCreateWizard extends AbstractWizard {
ArrayList<WizardStep> steps = new ArrayList<WizardStep>();
- configurationTemplateStep = new ConfigurationTemplateStep(this); - steps.add(configurationTemplateStep); + // skip the template step if this is an import (no resource name to be gathered) and the + // type has only the default template to offer for user selection. + if (!(this.isImport && this.configurationDefinition.getTemplates().size() < 2)) { + this.configurationTemplateStep = new ConfigurationTemplateStep(this); + steps.add(configurationTemplateStep); + }
configurationStep = new ConfigurationStep(this); steps.add(configurationStep); @@ -76,52 +77,57 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { }
public String getWindowTitle() { - return "Resource Create Wizard"; + return isImport() ? "Import Resource Wizard" : "Resource Create Wizard"; }
public String getTitle() { - return "Create New " + createType.getName(); + return (isImport() ? "Import Resource of Type: " : "Create New Resource of Type: ") + createType.getName(); }
public String getSubtitle() { return null; }
- public List<IButton> getCustomButtons(int step) { - switch (step) { - case 1: - IButton createButton = new IButton("Create"); - createButton.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - execute(); - } - }); - return Collections.singletonList(createButton); - } - return null; - } - - private void execute() { + public void execute() {
- int parentReourceId = parentResource.getId(); + int parentResourceId = parentResource.getId(); int createTypeId = createType.getId(); - String newResourceName = configurationTemplateStep.getResourceName(); Configuration newConfiguration = configurationStep.getConfiguration();
- GWTServiceLookup.getResourceService().createResource(parentReourceId, createTypeId, newResourceName, - newConfiguration, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create new resource", caught); - view.closeDialog(); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Submitted request to create new resource [" - + configurationTemplateStep.getResourceName() + "]", Message.Severity.Info)); - view.closeDialog(); - } - }); + if (isImport) { + GWTServiceLookup.getResourceService().manuallyAddResource(createTypeId, parentResourceId, newConfiguration, + new AsyncCallback<Resource>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to manually add resource", caught); + view.closeDialog(); + } + + public void onSuccess(Resource result) { + CoreGUI.getMessageCenter().notify( + new Message("Submitted request to manually add [" + createType.getName() + "]", + Message.Severity.Info)); + view.closeDialog(); + } + }); + + } else { + String newResourceName = configurationTemplateStep.getResourceName(); + + GWTServiceLookup.getResourceService().createResource(parentResourceId, createTypeId, newResourceName, + newConfiguration, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create new resource", caught); + view.closeDialog(); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Submitted request to create new resource [" + + configurationTemplateStep.getResourceName() + "]", Message.Severity.Info)); + view.closeDialog(); + } + }); + } }
public void display() { @@ -135,7 +141,19 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { new ResourceTypeRepository.TypeLoadedCallback() { public void onTypesLoaded(ResourceType type) { ResourceFactoryCreateWizard wizard = new ResourceFactoryCreateWizard(parentResource, type, type - .getResourceConfigurationDefinition()); + .getResourceConfigurationDefinition(), false); + wizard.display(); + } + }); + } + + public static void showImportWizard(final Resource parentResource, ResourceType childType) { + ResourceTypeRepository.Cache.getInstance().getResourceTypes(childType.getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + ResourceFactoryCreateWizard wizard = new ResourceFactoryCreateWizard(parentResource, type, type + .getPluginConfigurationDefinition(), true); wizard.display(); } }); @@ -146,7 +164,8 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { }
public Configuration getConfiguration() { - return configurationTemplateStep.getConfiguration(); + return (null == configurationTemplateStep) ? this.configurationDefinition.getDefaultTemplate() + .createConfiguration() : configurationTemplateStep.getConfiguration(); }
public Resource getParentResource() { @@ -157,6 +176,10 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { return createType; }
+ public boolean isImport() { + return isImport; + } + public void cancel() { // TODO: revert back to original state } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 071d45c..473a257 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -203,7 +203,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re platform.setChildren(servers); }
- return platforms; + return SerialUtility.prepare(platforms, "ResourceService.findRecentlyAddedResources"); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } @@ -286,4 +286,14 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), "ResourceService.getResourceErrors"); } + + public Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration) { + try { + Resource result = discoveryBoss.manuallyAddResource(getSessionSubject(), resourceTypeId, parentResourceId, + pluginConfiguration); + return SerialUtility.prepare(result, "ResourceService.manuallyAddResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } }
commit b7132dfd737d234ba5f72293ce12c720f769c77a Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 15:06:46 2010 -0400
Disable the experimental browser window logging out of the box
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index ecfac0b..040fc16 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -38,7 +38,8 @@ 2. In hosted mode, the windows are not automatically closed, although you can easily close them manually in the usual way --> - <!-- + <!-- When enabled FireFox is hard to use due to excessive popup window generation + <set-property name="log_WindowLogger" value="ENABLED" /> -->
commit 65926cd08afe48d612622182e56aa2fe93e04f96 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 09:57:45 2010 -0400
ResourceTree Authz work - support for locked nodes - support for autogroups for non-inventory managers. Now that AGs are backed by compat groups it's necessary for non-inv-managers to be able to create and access the private groups that they own. Private groups (aka subject-owned groups) are new, they are basically groups that are tagged with the creating subjectId. Those groups can be created (via a new slsb call) and fetched (via a new ResourceGroupCriteria filter) w/o inventory manager perms. - note: i had to move rhq_subject to auth-schema from authz-schema and slightly change the dbsetup order to make it ok for rhq_resource_group to reference rhq_subject. - schema spec bumped to 2.97 - added ResourceLineageComposite to combine Resource and locked/viewable info.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index a004680..071d45c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -281,7 +281,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } } - + public List<ResourceError> findResourceErrors(int resourceId) { return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), "ResourceService.getResourceErrors");
commit c5e222dff6d8c10b906d04d3847a8a9e3c6941b0 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 15:34:45 2010 +0200
fixing the compilation failure in tests
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java index 6630d4b..8fdc2f7 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java @@ -92,7 +92,7 @@ public class ResourceErrorTest extends AbstractEJB3Test { q.setParameter("resourceId", newResource.getId()); assert q.getResultList().size() == 2;
- q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPES); + q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE); q.setParameter("resourceId", newResource.getId()); q.setParameter("errorType", ResourceErrorType.INVALID_PLUGIN_CONFIGURATION); assert q.getResultList().size() == 2; @@ -129,7 +129,7 @@ public class ResourceErrorTest extends AbstractEJB3Test { assert errors.get(0).getDetail().equals("test detail"); assert errors.get(0).getTimeOccurred() == 12345;
- q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPES); + q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE); q.setParameter("resourceId", newResource.getId()); q.setParameter("errorType", ResourceErrorType.INVALID_PLUGIN_CONFIGURATION); errors = q.getResultList();
commit 4969aa53cf7f5ff45fbb1510d2f110560f3f6a8f Merge: 065319e... 1b86f3a... Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 14:18:01 2010 +0200
Merge branch '_resource-upgrade' into resource-upgrade
commit 1b86f3abaf44ebb4e0d62cb75a559b130500cd9f Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 14:17:46 2010 +0200
BZ 593270 - the new style resource key for apache is <server-root>||<httpd-conf>. Implemented the ResourceUpgradeFacet to upgrade existing resources to that new format.
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index 660f727..ca8f972 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -170,38 +170,24 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
public ResourceUpgradeReport upgrade(ResourceUpgradeContext<PlatformComponent> context) { String inventoriedResourceKey = context.getResourceKey(); - File inventoriedResourceKeyAsPath = new File(inventoriedResourceKey);
- //the resource key we use now is a full path to the httpd.conf. - //in the old version, it was the server root. - //so if the inventoried resource key is a path to a file, - //we know it's a new style resource key. - if (inventoriedResourceKeyAsPath.isFile()) { + //check if the inventoried resource has the old format of the resource key. + //the old format was "server-root", while the new format + //is "server-root||httpd-conf". Checking for "||" in the resource key is therefore + //enough. + if (inventoriedResourceKey.contains("||")) { return null; } + + //all the information we need for the new style resource key is + //actually present in the plugin configuration of the existing resource + //already, so let's just generate the new style resource key from it. + String resourceKey = formatResourceKey(context.getPluginConfiguration());
- Configuration pluginConfiguration = context.getPluginConfiguration(); + ResourceUpgradeReport rep = new ResourceUpgradeReport(); + rep.setNewResourceKey(resourceKey);
- String serverRoot = pluginConfiguration.getSimpleValue("serverRoot", null); - String httpdConf = pluginConfiguration.getSimpleValue("configFile", null); - - String resourceKey = null; - - if (httpdConf != null) { - File httpdConfFile = new File(httpdConf); - if (!httpdConfFile.isAbsolute()) { - httpdConfFile = new File(serverRoot, httpdConf); - } - - resourceKey = httpdConfFile.getPath(); - - ResourceUpgradeReport rep = new ResourceUpgradeReport(); - rep.setNewResourceKey(resourceKey); - - return rep; - } - - return null; + return rep; }
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig, @@ -256,15 +242,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen name = uri.getHost() + ":" + uri.getPort(); }
- String serverRoot = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT) - .getStringValue(); - - String key = FileUtils.getCanonicalPath(serverRoot); - - //BZ 612189 - reverting to the serverRoot as the resource key temporarily until we have the resource - //upgrade functionality ready (BZ 592038). Uncommenting the line below will make the resource key totally unique - //(see BZ 593270). - //key += "|" + httpdConf; + String key = formatResourceKey(pluginConfig);
DiscoveredResourceDetails resourceDetails = new DiscoveredResourceDetails(discoveryContext.getResourceType(), key, name, version, PRODUCT_DESCRIPTION, pluginConfig, processInfo); @@ -455,4 +433,14 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen } return null; } + + private static String formatResourceKey(Configuration pluginConfiguration) { + String serverRoot = pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT).getStringValue(); + String httpdConf = pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF).getStringValue(); + + serverRoot = FileUtils.getCanonicalPath(serverRoot); + httpdConf = FileUtils.getCanonicalPath(httpdConf); + + return serverRoot + "||" + httpdConf; + } }
commit a0edcceda8b63f23cc6570fb1da34251f245f3c0 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 13:35:57 2010 +0200
code formatting
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index c305ec4..660f727 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -21,18 +21,14 @@ package org.rhq.plugins.apache; import java.io.File; import java.io.IOException; import java.net.URI; -import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.rhq.augeas.node.AugeasNode; -import org.rhq.augeas.tree.AugeasTree; import org.rhq.augeas.util.Glob; import org.rhq.augeas.util.GlobFilter; import org.rhq.core.domain.configuration.Configuration; @@ -45,7 +41,6 @@ import org.rhq.core.pluginapi.inventory.ManualAddFacet; import org.rhq.core.pluginapi.inventory.ProcessScanResult; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; -import org.rhq.core.pluginapi.inventory.ManualAddFacet; import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; import org.rhq.core.pluginapi.util.FileUtils; @@ -58,8 +53,8 @@ import org.rhq.plugins.apache.parser.ApacheParserImpl; import org.rhq.plugins.apache.util.ApacheBinaryInfo; import org.rhq.plugins.apache.util.AugeasNodeValueUtil; import org.rhq.plugins.apache.util.HttpdAddressUtility; -import org.rhq.plugins.apache.util.OsProcessUtility; import org.rhq.plugins.apache.util.HttpdAddressUtility.Address; +import org.rhq.plugins.apache.util.OsProcessUtility; import org.rhq.plugins.platform.PlatformComponent; import org.rhq.rhqtransform.impl.PluginDescriptorBasedAugeasConfiguration;
@@ -69,13 +64,14 @@ import org.rhq.rhqtransform.impl.PluginDescriptorBasedAugeasConfiguration; * @author Ian Springer * @author Lukas Krejci */ -public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponent<PlatformComponent>, ManualAddFacet<PlatformComponent>, - ResourceUpgradeFacet<PlatformComponent> { +public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponent<PlatformComponent>, + ManualAddFacet<PlatformComponent>, ResourceUpgradeFacet<PlatformComponent> { private static final String PRODUCT_DESCRIPTION = "Apache Web Server";
private static final Log log = LogFactory.getLog(ApacheServerDiscoveryComponent.class);
- public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws Exception { + public Set<DiscoveredResourceDetails> + discoverResources(ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws Exception { Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
// Process any PC-discovered OS processes... @@ -89,16 +85,16 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen continue; } if (!executablePath.isAbsolute()) { - log.error("Executable path (" + executablePath + ") is not absolute for Apache [" + - process.getProcessInfo() + "]." + - "Please restart Apache specifying an absolute path for the executable."); + log.error("Executable path (" + executablePath + ") is not absolute for Apache [" + + process.getProcessInfo() + "]." + + "Please restart Apache specifying an absolute path for the executable."); continue; } log.debug("Apache executable path: " + executablePath); ApacheBinaryInfo binaryInfo; try { - binaryInfo = ApacheBinaryInfo.getInfo(executablePath.getPath(), - discoveryContext.getSystemInformation()); + binaryInfo = ApacheBinaryInfo + .getInfo(executablePath.getPath(), discoveryContext.getSystemInformation()); } catch (Exception e) { log.error("'" + executablePath + "' is not a valid Apache executable (" + e + ")."); continue; @@ -130,38 +126,40 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen PropertySimple configFile = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF, serverConfigFile); pluginConfig.put(configFile); - - PropertySimple inclusionGlobs = new PropertySimple(PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile); + + PropertySimple inclusionGlobs = new PropertySimple( + PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile); pluginConfig.put(inclusionGlobs); - - ApacheDirectiveTree serverConfig = loadParser(serverConfigFile.getAbsolutePath(),serverRoot); - + + ApacheDirectiveTree serverConfig = loadParser(serverConfigFile.getAbsolutePath(), serverRoot); + String serverUrl = null; String vhostsGlobInclude = null; - + //now check if the httpd.conf doesn't redefine the ServerRoot List<ApacheDirective> serverRoots = serverConfig.search("/ServerRoot"); if (!serverRoots.isEmpty()) { serverRoot = AugeasNodeValueUtil.unescape(serverRoots.get(0).getValuesAsString()); serverRootProp.setValue(serverRoot); - } + } + + serverUrl = getUrl(serverConfig, binaryInfo.getVersion()); + vhostsGlobInclude = scanForGlobInclude(serverConfig);
- serverUrl = getUrl(serverConfig, binaryInfo.getVersion()); - vhostsGlobInclude = scanForGlobInclude(serverConfig); - if (serverUrl != null) { Property urlProp = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL, serverUrl); - pluginConfig.put(urlProp); + pluginConfig.put(urlProp); } - + if (vhostsGlobInclude != null) { - pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_VHOST_FILES_MASK, vhostsGlobInclude)); - }else - { + pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_VHOST_FILES_MASK, + vhostsGlobInclude)); + } else { if (serverConfigFile.exists()) - pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_VHOST_FILES_MASK, serverConfigFile.getParent()+File.separator+"*")); + pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_VHOST_FILES_MASK, + serverConfigFile.getParent() + File.separator + "*")); } - + discoveredResources.add(createResourceDetails(discoveryContext, pluginConfig, process.getProcessInfo(), binaryInfo)); } @@ -202,18 +200,16 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
return rep; } - + return null; }
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig, - ResourceDiscoveryContext<PlatformComponent> discoveryContext) - throws InvalidPluginConfigurationException { + ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws InvalidPluginConfigurationException { validateServerRootAndServerConfigFile(pluginConfig);
- String executablePath = pluginConfig - .getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, - ApacheServerComponent.DEFAULT_EXECUTABLE_PATH); + String executablePath = pluginConfig.getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, + ApacheServerComponent.DEFAULT_EXECUTABLE_PATH); String absoluteExecutablePath = ApacheServerComponent.resolvePathRelativeToServerRoot(pluginConfig, executablePath).getPath(); ApacheBinaryInfo binaryInfo; @@ -222,13 +218,12 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen } catch (Exception e) { throw new InvalidPluginConfigurationException("'" + absoluteExecutablePath + "' is not a valid Apache executable (" + e + "). Please make sure the '" - + ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH - + "' connection property is set correctly."); + + ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH + "' connection property is set correctly."); }
if (!isSupportedVersion(binaryInfo.getVersion())) { - throw new InvalidPluginConfigurationException("Version of Apache executable (" - + binaryInfo.getVersion() + ") is not a supported version; supported versions are 1.3.x and 2.x."); + throw new InvalidPluginConfigurationException("Version of Apache executable (" + binaryInfo.getVersion() + + ") is not a supported version; supported versions are 1.3.x and 2.x."); }
ProcessInfo processInfo = null; @@ -236,8 +231,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen DiscoveredResourceDetails resourceDetails = createResourceDetails(discoveryContext, pluginConfig, processInfo, binaryInfo); return resourceDetails; - } - catch (Exception e) { + } catch (Exception e) { throw new RuntimeException("Failed to create resource details during manual add."); } } @@ -247,8 +241,9 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return (version != null) && (version.startsWith("1.3") || version.startsWith("2.")); }
- private DiscoveredResourceDetails createResourceDetails(ResourceDiscoveryContext<PlatformComponent> discoveryContext, - Configuration pluginConfig, ProcessInfo processInfo, ApacheBinaryInfo binaryInfo) throws Exception { + private DiscoveredResourceDetails createResourceDetails( + ResourceDiscoveryContext<PlatformComponent> discoveryContext, Configuration pluginConfig, + ProcessInfo processInfo, ApacheBinaryInfo binaryInfo) throws Exception { String httpdConf = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF).getStringValue(); String version = binaryInfo.getVersion(); String serverUrl = pluginConfig.getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL, null); @@ -258,19 +253,19 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen name = httpdConf; } else { URI uri = new URI(serverUrl); - name = uri.getHost() + ":" + uri.getPort(); + name = uri.getHost() + ":" + uri.getPort(); }
String serverRoot = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT) .getStringValue(); - + String key = FileUtils.getCanonicalPath(serverRoot);
//BZ 612189 - reverting to the serverRoot as the resource key temporarily until we have the resource //upgrade functionality ready (BZ 592038). Uncommenting the line below will make the resource key totally unique //(see BZ 593270). //key += "|" + httpdConf; - + DiscoveredResourceDetails resourceDetails = new DiscoveredResourceDetails(discoveryContext.getResourceType(), key, name, version, PRODUCT_DESCRIPTION, pluginConfig, processInfo); log.debug("Apache Server resource details created: " + resourceDetails); @@ -290,7 +285,6 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return addr == null ? null : "http://" + addr.host + ":" + addr.port + "/"; }
- @Nullable private String getServerRoot(@NotNull ApacheBinaryInfo binaryInfo, @NotNull ProcessInfo processInfo) { // First see if -d was specified on the httpd command line. @@ -315,12 +309,12 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen currentWorkingDir = processInfo.getCurrentWorkingDirectory(); } catch (Exception e) { log.error("Unable to determine current working directory of Apache process [" + processInfo - + "], which is needed to determine the server root of the Apache instance.", e); + + "], which is needed to determine the server root of the Apache instance.", e); return null; } if (currentWorkingDir == null) { log.error("Unable to determine current working directory of Apache process [" + processInfo - + "], which is needed to determine the server root of the Apache instance."); + + "], which is needed to determine the server root of the Apache instance."); return null; } else { rootFile = new File(currentWorkingDir, root); @@ -396,12 +390,12 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen }
private static void validateServerRootAndServerConfigFile(Configuration pluginConfig) { - String serverRoot = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT).getStringValue(); + String serverRoot = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT) + .getStringValue(); File serverRootFile; try { serverRootFile = new File(serverRoot).getCanonicalFile(); // this will resolve symlinks - } - catch (IOException e) { + } catch (IOException e) { serverRootFile = null; } if (serverRootFile == null || !serverRootFile.isDirectory()) { @@ -413,8 +407,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen File httpdConfFile; try { httpdConfFile = new File(httpdConf).getCanonicalFile(); // this will resolve symlinks - } - catch (IOException e) { + } catch (IOException e) { httpdConfFile = null; } if (httpdConfFile == null || !httpdConfFile.isFile()) { @@ -423,15 +416,15 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen + ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF + "' connection property is set correctly."); } } - - private static ApacheDirectiveTree loadParser(String path,String serverRoot) throws Exception{ + + private static ApacheDirectiveTree loadParser(String path, String serverRoot) throws Exception {
ApacheDirectiveTree tree = new ApacheDirectiveTree(); - ApacheParser parser = new ApacheParserImpl(tree,serverRoot); + ApacheParser parser = new ApacheParserImpl(tree, serverRoot); ApacheConfigReader.buildTree(path, parser); return tree; } - + public static String scanForGlobInclude(ApacheDirectiveTree tree) { try { List<ApacheDirective> includes = tree.search("/Include"); @@ -440,9 +433,9 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen if (Glob.isWildcard(include)) { //we only take the '*.something' into account here //so that we have a useful mask to base the file names on. - + //the only special glob character allowed is *. - for(char specialChar : GlobFilter.WILDCARD_CHARS) { + for (char specialChar : GlobFilter.WILDCARD_CHARS) { if (specialChar == '*') { if (include.indexOf(specialChar) != include.lastIndexOf(specialChar)) { //more than 1 star... that's too much @@ -462,4 +455,4 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen } return null; } -} \ No newline at end of file +}
commit 065319e2048376d93509e31dd526789b26947b4f Merge: 98a4d17... 297cc73... Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 12:49:38 2010 +0200
Merge branch 'master' into resource-upgrade
commit 98a4d17665d0fed83e0fd2c28770545178b00150 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Oct 5 12:48:12 2010 +0200
making the getResourcesWithType(ResourceType, Set<Resource>) private again.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index c5004dd..351f751 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1668,7 +1668,7 @@ public class InventoryManager extends AgentService implements ContainerService, return getResourcesWithType(serverType, this.platform.getChildResources()); }
- public Set<Resource> getResourcesWithType(ResourceType serverType, Set<Resource> resources) { + private Set<Resource> getResourcesWithType(ResourceType serverType, Set<Resource> resources) { Set<Resource> servers = new HashSet<Resource>();
if (resources == null) {
commit 297cc733d3b5567a444131892c4766d6852fa80e Author: Joseph Marques joseph@redhat.com Date: Tue Oct 5 01:22:58 2010 -0400
add todos for future infrastructure work
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 a779117..d0760d2 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 @@ -139,9 +139,15 @@ public class GWTServiceLookup {
public static class SessionRpcRequestBuilder extends RpcRequestBuilder {
+ private static int RPC_TIMEOUT = 10000; + @Override - protected void doFinish(RequestBuilder rb) { - super.doFinish(rb); + protected RequestBuilder doCreate(String serviceEntryPoint) { + RequestBuilder rb = super.doCreate(serviceEntryPoint); + + // TODO: alter callback handlers to capture timeout failure and retry (at least once) + // to add resilience to gwt service calls + rb.setTimeoutMillis(RPC_TIMEOUT);
// TODO Don't use the expensive determineName except in dev mode rb.setCallback(new MonitoringRequestCallback(determineName(), rb.getCallback())); @@ -155,6 +161,8 @@ public class GWTServiceLookup { .error("SessionRpcRequestBuilder constructed without a value for " + UserSessionManager.SESSION_NAME); } + + return rb; }
public String determineName() { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java index c9da68a..364140f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.server.gwt;
import java.io.IOException; +import java.util.Enumeration;
import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -49,6 +50,9 @@ public abstract class AbstractGWTServiceImpl extends RemoteServiceServlet {
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (Log.isTraceEnabled()) { + printHeaders(req); + } String sid = req.getHeader(UserSessionManager.SESSION_NAME); if (sid != null) { SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); @@ -62,8 +66,22 @@ public abstract class AbstractGWTServiceImpl extends RemoteServiceServlet { Log.error("Failed to validate request: sessionId missing, requestURL=" + req.getRequestURL()); }
+ // TODO: only execute this if the session lookup was successful, otherwise fail in some deterministic fashion + // alter callback handlers to capture expected failure and retry (at least once) + // to add resilience to gwt service calls long id = HibernatePerformanceMonitor.get().start(); super.service(req, resp); HibernatePerformanceMonitor.get().stop(id, "GWT Service Request"); } + + @SuppressWarnings("unchecked") + private void printHeaders(HttpServletRequest req) { + // TODO: figure out why SESSION_NAME header and other GWT-specific headers are missing occasionally + // seems to only happen on polling for recent alerts when there is no user activity for a few minutes + Enumeration<String> headerNames = req.getHeaderNames(); + Log.trace(req.getRequestURL().toString()); + while (headerNames.hasMoreElements()) { + Log.trace(" " + headerNames.nextElement()); + } + } }
commit 83c0317378f20d3a9aa1bf92bcf645a771a41e84 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 4 23:29:01 2010 -0400
fix z-index so log_DivLogger can be used if developers so choose
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css index 85d1b83..54cc3a9 100644 --- a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css +++ b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.css @@ -317,11 +317,9 @@ a:hover { -moz-box-sizing: border-box; overflow: hidden; cursor: auto; - z-index: 9999999; }
.gwtMenu, .gwt-MenuBarPopup, .gwt-MenuPopup { - z-index: 9999999; background-color: white; }
@@ -387,3 +385,7 @@ a:hover { background-color: #FF6666; /* slightly darker light red */ border-color: #EE1111; /* slightly darker medium red */ } + +.log-panel { + z-index: 9999999 !important; +}
commit 84ae15fae55dbaf217217cb4bb1c0edc58c4c907 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 4 17:41:07 2010 -0400
better logging around request-response workflow and user session management
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 ecbd719..65faa6d 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 @@ -56,7 +56,7 @@ import org.rhq.enterprise.gui.coregui.client.util.preferences.UserPreferences; public class UserSessionManager {
private static int SESSION_TIMEOUT = 29 * 60 * 1000; // 29 mins, just shorter than the 30-min web session timeout - private static int LOGOUT_DELAY = 15 * 1000; // wait 15 seconds for in-flight requests to complete before logout + private static int LOGOUT_DELAY = 5 * 1000; // wait 5 seconds for in-flight requests to complete before logout
public static final String SESSION_NAME = "RHQ_Sesssion"; private static Subject sessionSubject; @@ -88,7 +88,7 @@ public class UserSessionManager { try { b.setCallback(new RequestCallback() { public void onResponseReceived(final Request request, final Response response) { - com.allen_sauer.gwt.log.client.Log.info("response text = " + response.getText()); + Log.info("response text = " + response.getText()); String sessionIdString = response.getText(); if (sessionIdString != null && sessionIdString.length() > 0) {
@@ -96,20 +96,20 @@ public class UserSessionManager { final int subjectId = Integer.parseInt(parts[0]); final String sessionId = parts[1]; // not null final long lastAccess = Long.parseLong(parts[2]); - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-subjectId: " + subjectId); - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-sessionId: " + sessionId); - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-lastAccess: " + lastAccess); + Log.info("sessionAccess-subjectId: " + subjectId); + Log.info("sessionAccess-sessionId: " + sessionId); + Log.info("sessionAccess-lastAccess: " + lastAccess);
String previousSessionId = getPreviousSessionId(); // may be null - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-previousSessionId: " + previousSessionId); + Log.info("sessionAccess-previousSessionId: " + previousSessionId); if (previousSessionId == null || previousSessionId.equals(sessionId) == false) {
// persist sessionId if different from previously saved sessionId - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-savingSessionId: " + sessionId); + Log.info("sessionAccess-savingSessionId: " + sessionId); saveSessionId(sessionId);
// new sessions get the full 29 minutes to expire - com.allen_sauer.gwt.log.client.Log.info("sessionAccess-schedulingSessionTimeout: " + SESSION_TIMEOUT); + Log.info("sessionAccess-schedulingSessionTimeout: " + SESSION_TIMEOUT); sessionTimer.schedule(SESSION_TIMEOUT); } else {
@@ -124,7 +124,7 @@ public class UserSessionManager { expiryMillis = SESSION_TIMEOUT; // guarantees maximum is 29 minutes }
- com.allen_sauer.gwt.log.client.Log.info("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); + Log.info("sessionAccess-reschedulingSessionTimeout: " + expiryMillis); sessionTimer.schedule((int) expiryMillis); }
@@ -143,7 +143,7 @@ public class UserSessionManager { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError( "UserSessionManager: Failed to load user's subject", caught); - com.allen_sauer.gwt.log.client.Log.info("Failed to load user's subject"); + Log.info("Failed to load user's subject"); new LoginView().showLoginDialog(); }
@@ -260,10 +260,12 @@ public class UserSessionManager {
public static String getSessionId() { if (sessionSubject == null) { + Log.error("UserSessionManager: sessionSubject is null"); return null; } Integer sessionId = sessionSubject.getSessionId(); if (sessionId == null) { + Log.error("UserSessionManager: sessionId is null"); return null; } return sessionId.toString(); 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 4a9c639..a779117 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 @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.gwt;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.user.client.rpc.RpcRequestBuilder; import com.google.gwt.user.client.rpc.ServiceDefTarget; @@ -139,11 +140,6 @@ public class GWTServiceLookup { public static class SessionRpcRequestBuilder extends RpcRequestBuilder {
@Override - protected void doSetRequestData(RequestBuilder rb, String data) { - super.doSetRequestData(rb, data); // TODO: Implement this method. - } - - @Override protected void doFinish(RequestBuilder rb) { super.doFinish(rb);
@@ -152,7 +148,12 @@ public class GWTServiceLookup {
String sessionId = UserSessionManager.getSessionId(); if (sessionId != null) { + Log.info("SessionRpcRequestBuilder is adding sessionId to request: " + sessionId); rb.setHeader(UserSessionManager.SESSION_NAME, sessionId); + } else { + Log + .error("SessionRpcRequestBuilder constructed without a value for " + + UserSessionManager.SESSION_NAME); } }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java index ae1e85b..c9da68a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/AbstractGWTServiceImpl.java @@ -24,6 +24,7 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.rhq.core.domain.auth.Subject; @@ -34,9 +35,12 @@ import org.rhq.enterprise.server.util.LookupUtil;
/** * @author Greg Hinkle + * @author Joseph Marques */ public abstract class AbstractGWTServiceImpl extends RemoteServiceServlet {
+ private static final long serialVersionUID = 1L; + private ThreadLocal<Subject> sessionSubject = new ThreadLocal<Subject>();
protected Subject getSessionSubject() { @@ -46,20 +50,20 @@ public abstract class AbstractGWTServiceImpl extends RemoteServiceServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sid = req.getHeader(UserSessionManager.SESSION_NAME); - Subject subject = null; if (sid != null) { SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); try { - subject = subjectManager.getSubjectBySessionId(Integer.parseInt(sid)); + Subject subject = subjectManager.getSubjectBySessionId(Integer.parseInt(sid)); + sessionSubject.set(subject); } catch (Exception e) { - throw new RuntimeException("Failed to validate session", e); + Log.error("Failed to validate request: sessionId was '" + sid + "', requestURL=" + req.getRequestURL()); } + } else { + Log.error("Failed to validate request: sessionId missing, requestURL=" + req.getRequestURL()); } - sessionSubject.set(subject);
long id = HibernatePerformanceMonitor.get().start(); super.service(req, resp); HibernatePerformanceMonitor.get().stop(id, "GWT Service Request"); } - }
commit 34d44ee66ec927b1dbb1d96fc15de3250622e7e4 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 4 14:07:42 2010 -0400
remove duplicate servlet definitions, alphabetize the rest
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index c486f1d..ecfac0b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -80,8 +80,11 @@ <servlet path="/AuthorizationGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AuthorizationGWTServiceImpl"/> <servlet path="/AvailabilityGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.AvailabilityGWTServiceImpl"/> <servlet path="/BundleGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.BundleGWTServiceImpl"/> + <servlet path="/ClusterGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.ClusterGWTServiceImpl"/> <servlet path="/ConfigurationGwtService" class="org.rhq.enterprise.gui.coregui.server.gwt.ConfigurationGWTServiceImpl"/> <servlet path="/ContentGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.ContentGWTServiceImpl"/> + <servlet path="/DashboardGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.DashboardGWTServiceImpl"/> + <servlet path="/EventGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.EventGWTServiceImpl"/> <servlet path="/MeasurementDataGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.MeasurementDataGWTServiceImpl"/> <servlet path="/OperationGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.OperationGWTServiceImpl"/> <servlet path="/RemoteInstallGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.RemoteInstallGWTServiceImpl"/> @@ -95,11 +98,5 @@ <servlet path="/SubjectGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.SubjectGWTServiceImpl"/> <servlet path="/SystemGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.SystemGWTServiceImpl"/> <servlet path="/TagGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.TagGWTServiceImpl"/> - <servlet path="/RemoteInstallGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.RemoteInstallGWTServiceImpl"/> - <servlet path="/RepoGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.RepoGWTServiceImpl"/> - <servlet path="/ContentGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.ContentGWTServiceImpl"/> - <servlet path="/DashboardGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.DashboardGWTServiceImpl"/> - <servlet path="/EventGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.EventGWTServiceImpl"/> - <servlet path="/ClusterGWTService" class="org.rhq.enterprise.gui.coregui.server.gwt.ClusterGWTServiceImpl"/>
-</module> \ No newline at end of file +</module>
commit 01bb66ff5713c644f2f7bb4d46763a0866276eb5 Author: Joseph Marques joseph@redhat.com Date: Mon Oct 4 14:03:50 2010 -0400
show as much detail in the message center as possible
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java index 34e343e..e62b908 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/create/BundleUploadDataStep.java @@ -204,8 +204,7 @@ public class BundleUploadDataStep extends AbstractWizardStep { uploadForm.addFormSubmitFailedHandler(new FormSubmitFailedHandler() { public void onFormSubmitFailed(FormSubmitFailedEvent event) { allFilesStatus.put(uploadForm.getName(), Boolean.FALSE); - CoreGUI.getMessageCenter().notify( - new Message("Failed to upload file", null, Message.Severity.Error)); + CoreGUI.getMessageCenter().notify(new Message("Failed to upload file", Message.Severity.Error)); } });
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java index 49bb67e..1b97a65 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/ErrorHandler.java @@ -18,11 +18,14 @@ */ package org.rhq.enterprise.gui.coregui.client.util;
+import java.util.ArrayList; + import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.util.message.Message;
/** * @author Greg Hinkle + * @author Joseph Marques */ public class ErrorHandler { public void handleError(String message) { @@ -30,7 +33,7 @@ public class ErrorHandler { }
public void handleError(String message, Throwable t) { - Message errorMessage = new Message(message, (t == null) ? null : t.toString(), Message.Severity.Fatal); + Message errorMessage = new Message(message, t, Message.Severity.Fatal); CoreGUI.getMessageCenter().notify(errorMessage);
if (t != null) { @@ -38,4 +41,40 @@ public class ErrorHandler { t.printStackTrace(); } } + + public static String getAllMessages(Throwable t) { + StringBuffer results = new StringBuffer(); + + if (t != null) { + String[] msgs = getAllMessagesArray(t); + results.append(msgs[0]); + + String indent = " "; + for (int i = 1; i < msgs.length; i++) { + results.append("\n").append(indent); + results.append(msgs[i]); + indent = indent + " "; + } + } else { + results.append(">> exception was null <<"); + } + + return results.toString(); + } + + public static String[] getAllMessagesArray(Throwable t) { + ArrayList<String> list = new ArrayList<String>(); + + if (t != null) { + list.add(t.getClass().getName() + ":" + t.getMessage()); + + while ((t.getCause() != null) && (t != t.getCause())) { + t = t.getCause(); + + list.add(t.getClass().getName() + ":" + t.getMessage()); + } + } + + return list.toArray(new String[list.size()]); + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java index 3a0b464..a9e94c2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/message/Message.java @@ -21,13 +21,14 @@ package org.rhq.enterprise.gui.coregui.client.util.message; import java.util.Date; import java.util.EnumSet;
+import org.rhq.enterprise.gui.coregui.client.util.ErrorHandler; + /** * A message to be displayed to the user in one or more places. * * @author Greg Hinkle * @author Ian Springer */ -@SuppressWarnings({"UnnecessarySemicolon"}) public class Message { protected String conciseMessage; protected String detailedMessage; @@ -36,21 +37,30 @@ public class Message { protected EnumSet<Option> options;
// TODO: Add Debug severity? - public enum Severity { Info, Warning, Error, Fatal }; - public enum Option { Transient, Sticky, BackgroundJobResult }; + public enum Severity { + Info, Warning, Error, Fatal + }; + + public enum Option { + Transient, Sticky, BackgroundJobResult + };
public Message(String conciseMessage) { - this(conciseMessage, (Severity)null); + this(conciseMessage, (Severity) null); }
public Message(String conciseMessage, Severity severity) { - this(conciseMessage, null, severity); + this(conciseMessage, (String) null, severity); }
public Message(String conciseMessage, String detailedMessage) { this(conciseMessage, detailedMessage, null); }
+ public Message(String conciseMessage, Throwable details) { + this(conciseMessage, details, null); + } + public Message(String conciseMessage, EnumSet<Option> options) { this(conciseMessage, null, options); } @@ -59,8 +69,16 @@ public class Message { this(conciseMessage, detailedMessage, severity, null); }
+ public Message(String conciseMessage, Throwable details, Severity severity) { + this(conciseMessage, details, severity, null); + } + public Message(String conciseMessage, Severity severity, EnumSet<Option> options) { - this(conciseMessage, null, severity, options); + this(conciseMessage, (String) null, severity, options); + } + + public Message(String conciseMessage, Throwable details, Severity severity, EnumSet<Option> options) { + this(conciseMessage, ErrorHandler.getAllMessages(details), severity, options); }
public Message(String conciseMessage, String detailedMessage, Severity severity, EnumSet<Option> options) { @@ -97,15 +115,14 @@ public class Message { public boolean isBackgroundJobResult() { return options.contains(Option.BackgroundJobResult); } - + @Override public String toString() { - return "Message{" + - "conciseMessage='" + this.conciseMessage + ''' + - ", detailedMessage='" + this.detailedMessage + ''' + - ", fired=" + this.fired + - ", severity=" + this.severity + - ", options=" + this.options + - '}'; + return "Message{" // + + "conciseMessage='" + this.conciseMessage + ''' // + + ", detailedMessage='" + this.detailedMessage + ''' // + + ", fired=" + this.fired // + + ", severity=" + this.severity // + + ", options=" + this.options + '}'; } }
commit 25ccc993e3a166cbad9e03bf609343cb3b744c5a Author: Ian Springer ian.springer@redhat.com Date: Mon Oct 4 21:30:38 2010 -0400
finish support for lists of maps in config editor
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 d9c3dd7..fc63830 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 @@ -147,12 +147,14 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; */ @SuppressWarnings({"UnnecessarySemicolon"}) public class ConfigurationEditor extends LocatableVLayout { + private static final String RHQ_PROPERTY_ATTRIBUTE_NAME = "rhq:property"; + private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
private TabSet tabSet; private LocatableToolStrip toolStrip;
- private ConfigurationDefinition definition; + private ConfigurationDefinition configurationDefinition; private Configuration configuration; private Configuration originalConfiguration;
@@ -169,7 +171,7 @@ public class ConfigurationEditor extends LocatableVLayout {
private boolean readOnly = false; private Set<String> invalidPropertyNames = new HashSet<String>(); - private Set<PropertyValueChangeListener> validationStateChangeListeners = + private Set<PropertyValueChangeListener> propertyValueChangeListeners = new HashSet<PropertyValueChangeListener>();
public static enum ConfigType { @@ -193,10 +195,11 @@ public class ConfigurationEditor extends LocatableVLayout { setOverflow(Overflow.AUTO); }
- public ConfigurationEditor(String locatorId, ConfigurationDefinition definition, Configuration configuration) { + public ConfigurationEditor(String locatorId, ConfigurationDefinition configurationDefinition, + Configuration configuration) { super(locatorId); this.configuration = configuration; - this.definition = definition; + this.configurationDefinition = configurationDefinition; }
public Configuration getConfiguration() { @@ -227,8 +230,8 @@ public class ConfigurationEditor extends LocatableVLayout { return this.valuesManager.hasErrors(); }
- public void addValidationStateChangeListener(PropertyValueChangeListener validationStateChangeListener) { - this.validationStateChangeListeners.add(validationStateChangeListener); + public void addPropertyValueChangeListener(PropertyValueChangeListener propertyValueChangeListener) { + this.propertyValueChangeListeners.add(propertyValueChangeListener); }
@Override @@ -240,7 +243,7 @@ public class ConfigurationEditor extends LocatableVLayout {
final long start = System.currentTimeMillis();
- if (definition == null || configuration == null) { + if (configurationDefinition == null || configuration == null) {
if (configType == ConfigType.resource) { configurationService.getResourceConfiguration(resourceId, new AsyncCallback<Configuration>() { @@ -260,8 +263,8 @@ public class ConfigurationEditor extends LocatableVLayout { new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { com.allen_sauer.gwt.log.client.Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); - definition = types.get(resourceTypeId).getResourceConfigurationDefinition(); - if (definition == null) { + configurationDefinition = types.get(resourceTypeId).getResourceConfigurationDefinition(); + if (configurationDefinition == null) { loadingLabel.hide(); showError("Configuration is not supported by this Resource."); } @@ -286,8 +289,8 @@ public class ConfigurationEditor extends LocatableVLayout { new ResourceTypeRepository.TypesLoadedCallback() { public void onTypesLoaded(Map<Integer, ResourceType> types) { com.allen_sauer.gwt.log.client.Log.debug("ConfigDef retreived in: " + (System.currentTimeMillis() - start)); - definition = types.get(resourceTypeId).getPluginConfigurationDefinition(); - if (definition == null) { + configurationDefinition = types.get(resourceTypeId).getPluginConfigurationDefinition(); + if (configurationDefinition == null) { showError("Connection settings are not supported by this Resource."); } reload(); @@ -300,7 +303,7 @@ public class ConfigurationEditor extends LocatableVLayout { }
public void reload() { - if (definition == null || configuration == null) { + if (configurationDefinition == null || configuration == null) { // Wait for both to load return; } @@ -309,16 +312,16 @@ public class ConfigurationEditor extends LocatableVLayout {
tabSet = new LocatableTabSet(getLocatorId());
- if (definition.getConfigurationFormat() == ConfigurationFormat.RAW - || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { + if (configurationDefinition.getConfigurationFormat() == ConfigurationFormat.RAW + || configurationDefinition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { com.allen_sauer.gwt.log.client.Log.info("Loading files view..."); Tab tab = new LocatableTab("Files", "Files"); tab.setPane(buildRawPane()); tabSet.addTab(tab); }
- if (definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED - || definition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { + if (configurationDefinition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED + || configurationDefinition.getConfigurationFormat() == ConfigurationFormat.STRUCTURED_AND_RAW) { com.allen_sauer.gwt.log.client.Log.info("Loading properties view..."); Tab tab = new LocatableTab("Properties", "Properties"); tab.setPane(buildStructuredPane()); @@ -391,7 +394,7 @@ public class ConfigurationEditor extends LocatableVLayout { protected VLayout buildStructuredPane() {
LocatableVLayout layout = new LocatableVLayout(extendLocatorId("Structured")); - List<PropertyGroupDefinition> definitions = definition.getGroupDefinitions(); + List<PropertyGroupDefinition> definitions = configurationDefinition.getGroupDefinitions();
final SectionStack sectionStack = new LocatableSectionStack(layout.extendLocatorId("Sections")); sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); @@ -400,7 +403,7 @@ public class ConfigurationEditor extends LocatableVLayout { sectionStack.setScrollSectionIntoView(true); sectionStack.setOverflow(Overflow.AUTO);
- if (definition.getNonGroupedProperties().size() > 0) { + if (configurationDefinition.getNonGroupedProperties().size() > 0) { sectionStack.addSection(buildGroupSection(layout.extendLocatorId("NoGroup"), null)); }
@@ -481,8 +484,8 @@ public class ConfigurationEditor extends LocatableVLayout { section.setExpanded(!group.isDefaultHidden()); }
- List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(((group == null) ? definition - .getNonGroupedProperties() : definition.getPropertiesInGroup(group.getName()))); + List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(((group == null) ? configurationDefinition + .getNonGroupedProperties() : configurationDefinition.getPropertiesInGroup(group.getName())));
DynamicForm form = buildPropertiesForm(locatorId + "_Props", propertyDefinitions, configuration);
@@ -748,6 +751,7 @@ public class ConfigurationEditor extends LocatableVLayout { PropertySimple prop = propertyMap.getSimple(propertyName); if (prop == null) { prop = new PropertySimple(propertyName, null); + propertyMap.put(prop); } String value = record.getAttribute("Value"); prop.setStringValue(value); @@ -778,14 +782,30 @@ public class ConfigurationEditor extends LocatableVLayout { summaryTable.setOverflow(Overflow.VISIBLE); summaryTable.setAutoFitData(Autofit.HORIZONTAL);
- ArrayList<ListGridField> fieldsList = new ArrayList<ListGridField>(); - ArrayList<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(memberPropertyDefinitionMap + summaryTable.addCellSavedHandler(new CellSavedHandler() { + public void onCellSaved(CellSavedEvent cellSavedEvent) { + Record record = cellSavedEvent.getRecord(); + PropertyMap propertyMap = (PropertyMap)record.getAttributeAsObject(RHQ_PROPERTY_ATTRIBUTE_NAME); + for (String memberPropertyName : memberPropertyDefinitionMap.getPropertyDefinitions().keySet()) { + PropertySimple memberProperty = propertyMap.getSimple(memberPropertyName); + if (memberProperty == null) { + memberProperty = new PropertySimple(memberPropertyName, null); + propertyMap.put(memberProperty); + } + String newValue = record.getAttribute(memberPropertyName); + memberProperty.setStringValue(newValue); + } + } + }); + + List<ListGridField> fieldsList = new ArrayList<ListGridField>(); + List<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(memberPropertyDefinitionMap .getPropertyDefinitions().values()); Collections.sort(definitions, new PropertyDefinitionComparator());
for (PropertyDefinition subDef : definitions) { if (subDef.isSummary()) { - ListGridField field = new ListGridField(subDef.getName(), subDef.getDisplayName()); + ListGridField field = new ListGridField(subDef.getName(), subDef.getDisplayName(), 90);
PropertyDefinitionSimple defSimple = (PropertyDefinitionSimple) subDef; if (defSimple.getType() == PropertySimpleType.INTEGER) { @@ -798,7 +818,7 @@ public class ConfigurationEditor extends LocatableVLayout { } }
- if (fieldsList.size() == 0) { + if (fieldsList.isEmpty()) { // An extra "feature of the config system". If no fields are labeled summary, all are considered summary. for (PropertyDefinition subDef : definitions) { ListGridField field = new ListGridField(subDef.getName(), subDef.getDisplayName()); @@ -809,7 +829,6 @@ public class ConfigurationEditor extends LocatableVLayout { } else if (defSimple.getType() == PropertySimpleType.FLOAT) { field.setType(ListGridFieldType.FLOAT); } - } }
@@ -823,10 +842,11 @@ public class ConfigurationEditor extends LocatableVLayout { editField.setCanHide(false); editField.addRecordClickHandler(new RecordClickHandler() { public void onRecordClick(RecordClickEvent recordClickEvent) { - com.allen_sauer.gwt.log.client.Log.info("You want to edit: " + recordClickEvent.getRecord()); + Log.info("You want to edit: " + recordClickEvent.getRecord()); + PropertyMap memberPropertyMap = (PropertyMap)recordClickEvent.getRecord().getAttributeAsObject( + RHQ_PROPERTY_ATTRIBUTE_NAME); displayMapEditor(locatorId + "_MapEdit", summaryTable, recordClickEvent.getRecord(), - memberPropertyDefinitionMap, propertyList, (PropertyMap) recordClickEvent.getRecord().getAttributeAsObject( - "_RHQ_PROPERTY")); + memberPropertyDefinitionMap, propertyList, memberPropertyMap); } }); fieldsList.add(editField); @@ -845,7 +865,7 @@ public class ConfigurationEditor extends LocatableVLayout {
removeField.addRecordClickHandler(new RecordClickHandler() { public void onRecordClick(final RecordClickEvent recordClickEvent) { - com.allen_sauer.gwt.log.client.Log.info("You want to delete: " + recordClickEvent.getRecordNum()); + Log.info("You want to delete: " + recordClickEvent.getRecordNum()); SC.confirm("Are you sure you want to delete this row?", new BooleanCallback() { public void execute(Boolean aBoolean) { if (aBoolean) { @@ -862,6 +882,7 @@ public class ConfigurationEditor extends LocatableVLayout {
summaryTable.setFields(fieldsList.toArray(new ListGridField[fieldsList.size()]));
+ // Now add rows containing the actual data (i.e. member property values). ListGridRecord[] rows = buildSummaryRecords(propertyList, definitions); summaryTable.setData(rows);
@@ -886,7 +907,7 @@ public class ConfigurationEditor extends LocatableVLayout { return item; }
- private ListGridRecord[] buildSummaryRecords(PropertyList propertyList, ArrayList<PropertyDefinition> definitions) { + private ListGridRecord[] buildSummaryRecords(PropertyList propertyList, List<PropertyDefinition> definitions) { ListGridRecord[] rows = new ListGridRecord[propertyList == null ? 0 : propertyList.getList().size()]; int i = 0; for (Property row : propertyList.getList()) { @@ -897,11 +918,11 @@ public class ConfigurationEditor extends LocatableVLayout { return rows; }
- private ListGridRecord buildSummaryRecord(List<PropertyDefinition> definitions, PropertyMap rowMap) { + private ListGridRecord buildSummaryRecord(List<PropertyDefinition> memberPropertyDefinitions, PropertyMap memberPropertyMap) { ListGridRecord record = new ListGridRecord(); - for (PropertyDefinition subDef : definitions) { + for (PropertyDefinition subDef : memberPropertyDefinitions) { PropertyDefinitionSimple subDefSimple = (PropertyDefinitionSimple) subDef; - PropertySimple propertySimple = ((PropertySimple) rowMap.get(subDefSimple.getName())); + PropertySimple propertySimple = ((PropertySimple) memberPropertyMap.get(subDefSimple.getName()));
if (propertySimple.getStringValue() != null) { record.setAttribute(subDefSimple.getName(), propertySimple.getStringValue()); @@ -930,13 +951,12 @@ public class ConfigurationEditor extends LocatableVLayout {
} } - record.setAttribute("_RHQ_PROPERTY", rowMap); + record.setAttribute(RHQ_PROPERTY_ATTRIBUTE_NAME, memberPropertyMap); return record; }
private FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinition, - final PropertySimple propertySimple - ) { + final PropertySimple propertySimple) { Log.debug("Building simple field for " + propertySimple + "...");
FormItem valueItem = null; @@ -1004,6 +1024,7 @@ public class ConfigurationEditor extends LocatableVLayout { List<Validator> validators = buildValidators(propertyDefinition, propertySimple); valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
+ valueItem.setDisabled(isReadOnly(propertyDefinition) || isUnset(propertyDefinition, propertySimple)); /* Click handlers seem to be turned off for disabled fields... need an alternative valueItem.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() { @@ -1017,27 +1038,29 @@ public class ConfigurationEditor extends LocatableVLayout { */
valueItem.setShowTitle(false); - valueItem.setDisabled(isReadOnly(propertyDefinition) || isUnset(propertyDefinition, propertySimple)); valueItem.setWidth(220);
final FormItem finalValueItem = valueItem;
finalValueItem.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent changedEvent) { - boolean wasValidBefore = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); propertySimple.setErrorMessage(null); + + boolean wasValidBefore = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); + Property topLevelProperty = getTopLevelProperty(propertySimple); if (changedEvent.getItem().validate()) { - ConfigurationEditor.this.invalidPropertyNames.remove(propertySimple.getName()); - propertySimple.setValue(changedEvent.getValue()); + ConfigurationEditor.this.invalidPropertyNames.remove(topLevelProperty.getName()); + propertySimple.setValue(changedEvent.getValue()); } else { - ConfigurationEditor.this.invalidPropertyNames.add(propertySimple.getName()); + ConfigurationEditor.this.invalidPropertyNames.add(topLevelProperty.getName()); } boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); + boolean validationStateChanged = (isValidNow != wasValidBefore); - for (PropertyValueChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { + for (PropertyValueChangeListener propertyValueChangeListener : ConfigurationEditor.this.propertyValueChangeListeners) { PropertyValueChangeEvent event = new PropertyValueChangeEvent(propertySimple, propertyDefinition, validationStateChanged, ConfigurationEditor.this.invalidPropertyNames); - validationStateChangeListener.propertyValueChanged(event); + propertyValueChangeListener.propertyValueChanged(event); } } }); @@ -1045,9 +1068,19 @@ public class ConfigurationEditor extends LocatableVLayout { return valueItem; }
- private boolean isUnset(PropertyDefinitionSimple propertyDefinition, PropertySimple propertySimple) { - return (!propertyDefinition.isRequired() && - (propertySimple == null || propertySimple.getStringValue() == null)); + private static Property getTopLevelProperty(PropertySimple propertySimple) { + Property currentProperty = propertySimple; + while (currentProperty.getConfiguration() == null) { + if (currentProperty.getParentList() != null) { + currentProperty = currentProperty.getParentList(); + } else if (currentProperty.getParentMap() != null) { + currentProperty = currentProperty.getParentMap(); + } else { + Log.error("Property " + currentProperty + " has no parent."); + break; + } + } + return currentProperty; }
private FormItem buildUnsetItem(PropertyDefinitionSimple propertyDefinition, final PropertySimple property, @@ -1083,6 +1116,11 @@ public class ConfigurationEditor extends LocatableVLayout { return item; }
+ private boolean isUnset(PropertyDefinitionSimple propertyDefinition, PropertySimple propertySimple) { + return (!propertyDefinition.isRequired() && + (propertySimple == null || propertySimple.getStringValue() == null)); + } + private boolean isReadOnly(PropertyDefinition propertyDefinition) { return propertyDefinition.isReadOnly() || this.readOnly; } @@ -1131,14 +1169,14 @@ public class ConfigurationEditor extends LocatableVLayout { private void displayMapEditor(String locatorId, final ListGrid summaryTable, final Record existingRecord, PropertyDefinitionMap definition, final PropertyList list, PropertyMap map) {
- final List<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(definition + final List<PropertyDefinition> memberDefinitions = new ArrayList<PropertyDefinition>(definition .getPropertyDefinitions().values()); - - Collections.sort(definitions, new PropertyDefinitionComparator()); + Collections.sort(memberDefinitions, new PropertyDefinitionComparator());
final boolean newRow = map == null; - if (newRow) + if (newRow) { map = new PropertyMap(definition.getName()); + }
final PropertyMap finalMap = map; final PropertyMap copy = finalMap.deepCopy(true); @@ -1146,7 +1184,7 @@ public class ConfigurationEditor extends LocatableVLayout { LocatableVLayout layout = new LocatableVLayout(locatorId); layout.setHeight100();
- DynamicForm childForm = buildPropertiesForm(locatorId + "_Child", definitions, finalMap); + final DynamicForm childForm = buildPropertiesForm(locatorId + "_Child", memberDefinitions, finalMap); childForm.setHeight100(); layout.addMember(childForm);
@@ -1159,24 +1197,21 @@ public class ConfigurationEditor extends LocatableVLayout { popup.setShowCloseButton(false); popup.centerInPage();
- final IButton saveButton = new IButton("Save"); + final IButton okButton = new IButton("OK"); + okButton.disable(); // saveButton.setID("config_structured_button_save"); - saveButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { + okButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { - if (newRow) { list.add(finalMap); - ListGridRecord record = buildSummaryRecord(definitions, finalMap); - - com.allen_sauer.gwt.log.client.Log.info("here"); + ListGridRecord record = buildSummaryRecord(memberDefinitions, finalMap); try { summaryTable.addData(record); - com.allen_sauer.gwt.log.client.Log.info("there"); } catch (Exception e) { e.printStackTrace(); } } else { - for (PropertyDefinition subDef : definitions) { + for (PropertyDefinition subDef : memberDefinitions) { PropertyDefinitionSimple subDefSimple = (PropertyDefinitionSimple) subDef; PropertySimple propertySimple = ((PropertySimple) finalMap.get(subDefSimple.getName())); existingRecord.setAttribute(subDefSimple.getName(), propertySimple != null ? propertySimple @@ -1191,7 +1226,13 @@ public class ConfigurationEditor extends LocatableVLayout { // summaryTable.redraw(); // summaryTable.addData(); popup.destroy(); + } + });
+ // Only enable the OK button if all properties are valid. + childForm.addItemChangedHandler(new ItemChangedHandler() { + public void onItemChanged(ItemChangedEvent itemChangedEvent) { + okButton.setDisabled(!childForm.validate()); } });
@@ -1208,13 +1249,12 @@ public class ConfigurationEditor extends LocatableVLayout { HLayout buttons = new HLayout(); buttons.setAlign(Alignment.CENTER); buttons.setMembersMargin(10); - buttons.setMembers(saveButton, cancelButton); + buttons.setMembers(okButton, cancelButton); layout.addMember(buttons);
popup.addItem(layout);
popup.show(); - }
private static class PropertyDefinitionComparator implements Comparator<PropertyDefinition> { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java index f5afb2c..3f9f225 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/configuration/ResourceConfigurationEditView.java @@ -101,7 +101,7 @@ public class ResourceConfigurationEditView extends LocatableVLayout implements P editor = new ConfigurationEditor(this.extendLocatorId("Editor"), resource.getId(), resource.getResourceType().getId()); editor.setOverflow(Overflow.AUTO); - editor.addValidationStateChangeListener(this); + editor.addPropertyValueChangeListener(this); editor.setReadOnly(!this.resourcePermission.isConfigureWrite()); addMember(editor); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java index 116e1ad..1f1cc52 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/inventory/PluginConfigurationEditView.java @@ -101,7 +101,7 @@ public class PluginConfigurationEditView extends LocatableVLayout implements Pro editor = new ConfigurationEditor(extendLocatorId("Editor"), resource.getId(), resource.getResourceType().getId(), ConfigurationEditor.ConfigType.plugin); editor.setOverflow(Overflow.AUTO); - editor.addValidationStateChangeListener(this); + editor.addPropertyValueChangeListener(this); editor.setReadOnly(!this.resourcePermission.isInventory()); addMember(editor); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java index bfcb322..cc71a2c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationFactory.java @@ -244,11 +244,11 @@ public abstract class TestConfigurationFactory { propMap3.put(new PropertySimple("Integer", Integer.MAX_VALUE)); configuration.put(new PropertyList("ListOfMaps", propMap2, propMap3));
- PropertyMap propMap4 = new PropertyMap("MapOfSimples"); + PropertyMap propMap4 = new PropertyMap("MapOfSimplesInReadOnlyList"); propMap4.put(new PropertySimple("String1", "A")); propMap4.put(new PropertySimple("String2", "B")); propMap4.put(new PropertySimple("Integer", 999)); - PropertyMap propMap5 = new PropertyMap("MapOfSimples"); + PropertyMap propMap5 = new PropertyMap("MapOfSimplesInReadOnlyList"); propMap5.put(new PropertySimple("String1", "a")); propMap5.put(new PropertySimple("String2", "b")); propMap5.put(new PropertySimple("Integer", 0)); diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java index 0349718..2fd5dfa 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/test/TestConfigurationView.java @@ -86,24 +86,6 @@ public class TestConfigurationView reloadConfiguration(); }
- private void reloadConfiguration() { - this.saveButton.disable(); - if (editor != null) { - editor.destroy(); - removeMember(editor); - } - - editor = new ConfigurationEditor(extendLocatorId("Editor"), this.configurationDefinition, this.configuration); - editor.setOverflow(Overflow.AUTO); - editor.addValidationStateChangeListener(this); - addMember(editor); - } - - private void save() { - CoreGUI.getMessageCenter().notify( - new Message("Configuration updated.", "Test configuration updated.")); - } - @Override public void propertyValueChanged(PropertyValueChangeEvent event) { MessageCenter messageCenter = CoreGUI.getMessageCenter(); @@ -126,4 +108,23 @@ public class TestConfigurationView this.saveButton.enable(); } } + + private void reloadConfiguration() { + this.saveButton.disable(); + if (editor != null) { + editor.destroy(); + removeMember(editor); + } + + editor = new ConfigurationEditor(extendLocatorId("Editor"), this.configurationDefinition, this.configuration); + editor.setOverflow(Overflow.AUTO); + editor.addPropertyValueChangeListener(this); + addMember(editor); + } + + private void save() { + CoreGUI.getMessageCenter().notify( + new Message("Configuration updated.", "Test configuration updated.")); + reloadConfiguration(); + } } diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java index 37dddbb..ccc5eeb 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/configuration/test/TestConfigurationFactory.java @@ -236,11 +236,11 @@ public abstract class TestConfigurationFactory { propMap3.put(new PropertySimple("Integer", Integer.MAX_VALUE)); configuration.put(new PropertyList("ListOfMaps", propMap2, propMap3));
- PropertyMap propMap4 = new PropertyMap("MapOfSimples"); + PropertyMap propMap4 = new PropertyMap("MapOfSimplesInReadOnlyList"); propMap4.put(new PropertySimple("String1", "A")); propMap4.put(new PropertySimple("String2", "B")); propMap4.put(new PropertySimple("Integer", 999)); - PropertyMap propMap5 = new PropertyMap("MapOfSimples"); + PropertyMap propMap5 = new PropertyMap("MapOfSimplesInReadOnlyList"); propMap5.put(new PropertySimple("String1", "a")); propMap5.put(new PropertySimple("String2", "b")); propMap5.put(new PropertySimple("Integer", 0));
commit 978b466848e1bd299f191f370ca8c10e57f0f557 Author: John Sanda jsanda@redhat.com Date: Mon Oct 4 20:07:50 2010 -0400
Adding test to verify options are added to an upgraded property
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java index 2324a43..1f72c06 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java @@ -35,6 +35,7 @@ import org.rhq.core.clientapi.descriptor.plugin.PluginDescriptor; import org.rhq.core.clientapi.descriptor.plugin.ServerDescriptor; 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; @@ -109,6 +110,21 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { }
@Test + public void updatePropertyWithAddedOptions() { + initConfigDefs("servers[name='ServerWithAddedOptions']", "UpdatedPropertyWithAddedOptions"); + + String propertyName = "mySimple"; + PropertyDefinitionSimple expectedProperty = updatedConfigDef.getPropertyDefinitionSimple(propertyName); + List<PropertyDefinitionEnumeration> expected = expectedProperty.getEnumeratedValues(); + + PropertyDefinitionSimple actualProperty = originalConfigDef.getPropertyDefinitionSimple(propertyName); + List<PropertyDefinitionEnumeration> actual = actualProperty.getEnumeratedValues(); + + // TODO Need to verify order here as well + AssertUtils.assertCollectionEqualsNoOrder(expected, actual, "Options should have been added to property"); + } + + @Test public void addNewGroup() { initConfigDefs("servers[name='GroupTests']", "GroupTests");
diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml index 23f3a1b..5a1fe11 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml @@ -19,6 +19,12 @@ </plugin-configuration> </server>
+ <server name="ServerWithAddedOptions"> + <plugin-configuration> + <c:simple-property name="mySimple"/> + </plugin-configuration> + </server> + <server name="GroupTests"> <plugin-configuration> <c:group name="existingGroup"> diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml index 4c61512..564c68c 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml @@ -26,6 +26,17 @@ </plugin-configuration> </server>
+ <server name="ServerWithAddedOptions"> + <plugin-configuration> + <c:simple-property name="mySimple"> + <c:property-options> + <c:option name="x" value="1"/> + <c:option name="y" value="2"/> + </c:property-options> + </c:simple-property> + </plugin-configuration> + </server> + <server name="GroupTests"> <plugin-configuration> <c:group name="existingGroup">
commit e7acef3bd0f3bcc2122316cbbbc96366924c69f3 Merge: 87af918... 885a5f5... Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 18:06:53 2010 -0400
Merge branch 'master' into master-jay
Conflicts: modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml
commit 87af918747d582095353ede483dfa8e1c46b7a63 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 18:03:28 2010 -0400
Initial Manual Add Work
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index 7ad683a..8a0329e 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@ -68,4 +68,6 @@ public interface ResourceGWTService extends RemoteService {
void unignoreResources(Integer[] resourceIds);
+ Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration); + } \ No newline at end of file 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 d6cfdba..97a7d2f 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 @@ -300,9 +300,11 @@ public class ResourceTreeView extends LocatableVLayout { // Update breadcrumbs if (currentViewId != null) { currentViewId.getBreadcrumbs().clear(); - for (int i = parents.length - 1; i >= 0; i--) { - TreeNode n = parents[i]; - adjustBreadcrumb(n, currentViewId); + if (null != parents) { + for (int i = parents.length - 1; i >= 0; i--) { + TreeNode n = parents[i]; + adjustBreadcrumb(n, currentViewId); + } } adjustBreadcrumb(selectedNode, currentViewId); CoreGUI.refreshBreadCrumbTrail(); @@ -456,13 +458,15 @@ public class ResourceTreeView extends LocatableVLayout { for (final ResourceType childType : resourceType.getChildResourceTypes()) { if (childType.isCreatable()) { MenuItem createItem = new MenuItem(childType.getName()); - createChildSubMenu.addItem(createItem); + createItem.addClickHandler(new ClickHandler() { public void onClick(MenuItemClickEvent event) { ResourceFactoryCreateWizard.showCreateWizard(resource, childType); } });
+ createChildSubMenu.addItem(createItem); + } } createChildMenu.setSubmenu(createChildSubMenu); @@ -472,21 +476,30 @@ public class ResourceTreeView extends LocatableVLayout { // Manually Add Menu MenuItem importChildMenu = new MenuItem("Import"); Menu importChildSubMenu = new Menu(); - for (ResourceType childType : resourceType.getChildResourceTypes()) { + for (final ResourceType childType : resourceType.getChildResourceTypes()) { if (childType.isSupportsManualAdd()) { - importChildSubMenu.addItem(new MenuItem(childType.getName())); - //todo action + MenuItem importItem = new MenuItem(childType.getName()); + + importItem.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + ResourceFactoryCreateWizard.showImportWizard(resource, childType); + } + }); + + importChildSubMenu.addItem(importItem); } } + if (resourceType.getCategory() == ResourceCategory.PLATFORM) { - loadManuallyAddServersToPlatforms(importChildSubMenu); + loadManuallyAddServersToPlatforms(importChildSubMenu, resource); } + importChildMenu.setSubmenu(importChildSubMenu); importChildMenu.setEnabled(importChildSubMenu.getItems().length > 0); resourceContextMenu.addItem(importChildMenu); }
- private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu) { + private void loadManuallyAddServersToPlatforms(final Menu manuallyAddMenu, final Resource resource) { ResourceTypeGWTServiceAsync rts = GWTServiceLookup.getResourceTypeGWTService();
ResourceTypeCriteria criteria = new ResourceTypeCriteria(); @@ -498,9 +511,16 @@ public class ResourceTreeView extends LocatableVLayout { }
public void onSuccess(PageList<ResourceType> result) { - for (ResourceType type : result) { + for (final ResourceType type : result) { if (type.getParentResourceTypes() == null || type.getParentResourceTypes().isEmpty()) { MenuItem item = new MenuItem(type.getName()); + + item.addClickHandler(new ClickHandler() { + public void onClick(MenuItemClickEvent event) { + ResourceFactoryCreateWizard.showImportWizard(resource, type); + } + }); + manuallyAddMenu.addItem(item); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java index 84c6b55..5d7fbdc 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationStep.java @@ -49,6 +49,7 @@ public class ConfigurationStep extends AbstractWizardStep { }
public boolean nextPage() { + wizard.execute(); return true; }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java index 0db5af8..a588010 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/factory/ConfigurationTemplateStep.java @@ -20,6 +20,7 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.factory;
import java.util.Map;
+import com.smartgwt.client.types.TitleOrientation; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.SelectItem; @@ -49,10 +50,17 @@ public class ConfigurationTemplateStep extends AbstractWizardStep {
form = new LocatableDynamicForm("ResFactConfigTemplate");
- TextItem nameItem = new TextItem("resourceName", "Resource Name"); - nameItem.setRequired(true); + TextItem nameItem = null;
- SelectItem templateSelect = new SelectItem("template", "Template"); + if (!this.wizard.isImport()) { + nameItem = new TextItem("resourceName", "New Resource Name"); + nameItem.setWidth(300); + nameItem.setRequired(true); + } + + SelectItem templateSelect = new SelectItem("template", "Connection Property Templates (Choose One)"); + templateSelect.setTitleOrientation(TitleOrientation.TOP); + templateSelect.setWidth(300);
ConfigurationDefinition definition = wizard.getConfigurationDefinition();
@@ -64,9 +72,14 @@ public class ConfigurationTemplateStep extends AbstractWizardStep { templateSelect.setDisabled(true); }
- form.setItems(nameItem, templateSelect); + if (null != nameItem) { + form.setItems(nameItem, templateSelect); + } else { + form.setItems(templateSelect); + }
} + return form; }
@@ -75,7 +88,7 @@ public class ConfigurationTemplateStep extends AbstractWizardStep { }
public String getName() { - return "New Resource"; + return "Resource Information"; }
public Configuration getConfiguration() { 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 bad2058..7968635 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,14 +19,9 @@ 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.List;
import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.widgets.IButton; -import com.smartgwt.client.widgets.events.ClickEvent; -import com.smartgwt.client.widgets.events.ClickHandler;
import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.configuration.definition.ConfigurationDefinition; @@ -48,6 +43,7 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { private ConfigurationDefinition configurationDefinition; private Resource parentResource; private ResourceType createType; + private boolean isImport; // manual add vs. create new child
private WizardView view;
@@ -55,10 +51,11 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { private ConfigurationStep configurationStep;
public ResourceFactoryCreateWizard(Resource parentResource, ResourceType createType, - ConfigurationDefinition configurationDefinition) { + ConfigurationDefinition configurationDefinition, boolean isImport) { this.parentResource = parentResource; this.createType = createType; this.configurationDefinition = configurationDefinition; + this.isImport = isImport;
assert parentResource != null; assert createType != null; @@ -66,8 +63,12 @@ public class ResourceFactoryCreateWizard extends AbstractWizard {
ArrayList<WizardStep> steps = new ArrayList<WizardStep>();
- configurationTemplateStep = new ConfigurationTemplateStep(this); - steps.add(configurationTemplateStep); + // skip the template step if this is an import (no resource name to be gathered) and the + // type has only the default template to offer for user selection. + if (!(this.isImport && this.configurationDefinition.getTemplates().size() < 2)) { + this.configurationTemplateStep = new ConfigurationTemplateStep(this); + steps.add(configurationTemplateStep); + }
configurationStep = new ConfigurationStep(this); steps.add(configurationStep); @@ -76,52 +77,57 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { }
public String getWindowTitle() { - return "Resource Create Wizard"; + return isImport() ? "Import Resource Wizard" : "Resource Create Wizard"; }
public String getTitle() { - return "Create New " + createType.getName(); + return (isImport() ? "Import Resource of Type: " : "Create New Resource of Type: ") + createType.getName(); }
public String getSubtitle() { return null; }
- public List<IButton> getCustomButtons(int step) { - switch (step) { - case 1: - IButton createButton = new IButton("Create"); - createButton.addClickHandler(new ClickHandler() { - public void onClick(ClickEvent clickEvent) { - execute(); - } - }); - return Collections.singletonList(createButton); - } - return null; - } - - private void execute() { + public void execute() {
- int parentReourceId = parentResource.getId(); + int parentResourceId = parentResource.getId(); int createTypeId = createType.getId(); - String newResourceName = configurationTemplateStep.getResourceName(); Configuration newConfiguration = configurationStep.getConfiguration();
- GWTServiceLookup.getResourceService().createResource(parentReourceId, createTypeId, newResourceName, - newConfiguration, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to create new resource", caught); - view.closeDialog(); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Submitted request to create new resource [" - + configurationTemplateStep.getResourceName() + "]", Message.Severity.Info)); - view.closeDialog(); - } - }); + if (isImport) { + GWTServiceLookup.getResourceService().manuallyAddResource(createTypeId, parentResourceId, newConfiguration, + new AsyncCallback<Resource>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to manually add resource", caught); + view.closeDialog(); + } + + public void onSuccess(Resource result) { + CoreGUI.getMessageCenter().notify( + new Message("Submitted request to manually add [" + createType.getName() + "]", + Message.Severity.Info)); + view.closeDialog(); + } + }); + + } else { + String newResourceName = configurationTemplateStep.getResourceName(); + + GWTServiceLookup.getResourceService().createResource(parentResourceId, createTypeId, newResourceName, + newConfiguration, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to create new resource", caught); + view.closeDialog(); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify( + new Message("Submitted request to create new resource [" + + configurationTemplateStep.getResourceName() + "]", Message.Severity.Info)); + view.closeDialog(); + } + }); + } }
public void display() { @@ -135,7 +141,19 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { new ResourceTypeRepository.TypeLoadedCallback() { public void onTypesLoaded(ResourceType type) { ResourceFactoryCreateWizard wizard = new ResourceFactoryCreateWizard(parentResource, type, type - .getResourceConfigurationDefinition()); + .getResourceConfigurationDefinition(), false); + wizard.display(); + } + }); + } + + public static void showImportWizard(final Resource parentResource, ResourceType childType) { + ResourceTypeRepository.Cache.getInstance().getResourceTypes(childType.getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.pluginConfigurationDefinition), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + ResourceFactoryCreateWizard wizard = new ResourceFactoryCreateWizard(parentResource, type, type + .getPluginConfigurationDefinition(), true); wizard.display(); } }); @@ -146,7 +164,8 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { }
public Configuration getConfiguration() { - return configurationTemplateStep.getConfiguration(); + return (null == configurationTemplateStep) ? this.configurationDefinition.getDefaultTemplate() + .createConfiguration() : configurationTemplateStep.getConfiguration(); }
public Resource getParentResource() { @@ -157,6 +176,10 @@ public class ResourceFactoryCreateWizard extends AbstractWizard { return createType; }
+ public boolean isImport() { + return isImport; + } + public void cancel() { // TODO: revert back to original state } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 4e14b75..d256222 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -202,7 +202,7 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re platform.setChildren(servers); }
- return platforms; + return SerialUtility.prepare(platforms, "ResourceService.findRecentlyAddedResources"); } catch (Exception e) { throw new RuntimeException(ThrowableUtil.getAllMessages(e)); } @@ -281,4 +281,13 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re } }
+ public Resource manuallyAddResource(int resourceTypeId, int parentResourceId, Configuration pluginConfiguration) { + try { + Resource result = discoveryBoss.manuallyAddResource(getSessionSubject(), resourceTypeId, parentResourceId, + pluginConfiguration); + return SerialUtility.prepare(result, "ResourceService.manuallyAddResource"); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } + } } \ No newline at end of file
commit 885a5f526a3868a44d3f07f61c5df1ed1ef4ae16 Author: John Mazzitelli mazz@redhat.com Date: Mon Oct 4 17:02:47 2010 -0400
implement the new alert-role server plugin notification editor. this needs to be tested to make sure the sender still works. but the notification configuration is consistent with how it was before so it should work
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java index 3237c49..2d18670 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/RoleCriteria.java @@ -22,10 +22,13 @@ */ package org.rhq.core.domain.criteria;
+import java.util.List; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
import org.rhq.core.domain.authz.Role; +import org.rhq.core.domain.util.CriteriaUtils; import org.rhq.core.domain.util.PageOrdering;
/** @@ -39,7 +42,8 @@ public class RoleCriteria extends Criteria { private Integer filterId; private String filterDescription; private String filterName; - private Integer filterSubjectId; + private Integer filterSubjectId; // needs overrides + private List<Integer> filterIds; // needs overrides
private boolean fetchPermissions; private boolean fetchResourceGroups; @@ -54,6 +58,8 @@ public class RoleCriteria extends Criteria { + " FROM Role innerRole " // + " JOIN innerRole.subjects innerSubject " // + " WHERE innerSubject.id = ? )"); + + filterOverrides.put("ids", "id IN ( ? )"); }
@Override @@ -77,6 +83,10 @@ public class RoleCriteria extends Criteria { this.filterSubjectId = filterSubjectId; }
+ public void addFilterIds(Integer... filterIds) { + this.filterIds = CriteriaUtils.getListIgnoringNulls(filterIds); + } + /** * Requires MANAGE_SECURITY * @param fetchSubjects diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java index 7d8745d..40bd990 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java @@ -220,7 +220,7 @@ public class NewNotificationEditor extends LocatableDynamicForm { if ("System Users".equals(sender)) { newCanvas = new SystemUsersNotificationSenderForm(newLocatorId, notificationToEdit, sender); } else if ("System Roles".equals(sender)) { - newCanvas = null; // TODO + newCanvas = new SystemRolesNotificationSenderForm(newLocatorId, notificationToEdit, sender); } else if ("Resource Operations".equals(sender)) { newCanvas = null; // TODO } else { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemRolesNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemRolesNotificationSenderForm.java new file mode 100644 index 0000000..fe4cf36 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemRolesNotificationSenderForm.java @@ -0,0 +1,202 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.rhq.enterprise.gui.coregui.client.alert.definitions; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.authz.Role; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.criteria.RoleCriteria; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.admin.roles.RolesDataSource; +import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * This notification form will be used for the System Roles sender. This form lets + * you pick roles that the sender will send notifications to. + * + * @author John Mazzitelli + */ +public class SystemRolesNotificationSenderForm extends AbstractNotificationSenderForm { + + // the alert configuration property name where the IDs are stored in |-separated form + private static final String PROPNAME = "roleId"; + + private RoleSelector selector; + + public SystemRolesNotificationSenderForm(String locatorId, AlertNotification notif, String sender) { + super(locatorId, notif, sender); + } + + @Override + protected void onInit() { + super.onInit(); + + String roleIds = getConfiguration().getSimpleValue(PROPNAME, ""); // we know the role plugin defines this + if (roleIds != null && roleIds.length() > 0) { + try { + List<Integer> ids = unfence(roleIds, Integer.class); + RoleCriteria criteria = new RoleCriteria(); + criteria.addFilterIds(ids.toArray(new Integer[ids.size()])); + GWTServiceLookup.getRoleService().findRolesByCriteria(criteria, new AsyncCallback<PageList<Role>>() { + @Override + public void onSuccess(PageList<Role> result) { + createNewSelector(result); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler() + .handleError("Cannot determine current roles - starting empty", caught); + createNewSelector(null); + } + }); + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Cannot use current roles - starting empty", e); + createNewSelector(null); + } + } else { + createNewSelector(null); + } + } + + private void createNewSelector(Collection<Role> preselectedRoles) { + String selectorLocatorId = extendLocatorId("roleSelector"); + selector = new RoleSelector(selectorLocatorId, preselectedRoles); + selector.setWidth(400); + selector.setHeight(300); + addMember(selector); + markForRedraw(); + } + + @Override + public boolean validate() { + if (selector != null) { + try { + HashSet<Integer> selectedIds = selector.getSelection(); + String newPropValue = fence(selectedIds); + getConfiguration().put(new PropertySimple(PROPNAME, newPropValue)); + return true; + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Cannot save the selected roles", e); + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + private <T> List<T> unfence(String fencedData, Class<T> type) { + String delimiter = "\|"; + String[] elements = fencedData.split(delimiter); + List<T> results = new ArrayList<T>(elements.length); + + if (Integer.class.equals(type)) { + for (String next : elements) { + if (next.length() != 0) { + results.add((T) Integer.valueOf(next)); + } + } + } else if (String.class.equals(type)) { + for (String next : elements) { + if (next.length() != 0) { + results.add((T) next); + } + } + } else { + throw new IllegalArgumentException("No support for unfencing data of type " + type); + } + return results; + } + + /** + * Takes the list of elements e1, e2, e3 and fences + * them with '|' delimiters such that the result looks + * like "|e1|e2|e3|" + */ + private String fence(Collection<?> elements) { + if (elements.size() == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(); + builder.append('|'); + for (Object next : elements) { + builder.append(String.valueOf(next)).append('|'); + } + return builder.toString(); + } + + private class RoleSelector extends AbstractSelector<Role> { + + public RoleSelector(String id, Collection<Role> roles) { + super(id); + if (roles != null) { + ListGridRecord[] data = (new RolesDataSource()).buildRecords(roles); + setAssigned(data); + } + } + + @Override + protected RPCDataSource<Role> getDataSource() { + return new SelectedRolesDataSource(); + } + + @Override + protected DynamicForm getAvailableFilterForm() { + return null; // No Filters Currently + } + + @Override + protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { + return null; // No Filters Currently + } + + public class SelectedRolesDataSource extends RolesDataSource { + + @Override + public ListGridRecord[] buildRecords(Collection<Role> roles) { + ListGridRecord[] records = super.buildRecords(roles); + for (ListGridRecord record : records) { + if (selection.contains(record.getAttributeAsInt("id"))) { + record.setEnabled(false); + } + } + return records; + } + } + + } +} diff --git a/modules/enterprise/server/plugins/alert-roles/src/main/java/org/rhq/enterprise/server/plugins/alertRoles/RolesBackingBean.java b/modules/enterprise/server/plugins/alert-roles/src/main/java/org/rhq/enterprise/server/plugins/alertRoles/RolesBackingBean.java deleted file mode 100644 index a7f556e..0000000 --- a/modules/enterprise/server/plugins/alert-roles/src/main/java/org/rhq/enterprise/server/plugins/alertRoles/RolesBackingBean.java +++ /dev/null @@ -1,83 +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.enterprise.server.plugins.alertRoles; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.rhq.core.domain.authz.Role; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.util.PageControl; -import org.rhq.enterprise.server.plugin.pc.alert.AlertSender; -import org.rhq.enterprise.server.plugin.pc.alert.CustomAlertSenderBackingBean; -import org.rhq.enterprise.server.util.LookupUtil; - -/** - * Backing Bean for the roles sender alert sender plugin custom UI - * @author Joseph Marques - */ -public class RolesBackingBean extends CustomAlertSenderBackingBean { - - private Map<String, String> available; - private List<String> currentRoles; - private static final String ROLE_ID = "roleId"; - - @Override - public void loadView() { - // get available/all subjects - List<Role> allRoles = LookupUtil.getRoleManager().findRoles(new PageControl()); - available = new HashMap<String, String>(); - for (Role role : allRoles) { - String roleId = String.valueOf(role.getId()); - available.put(role.getName(), roleId); - } - - // get current subjects - String subjectString = alertParameters.getSimpleValue(ROLE_ID, ""); - currentRoles = AlertSender.unfence(subjectString, String.class); - } - - @Override - public void saveView() { - String roleIds = AlertSender.fence(currentRoles); - - PropertySimple p = alertParameters.getSimple(ROLE_ID); - if (p == null) { - p = new PropertySimple(ROLE_ID, roleIds); - alertParameters.put(p); - } else { - p.setStringValue(roleIds); - } - - alertParameters = persistConfiguration(alertParameters); - } - - public List<String> getCurrentRoles() { - return currentRoles; - } - - public void setCurrentRoles(List<String> currentRoles) { - this.currentRoles = currentRoles; - } - - public Map<String, String> getAvailableRolesMap() { - return available; - } -} diff --git a/modules/enterprise/server/plugins/alert-roles/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-roles/src/main/resources/META-INF/rhq-serverplugin.xml index 7d7551c..4e50100 100644 --- a/modules/enterprise/server/plugins/alert-roles/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-roles/src/main/resources/META-INF/rhq-serverplugin.xml @@ -14,19 +14,13 @@ Used to send notifications to all users in the selected system roles. </serverplugin:help>
- <!-- startup & tear down listener, + scheduled jobs - <serverplugin:plugin-component class="Foo" /> - --> - <!-- How does this sender show up in drop downs etc --> <short-name>System Roles</short-name>
<!-- Class that does the actual sending --> <plugin-class>RolesSender</plugin-class>
- <custom-ui> - <ui-snippet-name>roles.xhtml</ui-snippet-name> - <backing-bean-class>RolesBackingBean</backing-bean-class> - <backing-bean-name>rolesBean</backing-bean-name> - </custom-ui> + <alert-configuration> + <c:simple-property name="roleId" type="string" required="true" description="The roles (ids are |-separated) to be notified"/> + </alert-configuration> </alert-plugin> \ No newline at end of file diff --git a/modules/enterprise/server/plugins/alert-roles/src/main/resources/roles.xhtml b/modules/enterprise/server/plugins/alert-roles/src/main/resources/roles.xhtml deleted file mode 100644 index f807414..0000000 --- a/modules/enterprise/server/plugins/alert-roles/src/main/resources/roles.xhtml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:c="http://java.sun.com/jstl/core" - xmlns:a4j="https://richfaces.org/a4j" - xmlns:rich="http://richfaces.ajax4jsf.org/rich%22%3E - -<body> - <rich:pickList fastMoveControlsVisible="false" - sourceListWidth="200px" - targetListWidth="200px" - copyControlLabel="Add Roles" - removeControlLabel="Remove Roles" - value="#{rolesBean.currentRoles}"> - <f:selectItems value="#{rolesBean.availableRolesMap}" /> - </rich:pickList> -</body> - -</html> \ No newline at end of file
commit c1145e500bd70a985a0b609de0f42655902d23a6 Author: Ian Springer ian.springer@redhat.com Date: Mon Oct 4 16:58:21 2010 -0400
finish support for top-level maps - both static and dynamic/open; disable window logger
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index ed2ce42..c486f1d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -38,7 +38,9 @@ 2. In hosted mode, the windows are not automatically closed, although you can easily close them manually in the usual way --> + <!-- <set-property name="log_WindowLogger" value="ENABLED" /> + -->
<!-- You probably will want to disable the default `DivLogger` as well: 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 fdc2d9c..d9c3dd7 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 @@ -19,6 +19,7 @@ package org.rhq.enterprise.gui.coregui.client.components.configuration;
import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; @@ -29,6 +30,7 @@ import java.util.List; import java.util.Map; import java.util.Set;
+import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.data.Record; import com.smartgwt.client.types.Alignment; @@ -138,9 +140,12 @@ import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
/** + * A SmartGWT widget for editing an RHQ {@link Configuration}, which conforms to a {@link ConfigurationDefinition}. + * * @author Greg Hinkle * @author Ian Springer */ +@SuppressWarnings({"UnnecessarySemicolon"}) public class ConfigurationEditor extends LocatableVLayout { private ConfigurationGWTServiceAsync configurationService = GWTServiceLookup.getConfigurationService();
@@ -170,7 +175,6 @@ public class ConfigurationEditor extends LocatableVLayout { public static enum ConfigType { plugin, resource } - ; // Need this extra semicolon for the qdox parser
public ConfigurationEditor(String locatorId) { @@ -330,6 +334,11 @@ public class ConfigurationEditor extends LocatableVLayout { this.markForRedraw(); }
+ public void reset() { + this.configuration = this.originalConfiguration; + reload(); + } + protected HLayout buildRawPane() {
LocatableHLayout layout = new LocatableHLayout(extendLocatorId("Raw")); @@ -457,7 +466,6 @@ public class ConfigurationEditor extends LocatableVLayout { }
public SectionStackSection buildGroupSection(String locatorId, PropertyGroupDefinition group) { - SectionStackSection section; if (group == null) { section = new SectionStackSection("General Properties"); @@ -473,18 +481,25 @@ public class ConfigurationEditor extends LocatableVLayout { section.setExpanded(!group.isDefaultHidden()); }
- ArrayList<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(((group == null) ? definition - .getNonGroupedProperties() : definition.getPropertiesInGroup(group.getName()))); - Collections.sort(definitions, new PropertyDefinitionComparator()); + List<PropertyDefinition> propertyDefinitions = new ArrayList<PropertyDefinition>(((group == null) ? definition + .getNonGroupedProperties() : definition.getPropertiesInGroup(group.getName())));
- DynamicForm form = buildPropertiesForm(locatorId + "_Props", definitions, configuration); + DynamicForm form = buildPropertiesForm(locatorId + "_Props", propertyDefinitions, configuration);
section.addItem(form); return section; }
- private DynamicForm buildPropertiesForm(String locatorId, List<PropertyDefinition> definitions, + private DynamicForm buildPropertiesForm(String locatorId, Collection<PropertyDefinition> propertyDefinitions, AbstractPropertyMap propertyMap) { + List<PropertyDefinition> propertyDefinitionsList; + if (!(propertyDefinitions instanceof List)) { + propertyDefinitionsList = new ArrayList<PropertyDefinition>(propertyDefinitions); + } else { + propertyDefinitionsList = (List<PropertyDefinition>)propertyDefinitions; + } + Collections.sort(propertyDefinitionsList, new PropertyDefinitionComparator()); + LocatableDynamicForm form = new LocatableDynamicForm(locatorId); form.setValuesManager(valuesManager); form.setValidateOnChange(true); @@ -503,11 +518,17 @@ public class ConfigurationEditor extends LocatableVLayout { form.setCellPadding(5); form.setColWidths(190, 28, 210);
- ArrayList<FormItem> fields = new ArrayList<FormItem>(); + List<FormItem> fields = new ArrayList<FormItem>(); + addItemsForPropertiesRecursively(locatorId, propertyDefinitionsList, propertyMap, fields); + form.setFields(fields.toArray(new FormItem[fields.size()])); + + return form; + }
+ private void addItemsForPropertiesRecursively(String locatorId, Collection<PropertyDefinition> propertyDefinitions, + AbstractPropertyMap propertyMap, List<FormItem> fields) { boolean odd = true; - - for (PropertyDefinition propertyDefinition : definitions) { + for (PropertyDefinition propertyDefinition : propertyDefinitions) { Property property = propertyMap.get(propertyDefinition.getName()); if (property == null) { if (propertyDefinition instanceof PropertyDefinitionSimple) { @@ -515,17 +536,17 @@ public class ConfigurationEditor extends LocatableVLayout { propertyMap.put(property); } } - addItems(locatorId + "_" + propertyDefinition.getName(), fields, propertyDefinition, property, odd); + addItemsForPropertyRecursively(locatorId + "_" + propertyDefinition.getName(), propertyDefinition, property, + odd, fields); odd = !odd; } - - form.setFields(fields.toArray(new FormItem[fields.size()])); - - return form; }
- public void addItems(String locatorId, ArrayList<FormItem> fields, PropertyDefinition propertyDefinition, - Property property, boolean oddRow) { + public void addItemsForPropertyRecursively(String locatorId, PropertyDefinition propertyDefinition, + Property property, + boolean oddRow, + List<FormItem> fields) { + List<FormItem> fieldsForThisProperty = new ArrayList<FormItem>();
StaticTextItem nameItem = new StaticTextItem(); nameItem.setStartRow(true); @@ -534,30 +555,50 @@ public class ConfigurationEditor extends LocatableVLayout { .getName()) + "</b>"; nameItem.setValue(title); nameItem.setShowTitle(false); - nameItem.setCellStyle(oddRow ? "OddRow" : "EvenRow");
+ fieldsForThisProperty.add(nameItem); fields.add(nameItem);
FormItem valueItem; if (propertyDefinition instanceof PropertyDefinitionSimple) { - valueItem = buildSimpleField(fields, (PropertyDefinitionSimple) propertyDefinition, oddRow, property); + PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple)propertyDefinition; + PropertySimple propertySimple = (PropertySimple)property; + + valueItem = buildSimpleField(propertyDefinitionSimple, propertySimple); + + FormItem unsetItem = buildUnsetItem(propertyDefinitionSimple, propertySimple, valueItem); + fieldsForThisProperty.add(unsetItem); + fields.add(unsetItem); + + fieldsForThisProperty.add(valueItem); fields.add(valueItem);
StaticTextItem descriptionItem = new StaticTextItem(); descriptionItem.setValue(propertyDefinition.getDescription()); descriptionItem.setShowTitle(false); descriptionItem.setEndRow(true); - descriptionItem.setCellStyle(oddRow ? "OddRow" : "EvenRow"); + fieldsForThisProperty.add(descriptionItem); fields.add(descriptionItem); } else if (propertyDefinition instanceof PropertyDefinitionList) { if (((PropertyDefinitionList) propertyDefinition).getMemberDefinition() instanceof PropertyDefinitionMap) { // List of Maps is a specially supported case with summary fields as columns in a table - buildListOfMapsField(locatorId, fields, - (PropertyDefinitionMap) ((PropertyDefinitionList) propertyDefinition).getMemberDefinition(), - oddRow, (PropertyList) property); + // Note: This field spans 3 columns. + CanvasItem listOfMapsItem = buildListOfMapsField(locatorId, + (PropertyDefinitionMap)((PropertyDefinitionList)propertyDefinition).getMemberDefinition(), + oddRow, (PropertyList)property); + fields.add(listOfMapsItem); } + // TODO (ips): Add support for lists of simples. } else if (propertyDefinition instanceof PropertyDefinitionMap) { - buildMapsField(fields, (PropertyDefinitionMap) propertyDefinition, (PropertyMap) property); + // Note: This field spans 3 columns. + FormItem mapField = + buildMapField(locatorId, (PropertyDefinitionMap)propertyDefinition, (PropertyMap)property); + fields.add(mapField); + } + + // Set row background color. + for (FormItem field : fieldsForThisProperty) { + field.setCellStyle(oddRow ? "OddRow" : "EvenRow"); } }
@@ -565,13 +606,39 @@ public class ConfigurationEditor extends LocatableVLayout { return this.invalidPropertyNames; }
- private void buildMapsField(ArrayList<FormItem> fields, PropertyDefinitionMap propertyDefinitionMap, - final PropertyMap propertyMap) { + private FormItem buildMapField(String parentLocatorId, PropertyDefinitionMap propertyDefinitionMap, + final PropertyMap propertyMap) { + Canvas canvas; + Map<String, PropertyDefinition> memberPropertyDefinitions = propertyDefinitionMap.getPropertyDefinitions(); + String locatorId = parentLocatorId + "_" + propertyDefinitionMap.getName(); + if (memberPropertyDefinitions == null || memberPropertyDefinitions.isEmpty()) { + canvas = buildDynamicMapField(locatorId, propertyDefinitionMap, propertyMap); + } else { + canvas = buildStaticMapField(locatorId, propertyDefinitionMap, propertyMap); + } + CanvasItem canvasItem = buildComplexPropertyField(canvas); + + return canvasItem; + } + + private CanvasItem buildComplexPropertyField(Canvas canvas) { + CanvasItem canvasItem = new CanvasItem(); + canvasItem.setCanvas(canvas); + canvasItem.setColSpan(3); + canvasItem.setEndRow(true); + canvasItem.setShowTitle(false); + return canvasItem; + } + + private Canvas buildDynamicMapField(String parentLocatorId, PropertyDefinitionMap propertyDefinitionMap, + final PropertyMap propertyMap) { + Log.debug("Building dynamic map field for " + propertyMap + "..."); + // create the property grid final PropertyGrid propertyGrid = new PropertyGrid(); propertyGrid.getNameField().setName("Name"); propertyGrid.getValuesField().setName("Value"); - + // create the editors Map<String, FormItem> editorsMap = new HashMap<String, FormItem>(); TextItem textEditor = new TextItem(); @@ -580,27 +647,26 @@ public class ConfigurationEditor extends LocatableVLayout { // set the editors and attribute name where to find the record type propertyGrid.setEditorsMap("fieldType", editorsMap);
- if (propertyDefinitionMap != null) { - ListGridRecord[] records = new ListGridRecord[propertyDefinitionMap.getPropertyDefinitions().size()]; - int i = 0; - // TODO (ips): For open maps, create the records based on props, not propDefs. - // TODO (ips): Render unset checkboxes amd descriptions for member props, just as we would for top-level simples. - for (PropertyDefinition propDef : propertyDefinitionMap.getPropertyDefinitions().values()) { - ListGridRecord record = new ListGridRecord(); - String propertyName = propDef.getName(); - record.setAttribute("Name", propertyName); - PropertySimple prop = propertyMap.getSimple(propertyName); - String value = (prop != null) ? prop.getStringValue() : null; - record.setAttribute("Value", value); - record.setAttribute("fieldType", "simpleText"); - record.setAttribute("readOnly", propDef.isReadOnly()); - records[i++] = record; + ListGridRecord[] records = new ListGridRecord[propertyMap.getMap().size()]; + int i = 0; + for (Property prop : propertyMap.getMap().values()) { + if (!(prop instanceof PropertySimple)) { + Log.warn("Unsupported Configuration permutation: PropertyMap " + propertyMap + + " contains non-simple member Property " + prop + " - skipping..."); + continue; } - propertyGrid.setData(records); + PropertySimple propSimple = (PropertySimple)prop; + ListGridRecord record = new ListGridRecord(); + String propertyName = prop.getName(); + record.setAttribute("Name", propertyName); + String value = propSimple.getStringValue(); + record.setAttribute("Value", value); + record.setAttribute("fieldType", "simpleText"); + records[i++] = record; } + propertyGrid.setData(records);
VLayout canvas = new VLayout(); - canvas.addMember(propertyGrid);
// Footer @@ -610,8 +676,8 @@ public class ConfigurationEditor extends LocatableVLayout { footer.setMembersMargin(15); canvas.addMember(footer);
- // Properties can only be added to or deleted from non-read-only "open" maps. - if (propertyDefinitionMap.getPropertyDefinitions().isEmpty() && !propertyDefinitionMap.isReadOnly()) { + // Properties can only be added to or deleted from non-read-only dynamic maps. + if (!propertyDefinitionMap.isReadOnly()) { final IButton deleteButton = new LocatableIButton(extendLocatorId(propertyMap.getName()), "Delete"); deleteButton.setDisabled(true); deleteButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { @@ -688,19 +754,21 @@ public class ConfigurationEditor extends LocatableVLayout { } });
- propertyGrid.draw(); - - CanvasItem canvasItem = new CanvasItem(); - canvasItem.setCanvas(canvas); - // item.setHeight(500); - canvasItem.setColSpan(3); - canvasItem.setEndRow(true); - canvasItem.setShowTitle(false); - fields.add(canvasItem); + return canvas; + } + + private Canvas buildStaticMapField(String parentLocatorId, PropertyDefinitionMap propertyDefinitionMap, + PropertyMap propertyMap) { + Log.debug("Building static map field for " + propertyMap + "..."); + + return buildPropertiesForm(parentLocatorId, propertyDefinitionMap.getPropertyDefinitions().values(), propertyMap); + }
- private void buildListOfMapsField(final String locatorId, ArrayList<FormItem> fields, - final PropertyDefinitionMap propertyDefinition, boolean oddRow, final PropertyList propertyList) { + private CanvasItem buildListOfMapsField(final String locatorId, + final PropertyDefinitionMap memberPropertyDefinitionMap, boolean oddRow, + final PropertyList propertyList) { + Log.debug("Building list-of-maps field for " + propertyList + "...");
final ListGrid summaryTable = new ListGrid(); // summaryTable.setID("config_summaryTable_" + propertyDefinition.getName()); @@ -711,7 +779,7 @@ public class ConfigurationEditor extends LocatableVLayout { summaryTable.setAutoFitData(Autofit.HORIZONTAL);
ArrayList<ListGridField> fieldsList = new ArrayList<ListGridField>(); - ArrayList<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(propertyDefinition + ArrayList<PropertyDefinition> definitions = new ArrayList<PropertyDefinition>(memberPropertyDefinitionMap .getPropertyDefinitions().values()); Collections.sort(definitions, new PropertyDefinitionComparator());
@@ -757,7 +825,7 @@ public class ConfigurationEditor extends LocatableVLayout { public void onRecordClick(RecordClickEvent recordClickEvent) { com.allen_sauer.gwt.log.client.Log.info("You want to edit: " + recordClickEvent.getRecord()); displayMapEditor(locatorId + "_MapEdit", summaryTable, recordClickEvent.getRecord(), - propertyDefinition, propertyList, (PropertyMap) recordClickEvent.getRecord().getAttributeAsObject( + memberPropertyDefinitionMap, propertyList, (PropertyMap) recordClickEvent.getRecord().getAttributeAsObject( "_RHQ_PROPERTY")); } }); @@ -805,7 +873,7 @@ public class ConfigurationEditor extends LocatableVLayout { addRowButton.setIcon(Window.getImgURL("[SKIN]/actions/add.png")); addRowButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() { public void onClick(ClickEvent clickEvent) { - displayMapEditor(locatorId + "_MapEdit", summaryTable, null, propertyDefinition, propertyList, null); + displayMapEditor(locatorId + "_MapEdit", summaryTable, null, memberPropertyDefinitionMap, propertyList, null); } });
@@ -813,13 +881,9 @@ public class ConfigurationEditor extends LocatableVLayout {
summaryTableHolder.setMembers(summaryTable, toolStrip);
- CanvasItem item = new CanvasItem(); - item.setCanvas(summaryTableHolder); - // item.setHeight(500); - item.setColSpan(3); - item.setEndRow(true); - item.setShowTitle(false); - fields.add(item); + CanvasItem item = buildComplexPropertyField(summaryTableHolder); + + return item; }
private ListGridRecord[] buildSummaryRecords(PropertyList propertyList, ArrayList<PropertyDefinition> definitions) { @@ -827,7 +891,6 @@ public class ConfigurationEditor extends LocatableVLayout { int i = 0; for (Property row : propertyList.getList()) { PropertyMap rowMap = (PropertyMap) row; - ListGridRecord record = buildSummaryRecord(definitions, rowMap); rows[i++] = record; } @@ -871,32 +934,13 @@ public class ConfigurationEditor extends LocatableVLayout { return record; }
- private FormItem buildSimpleField(ArrayList<FormItem> fields, final PropertyDefinitionSimple propertyDefinition, - boolean oddRow, final Property property) { - final PropertySimple propertySimple = (PropertySimple) property; + private FormItem buildSimpleField(final PropertyDefinitionSimple propertyDefinition, + final PropertySimple propertySimple + ) { + Log.debug("Building simple field for " + propertySimple + "...");
FormItem valueItem = null;
- boolean isUnset = (property == null || propertySimple.getStringValue() == null) - && propertyDefinition.isRequired() == false; - - CheckboxItem unsetItem = null; - if (!propertyDefinition.isRequired()) { - unsetItem = new CheckboxItem(); - unsetItem.setValue(isUnset); - unsetItem.setDisabled(readOnly); - unsetItem.setShowLabel(false); - unsetItem.setShowTitle(false); - unsetItem.setLabelAsTitle(false); - unsetItem.setColSpan(1); - unsetItem.setCellStyle(oddRow ? "OddRow" : "EvenRow"); - fields.add(unsetItem); - } else { - SpacerItem spacer = new SpacerItem(); - spacer.setCellStyle(oddRow ? "OddRow" : "EvenRow"); - fields.add(spacer); - } - List<PropertyDefinitionEnumeration> enumeratedValues = propertyDefinition.getEnumeratedValues(); if (enumeratedValues != null && !enumeratedValues.isEmpty()) {
@@ -911,7 +955,7 @@ public class ConfigurationEditor extends LocatableVLayout { valueItem = new RadioGroupItem(); } valueItem.setValueMap(valueOptions); - if (property != null) { + if (propertySimple != null) { valueItem.setValue(propertySimple.getStringValue()); } } else { @@ -921,15 +965,15 @@ public class ConfigurationEditor extends LocatableVLayout { case FILE: case DIRECTORY: valueItem = new TextItem(); - valueItem.setValue(property == null ? "" : propertySimple.getStringValue()); + valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); break; case LONG_STRING: valueItem = new TextAreaItem(); - valueItem.setValue(property == null ? "" : propertySimple.getStringValue()); + valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); break; case PASSWORD: valueItem = new PasswordItem(); - valueItem.setValue(property == null ? "" : propertySimple.getStringValue()); + valueItem.setValue(propertySimple == null ? "" : propertySimple.getStringValue()); break; case BOOLEAN: valueItem = new RadioGroupItem(); @@ -937,19 +981,19 @@ public class ConfigurationEditor extends LocatableVLayout { valMap.put("true", "Yes"); valMap.put("false", "No"); valueItem.setValueMap(valMap); - valueItem.setValue(property == null || propertySimple.getStringValue() == null ? false : propertySimple + valueItem.setValue(propertySimple == null || propertySimple.getStringValue() == null ? false : propertySimple .getBooleanValue()); break; case INTEGER: case LONG: valueItem = new IntegerItem(); - if (property != null && propertySimple.getStringValue() != null) + if (propertySimple != null && propertySimple.getStringValue() != null) valueItem.setValue(propertySimple.getLongValue()); break; case FLOAT: case DOUBLE: valueItem = new FloatItem(); - valueItem.setValue(property == null || propertySimple.getStringValue() == null ? 0 : propertySimple + valueItem.setValue(propertySimple == null || propertySimple.getStringValue() == null ? 0 : propertySimple .getDoubleValue()); break; } @@ -957,7 +1001,7 @@ public class ConfigurationEditor extends LocatableVLayout {
valueItem.setRequired(propertyDefinition.isRequired());
- List<Validator> validators = buildValidators(propertyDefinition, property); + List<Validator> validators = buildValidators(propertyDefinition, propertySimple); valueItem.setValidators(validators.toArray(new Validator[validators.size()]));
/* @@ -973,9 +1017,8 @@ public class ConfigurationEditor extends LocatableVLayout { */
valueItem.setShowTitle(false); - valueItem.setDisabled(isUnset || readOnly); + valueItem.setDisabled(isReadOnly(propertyDefinition) || isUnset(propertyDefinition, propertySimple)); valueItem.setWidth(220); - valueItem.setCellStyle(oddRow ? "OddRow" : "EvenRow");
final FormItem finalValueItem = valueItem;
@@ -992,30 +1035,56 @@ public class ConfigurationEditor extends LocatableVLayout { boolean isValidNow = ConfigurationEditor.this.invalidPropertyNames.isEmpty(); boolean validationStateChanged = (isValidNow != wasValidBefore); for (PropertyValueChangeListener validationStateChangeListener : ConfigurationEditor.this.validationStateChangeListeners) { - PropertyValueChangeEvent event = new PropertyValueChangeEvent(property, propertyDefinition, + PropertyValueChangeEvent event = new PropertyValueChangeEvent(propertySimple, propertyDefinition, validationStateChanged, ConfigurationEditor.this.invalidPropertyNames); validationStateChangeListener.propertyValueChanged(event); } } });
- if (unsetItem != null) { + return valueItem; + } + + private boolean isUnset(PropertyDefinitionSimple propertyDefinition, PropertySimple propertySimple) { + return (!propertyDefinition.isRequired() && + (propertySimple == null || propertySimple.getStringValue() == null)); + } + + private FormItem buildUnsetItem(PropertyDefinitionSimple propertyDefinition, final PropertySimple property, + final FormItem valueItem) { + FormItem item; + if (!propertyDefinition.isRequired()) { + CheckboxItem unsetItem = new CheckboxItem(); + boolean unset = isUnset(propertyDefinition, property); + unsetItem.setValue(unset); + unsetItem.setDisabled(isReadOnly(propertyDefinition)); + unsetItem.setShowLabel(false); + unsetItem.setShowTitle(false); + unsetItem.setLabelAsTitle(false); + unsetItem.setColSpan(1); + unsetItem.addChangeHandler(new ChangeHandler() { public void onChange(ChangeEvent changeEvent) { Boolean isUnset = (Boolean) changeEvent.getValue(); if (isUnset) { - finalValueItem.setDisabled(true); - finalValueItem.setValue((String) null); + valueItem.setDisabled(true); + valueItem.setValue((String) null); } else { - finalValueItem.setDisabled(false); - finalValueItem.focusInItem(); + valueItem.setDisabled(false); + valueItem.focusInItem(); } - propertySimple.setValue(finalValueItem.getValue()); + property.setValue(valueItem.getValue()); } }); + item = unsetItem; + } else { + item = new SpacerItem(); } + return item; + }
- return valueItem; + private boolean isReadOnly(PropertyDefinition propertyDefinition) { + return propertyDefinition.isReadOnly() || this.readOnly; }
private List<Validator> buildValidators(PropertyDefinitionSimple propertyDefinition, Property property) {
commit 5e74d53f806d7d87fa769647a5be15827077806f Author: John Sanda jsanda@redhat.com Date: Mon Oct 4 16:02:31 2010 -0400
Adding more tests, and adding call to set type on updated property definition
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java index 04a3995..f46c7a4 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBean.java @@ -367,6 +367,8 @@ public class ConfigurationMetadataManagerBean implements ConfigurationMetadataMa if (newProperty instanceof PropertyDefinitionSimple) { PropertyDefinitionSimple newPDS = (PropertyDefinitionSimple) newProperty;
+ existingPDS.setType(newPDS.getType()); + // handle <property-options>? List<PropertyDefinitionEnumeration> existingOptions = existingPDS.getEnumeratedValues(); List<PropertyDefinitionEnumeration> newOptions = newPDS.getEnumeratedValues(); diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java index 5e2913b..2324a43 100644 --- a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java +++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/metadata/ConfigurationMetadataManagerBeanTest.java @@ -23,6 +23,8 @@
package org.rhq.enterprise.server.configuration.metadata;
+import java.util.List; + import javax.persistence.EntityManager; import javax.transaction.SystemException;
@@ -32,6 +34,9 @@ import org.testng.annotations.Test; import org.rhq.core.clientapi.descriptor.plugin.PluginDescriptor; import org.rhq.core.clientapi.descriptor.plugin.ServerDescriptor; 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.core.domain.configuration.definition.PropertyGroupDefinition; import org.rhq.enterprise.server.test.AbstractEJB3Test; @@ -40,7 +45,17 @@ import org.rhq.test.AssertUtils;
import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.loadPluginConfigDefFor; import static org.rhq.enterprise.server.configuration.metadata.PluginDescriptorUtil.loadPluginDescriptor; - +import static java.util.Arrays.asList; + +/** + * These are data-driven tests that exercise the plugin upgrade functionality around configurations such as plugin + * configurations and resource configurations. The data sets that are used are defined in two plugin descriptors. One + * is the original version and the other is the upgraded version. In order to avoid inter-dependencies between test + * methods, a separate plugin configuration should be used for each test method. A separate resource type is declared + * for each test, further documenting and delinating where each configuration is used. In the test methods, the + * original and updated coniguration definitions are initialized with an xpath expression that specifies the owning + * resource type. + */ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
PluginDescriptor originalDescriptor; @@ -62,7 +77,7 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { }
@Test - public void addNewUngroupedPropertyDef() { + public void addNewUngroupedSimplePropertyDef() { initConfigDefs("servers[name='MyServer1']", "test");
String propertyName = "newUngroupedProperty"; @@ -93,13 +108,7 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { "not change", expected, actual); }
- // This test fails with, - // - // PersistentObjectException: detached entity passed to persist - // - // I get the exception with both PropertyGroupDefinition and PropertyDefinitionSimple when I have tried various - // approaches to get past the exception. - @Test(enabled = false) + @Test public void addNewGroup() { initConfigDefs("servers[name='GroupTests']", "GroupTests");
@@ -107,14 +116,50 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { findGroup("newGroup", originalConfigDef)); }
-// void assertGroupDefinitionExists() { -// for (PropertyGroupDefinition groupDef : originalConfigurationDef.getGroupDefinitions()) { -// if (groupDef.getName().equals("groupToBeRemoved")) { -// assertTrue(groupDef.getId() != 0); -// assertNotNull(entityMgr.find(PropertyGroupDefinition.class, groupDef.getId())); -// } -// } -// } + @Test + public void replaceMemberDefinitionOfPropertyList() { + initConfigDefs("servers[name='UpdatedPropertyList']", "ReplaceMemberDefinitionOfPropertyList"); + + String propertyName = "myList"; + PropertyDefinitionList expectedList = updatedConfigDef.getPropertyDefinitionList(propertyName); + PropertyDefinitionList actualList = originalConfigDef.getPropertyDefinitionList(propertyName); + + assertPropertyDefinitionMatches("The member definition should be replaced with the new version", expectedList, actualList); + } + + // Test is currently failing with, + // + // IllegalArgumentException: Removing a detached instance org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple + // + // I beleive that this is a problem with the test environment and not with production code. + @Test(enabled = false) + public void updateMapWithRemovedProperty() { + initConfigDefs("servers[name='UpdatedMapWithRemovedProperty']", "UpdateMapWithRemovedProperty"); + + String propertyName = "myMap"; + PropertyDefinitionMap map = originalConfigDef.getPropertyDefinitionMap(propertyName); + assertEquals("Expected property to be removed when it is removed from parent map", 0, + map.getPropertyDefinitions().size()); + } + + @Test + public void updateMapWithUpdatedProperty() { + initConfigDefs("servers[name='UpdatedMapWithUpdatedProperty']", "UpdateMapWithUpdatedProperty"); + + String propertyName = "propertyToUpdate"; + String mapPropertyName = "myMap"; + + PropertyDefinitionMap expectedMap = updatedConfigDef.getPropertyDefinitionMap(mapPropertyName); + PropertyDefinitionSimple expected = expectedMap.getPropertyDefinitionSimple(propertyName); + + PropertyDefinitionMap actualMap = originalConfigDef.getPropertyDefinitionMap(mapPropertyName); + PropertyDefinitionSimple actual = actualMap.getPropertyDefinitionSimple(propertyName); + + List<String> ignoredProperties = asList("id", "parentPropertyMapDefinition"); + + assertPropertyDefinitionMatches("Expected property who is a child of map to get updated and remain in the map", + expected, actual, ignoredProperties); + }
private void initConfigDefs(String path, String configName) { loadAndPersistConfigDefs(path, configName); @@ -132,8 +177,6 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test {
EntityManager entityMgr = getEntityManager(); entityMgr.persist(originalConfigDef); - //entityMgr.persist(updatedConfigDef); - getTransactionManager().commit(); } catch (Exception e) { try { @@ -146,21 +189,8 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { }
private void updateConfigDef() { - try { - getTransactionManager().begin(); - - ConfigurationMetadataManagerLocal configMetadataMgr = LookupUtil.getConfigurationMetadataManager(); - configMetadataMgr.updateConfigurationDefinition(updatedConfigDef, originalConfigDef); - - getTransactionManager().commit(); - } catch (Exception e) { - try { - getTransactionManager().rollback(); - } catch (SystemException e1) { - throw new RuntimeException(e1); - } - throw new RuntimeException(e); - } + ConfigurationMetadataManagerLocal configMetadataMgr = LookupUtil.getConfigurationMetadataManager(); + configMetadataMgr.updateConfigurationDefinition(updatedConfigDef, originalConfigDef); }
private String getPackagePath() { @@ -176,33 +206,13 @@ public class ConfigurationMetadataManagerBeanTest extends AbstractEJB3Test { return null; }
- void assertPropertyDefinitionMatches(String msg, PropertyDefinitionSimple expected, - PropertyDefinitionSimple actual) { + void assertPropertyDefinitionMatches(String msg, PropertyDefinition expected, PropertyDefinition actual) { AssertUtils.assertPropertiesMatch(msg, expected, actual, "id", "configurationDefinition"); }
- @Test(enabled = false) - public void existingUngroupedPropertyDefShouldBeUpdated() throws Exception { - PropertyDefinitionSimple expected = updatedConfigDef.getPropertyDefinitionSimple("foo"); - PropertyDefinitionSimple actual = originalConfigDef.getPropertyDefinitionSimple("foo"); - - assertPropertyDefinitionMatches("Existing ungrouped property defs should be updated", expected, actual); - } - - @Test(enabled = false) - public void propertyDefNotInNewConfigurationDefShouldBeRemoved() throws Exception { - assertNull( - "A property def in the original configuration def that is removed in the new configuration def should be deleted", - originalConfigDef.getPropertyDefinitionSimple("propertyToBeRemoved") - ); + void assertPropertyDefinitionMatches(String msg, PropertyDefinition expected, PropertyDefinition actual, + List<String> ignoredProperties) { + AssertUtils.assertPropertiesMatch(msg, expected, actual, ignoredProperties); }
- @Test(enabled = false) - public void propertyGroupDefNotInNewConfigurationDefShouldBeRemoved() throws Exception { - for (PropertyGroupDefinition def : originalConfigDef.getGroupDefinitions()) { - if (def.getName().equals("groupToBeRemoved")) { - fail("Expected property group 'groupToBeRemoved' to be deleted since it is not in the new configuration def."); - } - } - } } diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml index dd8fcfa..23f3a1b 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v1.xml @@ -26,4 +26,39 @@ </c:group> </plugin-configuration> </server> + + <server name="UpdatedPropertyList"> + <plugin-configuration> + <c:list-property name="myList" + displayName="My Test List" + readOnly="false" + description="Update Property List Test" + required="true" + min="1" + max="5"> + <c:simple-property name="myListMember" + type="double" + default="3.14" + description="PI"/> + </c:list-property> + </plugin-configuration> + </server> + + <server name="UpdatedMapWithRemovedProperty"> + <plugin-configuration> + <c:map-property name="myMap"> + <c:simple-property name="propertyToRemove"/> + </c:map-property> + </plugin-configuration> + </server> + + <server name="UpdatedMapWithUpdatedProperty"> + <plugin-configuration> + <c:map-property name="myMap"> + <c:simple-property name="propertyToUpdate" + default="ten" + required="false"/> + </c:map-property> + </plugin-configuration> + </server> </plugin> diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml index d090e76..4c61512 100644 --- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml +++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/configuration/metadata/configuration_metadata_manager_bean_test_v2.xml @@ -42,4 +42,40 @@ </c:group> </plugin-configuration> </server> + + <server name="UpdatedPropertyList"> + <plugin-configuration> + <c:list-property name="myList" + displayName="My Test List" + readOnly="false" + description="Update Property List Test" + required="true" + min="1" + max="5"> + <c:map-property name="myMap"> + <c:simple-property name="myListMember" + type="double" + default="3.14" + description="PI"/> + </c:map-property> + </c:list-property> + </plugin-configuration> + </server> + + <server name="UpdatedMapWithRemovedProperty"> + <plugin-configuration> + <c:map-property name="myMap"/> + </plugin-configuration> + </server> + + <server name="UpdatedMapWithUpdatedProperty"> + <plugin-configuration> + <c:map-property name="myMap"> + <c:simple-property name="propertyToUpdate" + type="integer" + default="10" + required="true"/> + </c:map-property> + </plugin-configuration> + </server> </plugin>
commit 51ddbfc1c712a4e7cad1812007e77ef17de3e3ba Author: John Mazzitelli mazz@redhat.com Date: Mon Oct 4 15:25:22 2010 -0400
implement the new alert-subject server plugin notification editor. this needs to be tested to make sure the sender still works. but the notification configuration is consistent with how it was before so it should work
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java index 4e9418c..af0882f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/SubjectCriteria.java @@ -22,10 +22,13 @@ */ package org.rhq.core.domain.criteria;
+import java.util.List; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType;
import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.util.CriteriaUtils; import org.rhq.core.domain.util.PageOrdering;
/** @@ -45,7 +48,8 @@ public class SubjectCriteria extends Criteria { private String filterPhoneNumber; private String filterDepartment; private Boolean filterFactive; - private Integer filterRoleId; + private Integer filterRoleId; // needs overrides + private List<Integer> filterIds; // needs overrides
private boolean fetchConfiguration; private boolean fetchRoles; @@ -64,6 +68,8 @@ public class SubjectCriteria extends Criteria { + " FROM Subject innerSubject " // + " JOIN innerSubject.roles innerRole " // + " WHERE innerRole.id = ? )"); + + filterOverrides.put("ids", "id IN ( ? )"); }
@Override @@ -111,6 +117,10 @@ public class SubjectCriteria extends Criteria { this.filterRoleId = filterRoleId; }
+ public void addFilterIds(Integer... filterIds) { + this.filterIds = CriteriaUtils.getListIgnoringNulls(filterIds); + } + public void fetchConfiguration(boolean fetchConfiguration) { this.fetchConfiguration = fetchConfiguration; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java index 5b8b0b4..0dabe26 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/AbstractNotificationSenderForm.java @@ -99,4 +99,6 @@ public abstract class AbstractNotificationSenderForm extends LocatableVLayout { public void setExtraConfiguration(Configuration extraConfiguration) { this.extraConfiguration = extraConfiguration; } + + public abstract boolean validate(); } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java index 390357c..7d8745d 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/NewNotificationEditor.java @@ -147,8 +147,12 @@ public class NewNotificationEditor extends LocatableDynamicForm { @Override public void onClick(ClickEvent event) { if (validate(false)) { - saveNewNotification(); - closeFunction.run(); + AbstractNotificationSenderForm senderForm = (AbstractNotificationSenderForm) senderCanvasItem + .getCanvas(); + if (senderForm.validate()) { + saveNewNotification(); + closeFunction.run(); + } } } }); @@ -214,7 +218,7 @@ public class NewNotificationEditor extends LocatableDynamicForm { // For those that want to write their own custom alert plugins, you are restricted to // using configuration definitions as the only way to configure the sender. if ("System Users".equals(sender)) { - newCanvas = null; // TODO + newCanvas = new SystemUsersNotificationSenderForm(newLocatorId, notificationToEdit, sender); } else if ("System Roles".equals(sender)) { newCanvas = null; // TODO } else if ("Resource Operations".equals(sender)) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java index 4a16380..65ddcd9 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SimpleNotificationSenderForm.java @@ -41,6 +41,8 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; */ public class SimpleNotificationSenderForm extends AbstractNotificationSenderForm {
+ private ConfigurationEditor configEditor; + public SimpleNotificationSenderForm(String locatorId, AlertNotification notif, String sender) { super(locatorId, notif, sender); } @@ -53,10 +55,10 @@ public class SimpleNotificationSenderForm extends AbstractNotificationSenderForm new AsyncCallback<ConfigurationDefinition>() { @Override public void onSuccess(ConfigurationDefinition configDef) { - ConfigurationEditor configEditor = new ConfigurationEditor(extendLocatorId("configEditor"), - configDef, getConfiguration()); - configEditor.setHeight(500); - configEditor.setWidth(500); + configEditor = new ConfigurationEditor(extendLocatorId("configEditor"), configDef, + getConfiguration()); + configEditor.setHeight(400); + configEditor.setWidth(600); addMember(configEditor); markForRedraw(); } @@ -72,4 +74,13 @@ public class SimpleNotificationSenderForm extends AbstractNotificationSenderForm } }); } + + @Override + public boolean validate() { + if (configEditor != null) { + return configEditor.validate(); + } + return true; + } + } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemUsersNotificationSenderForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemUsersNotificationSenderForm.java new file mode 100644 index 0000000..cdbaedf --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/alert/definitions/SystemUsersNotificationSenderForm.java @@ -0,0 +1,203 @@ +/* + * 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, version 2, as + * published by the Free Software Foundation, and/or the GNU Lesser + * General Public License, version 2.1, also as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.rhq.enterprise.gui.coregui.client.alert.definitions; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.Criteria; +import com.smartgwt.client.widgets.form.DynamicForm; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +import org.rhq.core.domain.alert.notification.AlertNotification; +import org.rhq.core.domain.auth.Subject; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.criteria.SubjectCriteria; +import org.rhq.core.domain.util.PageList; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.admin.users.UsersDataSource; +import org.rhq.enterprise.gui.coregui.client.components.selector.AbstractSelector; +import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +/** + * This notification form will be used for the System Users sender. This form lets + * you pick users that the sender will send notifications to. + * + * @author John Mazzitelli + */ +public class SystemUsersNotificationSenderForm extends AbstractNotificationSenderForm { + + // the alert configuration property name where the IDs are stored in |-separated form + private static final String PROPNAME = "subjectId"; + + private SubjectSelector selector; + + public SystemUsersNotificationSenderForm(String locatorId, AlertNotification notif, String sender) { + super(locatorId, notif, sender); + } + + @Override + protected void onInit() { + super.onInit(); + + String subjectIds = getConfiguration().getSimpleValue(PROPNAME, ""); // we know the subject plugin defines this + if (subjectIds != null && subjectIds.length() > 0) { + try { + List<Integer> ids = unfence(subjectIds, Integer.class); + SubjectCriteria criteria = new SubjectCriteria(); + criteria.addFilterIds(ids.toArray(new Integer[ids.size()])); + GWTServiceLookup.getSubjectService().findSubjectsByCriteria(criteria, + new AsyncCallback<PageList<Subject>>() { + @Override + public void onSuccess(PageList<Subject> result) { + createNewSelector(result); + } + + @Override + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Cannot determine current users - starting empty", + caught); + createNewSelector(null); + } + }); + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Cannot use current users - starting empty", e); + createNewSelector(null); + } + } else { + createNewSelector(null); + } + } + + private void createNewSelector(Collection<Subject> preselectedSubjects) { + String selectorLocatorId = extendLocatorId("userSelector"); + selector = new SubjectSelector(selectorLocatorId, preselectedSubjects); + selector.setWidth(400); + selector.setHeight(300); + addMember(selector); + markForRedraw(); + } + + @Override + public boolean validate() { + if (selector != null) { + try { + HashSet<Integer> selectedIds = selector.getSelection(); + String newPropValue = fence(selectedIds); + getConfiguration().put(new PropertySimple(PROPNAME, newPropValue)); + return true; + } catch (Exception e) { + CoreGUI.getErrorHandler().handleError("Cannot save the selected users", e); + return false; + } + } + return true; + } + + @SuppressWarnings("unchecked") + private <T> List<T> unfence(String fencedData, Class<T> type) { + String delimiter = "\|"; + String[] elements = fencedData.split(delimiter); + List<T> results = new ArrayList<T>(elements.length); + + if (Integer.class.equals(type)) { + for (String next : elements) { + if (next.length() != 0) { + results.add((T) Integer.valueOf(next)); + } + } + } else if (String.class.equals(type)) { + for (String next : elements) { + if (next.length() != 0) { + results.add((T) next); + } + } + } else { + throw new IllegalArgumentException("No support for unfencing data of type " + type); + } + return results; + } + + /** + * Takes the list of elements e1, e2, e3 and fences + * them with '|' delimiters such that the result looks + * like "|e1|e2|e3|" + */ + private String fence(Collection<?> elements) { + if (elements.size() == 0) { + return ""; + } + StringBuilder builder = new StringBuilder(); + builder.append('|'); + for (Object next : elements) { + builder.append(String.valueOf(next)).append('|'); + } + return builder.toString(); + } + + private class SubjectSelector extends AbstractSelector<Subject> { + + public SubjectSelector(String id, Collection<Subject> subjects) { + super(id); + if (subjects != null) { + ListGridRecord[] data = (new UsersDataSource()).buildRecords(subjects); + setAssigned(data); + } + } + + @Override + protected RPCDataSource<Subject> getDataSource() { + return new SelectedSubjectsDataSource(); + } + + @Override + protected DynamicForm getAvailableFilterForm() { + return null; // No Filters Currently + } + + @Override + protected Criteria getLatestCriteria(DynamicForm availableFilterForm) { + return null; // No Filters Currently + } + + public class SelectedSubjectsDataSource extends UsersDataSource { + + @Override + public ListGridRecord[] buildRecords(Collection<Subject> subjects) { + ListGridRecord[] records = super.buildRecords(subjects); + for (ListGridRecord record : records) { + if (selection.contains(record.getAttributeAsInt("id"))) { + record.setEnabled(false); + } + } + return records; + } + } + + } +} diff --git a/modules/enterprise/server/plugins/alert-subject/pom.xml b/modules/enterprise/server/plugins/alert-subject/pom.xml index 09f2ddc..03e4631 100644 --- a/modules/enterprise/server/plugins/alert-subject/pom.xml +++ b/modules/enterprise/server/plugins/alert-subject/pom.xml @@ -23,31 +23,10 @@
<properties> <scm.module.path>modules/enterprise/server/plugins/alert-subject/</scm.module.path> - <seam.version>2.1.0.SP1</seam.version> </properties>
<dependencies>
- <dependency> - <groupId>org.jboss.seam</groupId> - <artifactId>jboss-seam</artifactId> - <version>${seam.version}</version> - <exclusions> - <exclusion> - <groupId>xml-apis</groupId> - <artifactId>xml-apis</artifactId> - </exclusion> - </exclusions> - </dependency> - - - <dependency> - <groupId>jboss.jboss-embeddable-ejb3</groupId> - <artifactId>jboss-ejb3-all</artifactId> - <version>1.0.0.Alpha9</version> - <scope>compile</scope> - </dependency> - </dependencies>
<build> diff --git a/modules/enterprise/server/plugins/alert-subject/src/main/java/org/rhq/enterprise/server/plugins/alertSubject/SubjectsBackingBean.java b/modules/enterprise/server/plugins/alert-subject/src/main/java/org/rhq/enterprise/server/plugins/alertSubject/SubjectsBackingBean.java deleted file mode 100644 index b98bb1b..0000000 --- a/modules/enterprise/server/plugins/alert-subject/src/main/java/org/rhq/enterprise/server/plugins/alertSubject/SubjectsBackingBean.java +++ /dev/null @@ -1,84 +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.enterprise.server.plugins.alertSubject; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.rhq.core.domain.auth.Subject; -import org.rhq.core.domain.configuration.PropertySimple; -import org.rhq.core.domain.util.PageControl; -import org.rhq.enterprise.server.plugin.pc.alert.AlertSender; -import org.rhq.enterprise.server.plugin.pc.alert.CustomAlertSenderBackingBean; -import org.rhq.enterprise.server.util.LookupUtil; - -/** - * Backing Bean for the subjects sender alert sender plugin custom UI - * @author Joseph Marques - */ -public class SubjectsBackingBean extends CustomAlertSenderBackingBean { - - private Map<String, String> available; - private List<String> currentSubjects; - private static final String SUBJECT_ID = "subjectId"; - - @Override - public void loadView() { - // get available/all subjects - List<Subject> allSubjects = LookupUtil.getSubjectManager().findAllSubjects(new PageControl()); - available = new HashMap<String, String>(); - for (Subject subject : allSubjects) { - String subjectId = String.valueOf(subject.getId()); - available.put(subject.getName(), subjectId); - } - - // get current subjects - String subjectString = alertParameters.getSimpleValue(SUBJECT_ID, ""); - currentSubjects = AlertSender.unfence(subjectString, String.class); - } - - @Override - public void saveView() { - String subjectIds = AlertSender.fence(currentSubjects); - - PropertySimple p = alertParameters.getSimple(SUBJECT_ID); - if (p == null) { - p = new PropertySimple(SUBJECT_ID, subjectIds); - alertParameters.put(p); - } else { - p.setStringValue(subjectIds); - } - - alertParameters = persistConfiguration(alertParameters); - } - - public List<String> getCurrentSubjects() { - return currentSubjects; - } - - public void setCurrentSubjects(List<String> currentSubjects) { - this.currentSubjects = currentSubjects; - } - - public Map<String, String> getAvailableSubjectsMap() { - return available; - } - -} diff --git a/modules/enterprise/server/plugins/alert-subject/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/alert-subject/src/main/resources/META-INF/rhq-serverplugin.xml index 6260aa4..277df97 100644 --- a/modules/enterprise/server/plugins/alert-subject/src/main/resources/META-INF/rhq-serverplugin.xml +++ b/modules/enterprise/server/plugins/alert-subject/src/main/resources/META-INF/rhq-serverplugin.xml @@ -15,21 +15,13 @@ Used to send notifications to registered users in the system. </serverplugin:help>
- <!-- startup & tear down listener, + scheduled jobs - <serverplugin:plugin-component class="Foo" /> - --> - - - <!-- How does this sender show up in drop downs etc --> <short-name>System Users</short-name>
<!-- Class that does the actual sending --> <plugin-class>SubjectsSender</plugin-class>
- <custom-ui> - <ui-snippet-name>subjects.xhtml</ui-snippet-name> - <backing-bean-class>SubjectsBackingBean</backing-bean-class> - <backing-bean-name>subjectsBean</backing-bean-name> - </custom-ui> + <alert-configuration> + <c:simple-property name="subjectId" type="string" required="true" description="The subjects (ids are |-separated) to be notified"/> + </alert-configuration> </alert-plugin> \ No newline at end of file diff --git a/modules/enterprise/server/plugins/alert-subject/src/main/resources/subjects.xhtml b/modules/enterprise/server/plugins/alert-subject/src/main/resources/subjects.xhtml deleted file mode 100644 index 39d86e8..0000000 --- a/modules/enterprise/server/plugins/alert-subject/src/main/resources/subjects.xhtml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:c="http://java.sun.com/jstl/core" - xmlns:a4j="https://richfaces.org/a4j" - xmlns:rich="http://richfaces.ajax4jsf.org/rich%22%3E - -<body> - <rich:pickList fastMoveControlsVisible="false" - sourceListWidth="200px" - targetListWidth="200px" - copyControlLabel="Add Subjects" - removeControlLabel="Remove Subjects" - value="#{subjectsBean.currentSubjects}"> - <f:selectItems value="#{subjectsBean.availableSubjectsMap}" /> - </rich:pickList> -</body> - -</html> \ No newline at end of file
commit f4c316bed1ed30f33cc6365421f051b945710870 Author: Jay Shaughnessy jshaughn@redhat.com Date: Mon Oct 4 15:06:46 2010 -0400
Disable the experimental browser window logging out of the box
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml index ed2ce42..93d7ecb 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/CoreGUI.gwt.xml @@ -38,7 +38,7 @@ 2. In hosted mode, the windows are not automatically closed, although you can easily close them manually in the usual way --> - <set-property name="log_WindowLogger" value="ENABLED" /> + <set-property name="log_WindowLogger" value="DISABLED" />
<!-- You probably will want to disable the default `DivLogger` as well:
commit 98ab21b9a9348520b30fae149d67d39af7553373 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 18:58:14 2010 +0200
Getting the InventoryManager.handleReport(InventoryReport) inline with the version in master, updating the upgrade tests to accommodate for the changed behavior.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index ec40b0c..c5004dd 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -932,30 +932,16 @@ public class InventoryManager extends AgentService implements ContainerService, }
/** - * @see #handleReport(InventoryReport, boolean) - * @param report - * @return - */ - public boolean handleReport(InventoryReport report) { - return handleReport(report, false); - } - - /** * Send an inventory report to the Server. * * @param report the inventory report to be sent - * @param forceServerRoundtrip whether to report to the server even if there are no resources to report. * @return true if sending the report to the Server succeeded, or false otherwise */ - public boolean handleReport(InventoryReport report, boolean forceServerRoundtrip) { + public boolean handleReport(InventoryReport report) { if (!configuration.isInsideAgent()) { return true; }
- if (report.getAddedRoots().isEmpty() && !forceServerRoundtrip) { - return true; // nothing to do - } - ResourceSyncInfo syncInfo; try { String reportType = (report.isRuntimeReport()) ? "runtime" : "server"; @@ -2659,7 +2645,7 @@ public class InventoryManager extends AgentService implements ContainerService,
log.debug("Executing resource upgrade.");
- boolean syncResult = handleReport(new InventoryReport(getAgent()), true); + boolean syncResult = handleReport(new InventoryReport(getAgent())); if (!syncResult) { log.warn("Resource upgrade failed to sync up the inventory with the server."); return; diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java index ebb73be..ab1cd2b 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java @@ -342,10 +342,6 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources( expectations.with(Expectations.any(Set.class))); expectations.will(getCurrentServerSideInventory().upgradeResources()); - - expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources( - expectations.with(Expectations.any(Set.class))); - } catch (InvalidInventoryReportException e) { //this is not going to happen because we're mocking the invocation } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 8b966c3..e2a8a84 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -93,7 +93,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { { defineDefaultExpectations(this);
- between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
@@ -144,7 +144,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { { defineDefaultExpectations(this);
- between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
@@ -197,7 +197,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
//the rest of the inventory merges are executed by discoveries, so let's import the //discovered stuff into the server-side inventory. - between(1, 3).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
@@ -242,7 +242,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { { defineDefaultExpectations(this);
- between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
@@ -276,7 +276,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { { defineDefaultExpectations(this);
- between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(requiredInventoryStatus)); } @@ -317,7 +317,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { { defineDefaultExpectations(this);
- between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java index 0aefafd..c299cce 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java @@ -402,6 +402,9 @@ public abstract class ResourceUpgradeTestBase { expectations.allowing(getCurrentDiscoveryServerService()).getResources( expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); expectations.will(getCurrentServerSideInventory().getResources()); + + expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources( + expectations.with(Expectations.any(Set.class))); }
protected void cleanDataDir() throws IOException {
commit 65c3b23735a092f9675cb2e878b79039b5ab9c93 Merge: e7fb6ed... ebd4ec6... Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 18:37:55 2010 +0200
Merge branch 'master' into resource-upgrade
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 150a692,4e14b75..a004680 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@@ -238,11 -274,11 +275,15 @@@ public class ResourceGWTServiceImpl ext }
public void unignoreResources(Integer[] resourceIds) { - discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); + try { + discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); + } catch (Exception e) { + throw new RuntimeException(ThrowableUtil.getAllMessages(e)); + } } - -} + + public List<ResourceError> findResourceErrors(int resourceId) { + return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), + "ResourceService.getResourceErrors"); + } +}
commit e7fb6edacd4c172a236cfc39b19096f03cef85ee Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 18:34:25 2010 +0200
Discovery now recurses to child resource types of the existing resources even if the discovery of the existing resources' type is disallowed due to upgrade failure. This means that no new siblings will be discovered but the existing resources "contents" will be up-to-date with the plugin version.
Added tests for this behaviour and updated the existing to reflect the changes.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 99a0513..ec40b0c 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -91,6 +91,7 @@ import org.rhq.core.pc.plugin.BlacklistedException; import org.rhq.core.pc.plugin.CanonicalResourceKey; import org.rhq.core.pc.plugin.PluginComponentFactory; import org.rhq.core.pc.plugin.PluginManager; +import org.rhq.core.pc.upgrade.DiscoverySuspendedException; import org.rhq.core.pc.upgrade.ResourceUpgradeDelegate; import org.rhq.core.pc.util.DiscoveryComponentProxyFactory; import org.rhq.core.pc.util.FacetLockType; @@ -289,18 +290,22 @@ public class InventoryManager extends AgentService implements ContainerService, * @param context the context for use by the discovery component * @return the details of all discovered resources, may be empty or <code>null</code> * + * @throws DiscoverySuspendedException if the discovery is suspended due to a resource upgrade failure * @throws Exception if the discovery component threw an exception */ public Set<DiscoveredResourceDetails> invokeDiscoveryComponent(ResourceContainer parentResourceContainer, - ResourceDiscoveryComponent component, ResourceDiscoveryContext context) throws Exception { + ResourceDiscoveryComponent component, ResourceDiscoveryContext context) throws DiscoverySuspendedException, Exception {
Resource parentResource = parentResourceContainer == null ? null : parentResourceContainer.getResource();
if (resourceUpgradeDelegate.hasUpgradeFailedInChildren(parentResource, context.getResourceType())) { - log.debug("Discovery of [" + context.getResourceType() + "] has been disallowed under " - + (parentResource == null ? " the platform " : parentResource) - + " because some of its siblings failed to upgrade."); - return null; + String message = "Discovery of [" + context.getResourceType() + "] has been suspended under " + + (parentResource == null ? " the platform " : parentResource) + + " because some of its siblings failed to upgrade."; + + log.debug(message); + + throw new DiscoverySuspendedException(message); }
long timeout = getDiscoveryComponentTimeout(context.getResourceType()); @@ -699,19 +704,29 @@ public class InventoryManager extends AgentService implements ContainerService,
// Ask the plugin's discovery component to find the new resource, throwing exceptions if it cannot be // found at all. - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentResourceContainer, - discoveryComponent, discoveryContext); - if ((discoveredResources == null) || discoveredResources.isEmpty()) { - log.info("Plugin Error: During manual add, discovery component method [" - + discoveryComponent.getClass().getName() + ".discoverResources()] returned " - + discoveredResources + " when passed a single plugin configuration " - + "(either the resource type was blacklisted or the plugin developer " - + "did not implement support for manually discovered resources correctly)."); - throw new PluginContainerException("The [" + resourceType.getPlugin() - + "] plugin does not properly support manual addition of [" + resourceType.getName() - + "] resources."); + try { + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentResourceContainer, + discoveryComponent, discoveryContext); + if ((discoveredResources == null) || discoveredResources.isEmpty()) { + log.info("Plugin Error: During manual add, discovery component method [" + + discoveryComponent.getClass().getName() + ".discoverResources()] returned " + + discoveredResources + " when passed a single plugin configuration " + + "(either the resource type was blacklisted or the plugin developer " + + "did not implement support for manually discovered resources correctly)."); + throw new PluginContainerException("The [" + resourceType.getPlugin() + + "] plugin does not properly support manual addition of [" + resourceType.getName() + + "] resources."); + } + discoveredResourceDetails = discoveredResources.iterator().next(); + } catch (DiscoverySuspendedException e) { + String message = "The discovery class [" + discoveryComponent.getClass().getName() + "]" + + " uses a legacy implementation of "manual add" functionality. Some of the child resources" + + " with the resource type [" + resourceType + "] under the parent resource [" + parentResourceContainer.getResource() + "]" + + " failed to upgrade, which makes it impossible to support the legacy manual-add implementation. Either upgrade the plugin [" + + resourceType.getPlugin() + "] to successfully upgrade all resources or consider implementing the ManuallAdd facet."; + log.info(message); + throw new PluginContainerException(message, e); } - discoveredResourceDetails = discoveredResources.iterator().next(); }
// Create the new Resource and add it to inventory if it isn't already there. @@ -1844,6 +1859,8 @@ public class InventoryManager extends AgentService implements ContainerService,
try { discoveredResources = invokeDiscoveryComponent(null, component, context); + } catch (DiscoverySuspendedException e) { + log.error("Discovery seems to be suspended for platforms due to upgrade error.", e); } catch (Throwable e) { log.warn("Platform plugin discovery failed - skipping", e); } @@ -2179,35 +2196,47 @@ public class InventoryManager extends AgentService implements ContainerService, parentResourceContext, SystemInfoFactory.createSystemInfo(), processScanResults, Collections.EMPTY_LIST, this.configuration.getContainerName(), this.configuration.getPluginContainerDeployment()); - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer, - discoveryComponent, context); newResources = new HashSet<Resource>(); - if ((discoveredResources != null) && (!discoveredResources.isEmpty())) { - IdentityHashMap<Configuration, DiscoveredResourceDetails> pluginConfigObjects = new IdentityHashMap<Configuration, DiscoveredResourceDetails>(); - for (DiscoveredResourceDetails discoveredResource : discoveredResources) { - if (discoveredResource == null) { - throw new IllegalStateException("Plugin error: Discovery class " - + discoveryComponent.getClass().getName() - + " returned a Set containing one or more null items."); - } - if (!discoveredResource.getResourceType().equals(resourceType)) { - throw new IllegalStateException("Plugin error: Discovery class " - + discoveryComponent.getClass().getName() - + " returned a DiscoveredResourceDetails with an incorrect ResourceType (was " - + discoveredResource.getResourceType().getName() + " but should have been " - + resourceType.getName()); + try { + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer, + discoveryComponent, context); + if ((discoveredResources != null) && (!discoveredResources.isEmpty())) { + IdentityHashMap<Configuration, DiscoveredResourceDetails> pluginConfigObjects = new IdentityHashMap<Configuration, DiscoveredResourceDetails>(); + for (DiscoveredResourceDetails discoveredResource : discoveredResources) { + if (discoveredResource == null) { + throw new IllegalStateException("Plugin error: Discovery class " + + discoveryComponent.getClass().getName() + + " returned a Set containing one or more null items."); + } + if (!discoveredResource.getResourceType().equals(resourceType)) { + throw new IllegalStateException("Plugin error: Discovery class " + + discoveryComponent.getClass().getName() + + " returned a DiscoveredResourceDetails with an incorrect ResourceType (was " + + discoveredResource.getResourceType().getName() + " but should have been " + + resourceType.getName()); + } + if (null != pluginConfigObjects + .put(discoveredResource.getPluginConfiguration(), discoveredResource)) { + throw new IllegalStateException("The plugin component " + + discoveryComponent.getClass().getName() + + " returned multiple resources that point to the same plugin configuration object on the " + + "resource type [" + resourceType + "]. This is not allowed, please use " + + "ResoureDiscoveryContext.getDefaultPluginConfiguration() " + + "for each discovered resource."); + } + Resource newResource = InventoryManager.createNewResource(discoveredResource); + newResources.add(newResource); } - if (null != pluginConfigObjects - .put(discoveredResource.getPluginConfiguration(), discoveredResource)) { - throw new IllegalStateException("The plugin component " - + discoveryComponent.getClass().getName() - + " returned multiple resources that point to the same plugin configuration object on the " - + "resource type [" + resourceType + "]. This is not allowed, please use " - + "ResoureDiscoveryContext.getDefaultPluginConfiguration() " - + "for each discovered resource."); + } + } catch (DiscoverySuspendedException e) { + //ok, the discovery is suspended for this resource type under this parent. + //but we can continue the discovery in the child resource types of the existing resources. + //we can therefore pretend that the discovery returned the existing resources so that + //we can recurse into their children up in the call-chain. + for(Resource existingResource : parentResource.getChildResources()) { + if (resourceType.equals(existingResource.getResourceType())) { + newResources.add(existingResource); } - Resource newResource = InventoryManager.createNewResource(discoveredResource); - newResources.add(newResource); } } } catch (Throwable e) { @@ -2654,14 +2683,14 @@ public class InventoryManager extends AgentService implements ContainerService, if (container != null) { if (container.getResourceComponentState() == ResourceComponentState.STARTED) { try { - resourceUpgradeDelegate.processAndQueue(container); + if (resourceUpgradeDelegate.processAndQueue(container)) { + for (Resource child : resource.getChildResources()) { + upgradeResource(child); + } + } } catch (PluginContainerException e) { log.error("Exception thrown while upgrading [" + resource + "].", e); } - - for (Resource child : resource.getChildResources()) { - upgradeResource(child); - } } else { String message = "The resource container for resource [" + resource + "] wasn't started while upgrading."; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/DiscoverySuspendedException.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/DiscoverySuspendedException.java new file mode 100644 index 0000000..5cb695d --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/DiscoverySuspendedException.java @@ -0,0 +1,50 @@ +/* + * 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.core.pc.upgrade; + +import org.rhq.core.pc.inventory.InventoryManager; + +/** + * This exception is thrown from the {@link InventoryManager#invokeDiscoveryComponent(org.rhq.core.pc.inventory.ResourceContainer, org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent, org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext)} if the + * discovery is suspended for given resource type due to a resource upgrade failure. + * + * @author Lukas Krejci + */ +public class DiscoverySuspendedException extends Exception { + + private static final long serialVersionUID = 1L; + + public DiscoverySuspendedException() { + super(); + } + + public DiscoverySuspendedException(String message, Throwable cause) { + super(message, cause); + } + + public DiscoverySuspendedException(String message) { + super(message); + } + + public DiscoverySuspendedException(Throwable cause) { + super(cause); + } + +} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java index 98a897e..06d2cd0 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java @@ -26,6 +26,7 @@ import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; import org.rhq.core.domain.resource.Resource; @@ -61,7 +62,7 @@ public class ResourceUpgradeDelegate { private Set<Resource> failedResources = new HashSet<Resource>(); private Map<Resource, Set<ResourceType>> failedResourceTypesPerParent = new HashMap<Resource, Set<ResourceType>>(); private boolean mergeFailed; - + public ResourceUpgradeDelegate(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; } @@ -84,13 +85,17 @@ public class ResourceUpgradeDelegate { /** * Asks the resource's discovery component to upgrade the resource. * @param resourceContainer - * @return true if the resource was queued for upgrade, false otherwise + * @return true if the resource was queued for upgrade with no problems, + * false if there was some problem upgrading and the resource container was deactivated as + * a results of that. * @throws PluginContainerException on error */ - public void processAndQueue(ResourceContainer resourceContainer) throws PluginContainerException { + public boolean processAndQueue(ResourceContainer resourceContainer) throws PluginContainerException { if (enabled) { - executeResourceUpgradeFacetAndStoreRequest(resourceContainer); + return executeResourceUpgradeFacetAndStoreRequest(resourceContainer); } + + return true; }
/** @@ -99,7 +104,7 @@ public class ResourceUpgradeDelegate { public boolean hasUpgradeMergeFailed() { return mergeFailed; } - + /** * Tells whether given resource had a upgrade failure during the {@link #processAndQueue(ResourceContainer)} invocation. * @@ -109,7 +114,7 @@ public class ResourceUpgradeDelegate { public boolean hasUpgradeFailed(Resource resource) { return mergeFailed || failedResources.contains(resource); } - + /** * Tells whether at least one of the children with given resource type of the given parent resource * had an upgrade failure during {@link #processAndQueue(ResourceContainer)} invocation. @@ -120,35 +125,35 @@ public class ResourceUpgradeDelegate { if (mergeFailed) { return true; } - + Set<ResourceType> failedTypes = failedResourceTypesPerParent.get(parentResource); - + return failedTypes != null && failedTypes.contains(childrenResourceType); } - + public void sendRequests() throws Throwable { if (enabled && requests.size() > 0) { try { inventoryManager.mergeResourcesFromUpgrade(requests); } catch (Throwable t) { mergeFailed = true; - + //deactivate all the resources to be upgraded. We might have a problem //because they have not been upgraded because the merge failed. - for(ResourceUpgradeRequest request : requests) { + for (ResourceUpgradeRequest request : requests) { ResourceContainer container = inventoryManager.getResourceContainer(request.getResourceId()); if (container != null) { inventoryManager.deactivateResource(container.getResource()); } } - + throw t; } } }
@SuppressWarnings("unchecked") - private <T extends ResourceComponent> void executeResourceUpgradeFacetAndStoreRequest( + private <T extends ResourceComponent> boolean executeResourceUpgradeFacetAndStoreRequest( ResourceContainer resourceContainer) throws PluginContainerException {
ResourceComponent<T> parentResourceComponent = resourceContainer.getResourceContext() @@ -166,16 +171,16 @@ public class ResourceUpgradeDelegate {
if (!(discoveryComponent instanceof ResourceUpgradeFacet)) { //well, there's no point in continuing if the resource doesn't support the facet - return; + return true; }
ResourceUpgradeContext<ResourceComponent<T>> upgradeContext = inventoryManager.createResourceUpgradeContext( resource, parentResourceComponent, discoveryComponent);
ResourceUpgradeRequest request = new ResourceUpgradeRequest(resource.getId()); - + request.setTimestamp(System.currentTimeMillis()); - + ResourceUpgradeReport upgradeReport = null; try { upgradeReport = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resource.getResourceType(), @@ -189,13 +194,13 @@ public class ResourceUpgradeDelegate { String upgradeErrors = null; if ((upgradeErrors = checkUpgradeValid(resource, upgradeReport)) != null) { String errorString = "Upgrading the resource [" + resource + "] using these updates [" + upgradeReport - + "] would render the inventory invalid because of the following reasons: " + upgradeErrors; - + + "] would render the inventory invalid because of the following reasons: " + upgradeErrors; + log.error(errorString); - + IllegalStateException ex = new IllegalStateException(errorString); ex.fillInStackTrace(); - + request.setErrorProperties(ex); } else { request.fillInFromReport(upgradeReport); @@ -207,20 +212,24 @@ public class ResourceUpgradeDelegate { if (request.hasSomethingToUpgrade()) { requests.add(request); } - + if (request.getUpgradeErrorMessage() != null) { failedResources.add(resource); - + Set<ResourceType> failedResourceTypesInParent = failedResourceTypesPerParent.get(parentResource); if (failedResourceTypesInParent == null) { failedResourceTypesInParent = new HashSet<ResourceType>(); failedResourceTypesPerParent.put(parentResource, failedResourceTypesInParent); } - + failedResourceTypesInParent.add(resource.getResourceType()); - + inventoryManager.deactivateResource(resource); + + return false; } + + return true; }
private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java index 7eafafc..ebb73be 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java @@ -156,9 +156,9 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase
//check that the resources are upgraded checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1); - checkResourcesUpgraded(resources.get(PARENT_TYPE), 2); - checkResourcesUpgraded(resources.get(SIBLING_TYPE), 30); - checkResourcesUpgraded(resources.get(TEST_TYPE), 30); + checkResourcesUpgraded(resources.get(PARENT_TYPE), 3); + checkResourcesUpgraded(resources.get(SIBLING_TYPE), 45); + checkResourcesUpgraded(resources.get(TEST_TYPE), 45); }
public Expectations getExpectations(Mockery context) throws Exception { @@ -206,19 +206,24 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase
checkNumberOfResources(resources, ROOT_TYPE, 1); checkNumberOfResources(resources, PARENT_DEP_TYPE, 1); - checkNumberOfResources(resources, PARENT_TYPE, 2);
- checkResourcesUpgraded(resources.get(PARENT_TYPE), 2); + checkResourcesUpgraded(resources.get(PARENT_TYPE), 3); checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0); Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1); - - Set<Resource> siblingsUnderParent0 = filterResources(parent0.getChildResources(), SIBLING_TYPE); + Resource parent2 = findResourceWithOrdinal(PARENT_TYPE, 2); + Set<Resource> testsUnderParent0 = filterResources(parent0.getChildResources(), TEST_TYPE); - Set<Resource> siblingsUnderParent1 = filterResources(parent1.getChildResources(), SIBLING_TYPE); + Set<Resource> siblingsUnderParent0 = filterResources(parent0.getChildResources(), SIBLING_TYPE); Set<Resource> testsUnderParent1 = filterResources(parent1.getChildResources(), TEST_TYPE); - + Set<Resource> siblingsUnderParent1 = filterResources(parent1.getChildResources(), SIBLING_TYPE); + Set<Resource> testsUnderParent2 = filterResources(parent2.getChildResources(), TEST_TYPE); + Set<Resource> siblingsUnderParent2 = filterResources(parent2.getChildResources(), SIBLING_TYPE); + + //first check for the successful upgrades + checkResourcesUpgraded(testsUnderParent2, 15); + checkResourcesUpgraded(siblingsUnderParent2, 15); checkResourcesUpgraded(siblingsUnderParent0, 15); checkResourcesUpgraded(testsUnderParent1, 15);
@@ -257,10 +262,72 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase }
@Test - public void testFailureOnDependencies() { - //TODO implement - //check that stuff works if there is an upgrade failure on some of the resources - //in the plugin some "in the middle" of the plugin dep graph + public void testFailureOnDependencies() throws Exception { + setCurrentServerSideInventory(new FakeServerInventory()); + + executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME), + new AbstractTestPayload(true, Collections.<ResType> emptyList()) { + public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) { + //in here we set up the failures that are going to happen when + //the v2 plugins are run + + Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0); + assertNotNull(parent, "Failed to find the parent to setup the failures for."); + + addChildrenToFail(parent, PARENT_TYPE, 0); + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); + + executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME), + new AbstractTestPayload(false, ALL_TYPES) { + public void test(Map<ResType, Set<Resource>> resources) { + checkPresenceOfResourceTypes(resources, getExpectedResourceTypes()); + + checkNumberOfResources(resources, ROOT_TYPE, 1); + checkNumberOfResources(resources, PARENT_DEP_TYPE, 1); + checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1); + + //check that the failed resources have the error attached to them + //we find the resource instance from the map provided to this method + //because that map contains the resources as found on the server-side + //(i.e. they include error objects). + Resource parent0 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 0)); + Resource parent1 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 1)); + + //v2 plugin discovers 3 resources but because parent0 failed to upgrade, + //the discovery shouldn't have occurred leaving us with the 2 already existing resources. + checkNumberOfResources(resources, PARENT_TYPE, 2); + checkResourceFailedUpgrade(parent0); + checkOthersUpgraded(resources.get(PARENT_TYPE), parent0); + + //parent1 upgraded ok, so discovering its children should have executed. + //this is v2, so we should find 15 of each. + checkResourcesUpgraded(filterResources(parent1.getChildResources(), TEST_TYPE), 15); + checkResourcesUpgraded(filterResources(parent1.getChildResources(), SIBLING_TYPE), 15); + + //these shouldn't have been upgraded. in v1 we had 10 resources of TEST_TYPE + //and 10 resources of SIBLING_TYPE and that's what we should be seeing + //now. + checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), TEST_TYPE), 10); + checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), SIBLING_TYPE), 10); + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); }
@SuppressWarnings("unchecked") @@ -317,6 +384,22 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase } }
+ private static void checkResourcesNotUpgraded(Set<Resource> resources, int expectedSize) { + assertEquals(resources.size(), expectedSize, "The set of resources has unexpected size."); + for(Resource res : resources) { + assertFalse(res.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + res + + " seems to be upgraded even though it shouldn't."); + + ResourceContainer rc = PluginContainer.getInstance().getInventoryManager().getResourceContainer(res); + + assertEquals(rc.getResourceComponentState(), ResourceComponentState.STOPPED, + "A resource that has not been upgraded due to upgrade error in parent should be stopped."); + + //recurse, since the whole subtree under the failed resource should be not upgraded and stopped. + checkResourcesNotUpgraded(res.getChildResources(), res.getChildResources().size()); + } + } + private static void checkResourceFailedUpgrade(Resource resource) { assertFalse(resource.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + resource + " seems to be upgraded even though it shouldn't."); diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml index 3d709b0..0f6671b 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml @@ -21,7 +21,7 @@ </runs-inside>
<plugin-configuration> - <c:simple-property name="count" default="2" /> + <c:simple-property name="count" default="3" /> <c:simple-property name="key" default="UPGRADED-test-resource-parent-%n,parent-%p" /> </plugin-configuration>
commit 9533fc2898f18af7262f513049d7261516787f4f Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 14:50:49 2010 +0200
Upgrade even the non-commited resources to prevent duplication of resources in the auto-discovery queue
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index c6f1169..99a0513 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -2650,11 +2650,6 @@ public class InventoryManager extends AgentService implements ContainerService, }
private void upgradeResource(Resource resource) { - //only process committed resources - if (resource.getInventoryStatus() != InventoryStatus.COMMITTED) { - return; - } - ResourceContainer container = getResourceContainer(resource); if (container != null) { if (container.getResourceComponentState() == ResourceComponentState.STARTED) { @@ -2668,8 +2663,17 @@ public class InventoryManager extends AgentService implements ContainerService, upgradeResource(child); } } else { - log.error("The resource container for resource [" + resource - + "] wasn't started during upgrade. This should not happen."); + String message = "The resource container for resource [" + resource + + "] wasn't started while upgrading."; + + if (resource.getChildResources().isEmpty()) { + log.info(message + + " If this is the first time the plugin container starts up and has completely empty inventory, you can ignore this message."); + } else { + log.error(message + + " This can potentially cause the discovery to find resources logically equivalent to already " + + "existing resources if the corresponding plugins support upgrade for that particular resource type."); + } } } else { log.error("Resource container not initialized for resource [" + resource diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java index 39597ee..0dd3459 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -80,8 +80,6 @@ public class FakeServerInventory { this.failing = failing; }
- //need to synchronize, because resource upgrade is async and can overlap with - //resource discovery. public synchronized CustomAction mergeInventoryReport(final InventoryStatus requiredInventoryStatus) { return new CustomAction("updateServerSideInventory") { public Object invoke(Invocation invocation) throws Throwable { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 04858c6..8b966c3 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -71,7 +71,7 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { }
@Test - public void testIgnoreUncommittedResources() throws Exception { + public void testIncludeUncommittedResources() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.NEW);
@@ -82,11 +82,12 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); - assertEquals(discoveredResource.getName(), "resource-name-v1"); - assertEquals(discoveredResource.getDescription(), "resource-description-v1"); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); + assertEquals(discoveredResource.getName(), "resource-name-v2"); + assertEquals(discoveredResource.getDescription(), "resource-description-v2"); }
+ @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { @@ -95,6 +96,9 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); + + oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); + will(getCurrentServerSideInventory().upgradeResources()); } }; }
commit 8ecbe7dec08b0e2e1f86ad8e1e56efd9f651cc7e Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 14:32:55 2010 +0200
code formatting
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index de52cd8..c6f1169 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -242,16 +242,19 @@ public class InventoryManager extends AgentService implements ContainerService, // inside EmbJopr). if (configuration.isInsideAgent()) { // After an initial delay (5s by default), periodically run an availability check (every 1m by default). - availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor, configuration - .getAvailabilityScanInitialDelay(), configuration.getAvailabilityScanPeriod(), TimeUnit.SECONDS); + availabilityThreadPoolExecutor.scheduleWithFixedDelay(availabilityExecutor, + configuration.getAvailabilityScanInitialDelay(), configuration.getAvailabilityScanPeriod(), + TimeUnit.SECONDS);
// After an initial delay (10s by default), periodically run a server discovery scan (every 15m by default). - inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor, configuration - .getServerDiscoveryInitialDelay(), configuration.getServerDiscoveryPeriod(), TimeUnit.SECONDS); + inventoryThreadPoolExecutor.scheduleWithFixedDelay(serverScanExecutor, + configuration.getServerDiscoveryInitialDelay(), configuration.getServerDiscoveryPeriod(), + TimeUnit.SECONDS);
// After an initial delay (20s by default), periodically run a service discovery scan (every 1d by default). - inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor, configuration - .getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS); + inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor, + configuration.getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), + TimeUnit.SECONDS); } } finally { inventoryLock.writeLock().unlock(); @@ -288,22 +291,23 @@ public class InventoryManager extends AgentService implements ContainerService, * * @throws Exception if the discovery component threw an exception */ - public Set<DiscoveredResourceDetails> invokeDiscoveryComponent(ResourceContainer parentResourceContainer, ResourceDiscoveryComponent component, - ResourceDiscoveryContext context) throws Exception { + public Set<DiscoveredResourceDetails> invokeDiscoveryComponent(ResourceContainer parentResourceContainer, + ResourceDiscoveryComponent component, ResourceDiscoveryContext context) throws Exception {
Resource parentResource = parentResourceContainer == null ? null : parentResourceContainer.getResource(); - + if (resourceUpgradeDelegate.hasUpgradeFailedInChildren(parentResource, context.getResourceType())) { - log.debug("Discovery of [" + context.getResourceType() + "] has been disallowed under " + (parentResource == null ? " the platform " : parentResource) + - " because some of its siblings failed to upgrade."); + log.debug("Discovery of [" + context.getResourceType() + "] has been disallowed under " + + (parentResource == null ? " the platform " : parentResource) + + " because some of its siblings failed to upgrade."); return null; } - + long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try { - ResourceDiscoveryComponent proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context - .getResourceType(), component, timeout); + ResourceDiscoveryComponent proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy( + context.getResourceType(), component, timeout); Set<DiscoveredResourceDetails> results = proxy.discoverResources(context); return results; } catch (TimeoutException te) { @@ -335,8 +339,8 @@ public class InventoryManager extends AgentService implements ContainerService, long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try { - ManualAddFacet proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(context - .getResourceType(), component, timeout, ManualAddFacet.class); + ManualAddFacet proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy( + context.getResourceType(), component, timeout, ManualAddFacet.class); DiscoveredResourceDetails result = proxy.discoverResource(pluginConfig, context); return result; } catch (TimeoutException te) { @@ -375,8 +379,8 @@ public class InventoryManager extends AgentService implements ContainerService, component, timeout, ClassLoaderFacet.class);
ResourceDiscoveryContext discoveryContext = new ResourceDiscoveryContext(resourceType, parentComponent, - parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null, this.configuration - .getContainerName(), this.configuration.getPluginContainerDeployment()); + parentResourceContext, SystemInfoFactory.createSystemInfo(), null, null, + this.configuration.getContainerName(), this.configuration.getPluginContainerDeployment());
// Configurations are not immutable, so clone the plugin config, so the plugin will not be able to change the // actual PC-managed plugin config. @@ -384,8 +388,7 @@ public class InventoryManager extends AgentService implements ContainerService, // TODO (ips): Clone the ResourceType too for the same reason.
DiscoveredResourceDetails details = new DiscoveredResourceDetails(resourceType, resource.getResourceKey(), - resource.getName(), resource.getVersion(), resource.getDescription(), pluginConfigClone, - null); // TODO: I have a feeling we'll need process info, how to get it?? + resource.getName(), resource.getVersion(), resource.getDescription(), pluginConfigClone, null); // TODO: I have a feeling we'll need process info, how to get it??
List<URL> results = proxy.getAdditionalClasspathUrls(discoveryContext, details);
@@ -592,7 +595,8 @@ public class InventoryManager extends AgentService implements ContainerService,
@NotNull // TODO (ips): Perhaps refactor this so that it shares code with AvailablityExecutor.checkInventory(). - public Availability getCurrentAvailability(Resource resource) { + public + Availability getCurrentAvailability(Resource resource) { AvailabilityType availType = null; // i.e. UNKNOWN; ResourceContainer resourceContainer = getResourceContainer(resource); if (resourceContainer != null) { @@ -665,8 +669,8 @@ public class InventoryManager extends AgentService implements ContainerService, ResourceDiscoveryContext<ResourceComponent> discoveryContext = new ResourceDiscoveryContext<ResourceComponent>( resourceType, parentResourceComponent, parentResourceContainer.getResourceContext(), SystemInfoFactory.createSystemInfo(), new ArrayList<ProcessScanResult>(0), - new ArrayList<Configuration>(0), this.configuration.getContainerName(), this.configuration - .getPluginContainerDeployment()); + new ArrayList<Configuration>(0), this.configuration.getContainerName(), + this.configuration.getPluginContainerDeployment());
// Ask the plugin's discovery component to find the new resource, throwing exceptions if it cannot be // found at all. @@ -695,8 +699,8 @@ public class InventoryManager extends AgentService implements ContainerService,
// Ask the plugin's discovery component to find the new resource, throwing exceptions if it cannot be // found at all. - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentResourceContainer, discoveryComponent, - discoveryContext); + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentResourceContainer, + discoveryComponent, discoveryContext); if ((discoveredResources == null) || discoveredResources.isEmpty()) { log.info("Plugin Error: During manual add, discovery component method [" + discoveryComponent.getClass().getName() + ".discoverResources()] returned " @@ -850,8 +854,7 @@ public class InventoryManager extends AgentService implements ContainerService, if ((this.platform != null) && (this.platform.getInventoryStatus() == InventoryStatus.NEW) && newPlatformWasDeletedRecently) { // let's make sure we are registered; its probable that our platform was deleted and we need to re-register - log - .info("No committed resources to send in our availability report - the platform/agent was deleted, let's re-register again"); + log.info("No committed resources to send in our availability report - the platform/agent was deleted, let's re-register again"); registerWithServer(); newPlatformWasDeletedRecently = false; // we've tried to recover from our platform being deleted, let's not do it again } @@ -891,8 +894,8 @@ public class InventoryManager extends AgentService implements ContainerService, log.debug("Availability report content: " + report.toString(log.isTraceEnabled())); }
- boolean ok = configuration.getServerServices().getDiscoveryServerService().mergeAvailabilityReport( - report); + boolean ok = configuration.getServerServices().getDiscoveryServerService() + .mergeAvailabilityReport(report); if (!ok) { // I guess I could immediately call executeAvailabilityScanImmediately and pass its results to // mergeAvailabilityReport again right now, but what happens if we've queued up a bunch of @@ -955,8 +958,7 @@ public class InventoryManager extends AgentService implements ContainerService, if ((this.platform != null) && (this.platform.getInventoryStatus() == InventoryStatus.NEW) && newPlatformWasDeletedRecently) { // let's make sure we are registered; its probable that our platform was deleted and we need to re-register - log - .info("The inventory report was invalid probably because the platform/Agent was deleted; let's re-register..."); + log.info("The inventory report was invalid probably because the platform/Agent was deleted; let's re-register..."); registerWithServer(); newPlatformWasDeletedRecently = false; // we've tried to recover from our platform being deleted, let's not do it again } @@ -974,8 +976,8 @@ public class InventoryManager extends AgentService implements ContainerService, if (syncInfo != null) { synchInventory(syncInfo); } else { - purgeObsoleteResources(Collections.<String>emptySet()); - + purgeObsoleteResources(Collections.<String> emptySet()); + //can't live without a platform, but we just deleted it. Let's rediscover it. discoverPlatform(); } @@ -1113,7 +1115,7 @@ public class InventoryManager extends AgentService implements ContainerService, return; } boolean scan = removeResourceAndIndicateIfScanIsNeeded(resourceContainer.getResource()); - + //only actually schedule the scanning when we are finished with resource upgrade. The resource upgrade //happens before any scanning infrastructure is established. if (!resourceUpgradeDelegate.enabled() && scan) { @@ -1152,8 +1154,8 @@ public class InventoryManager extends AgentService implements ContainerService, parent.removeChildResource(resource); }
- PluginContainer.getInstance().getMeasurementManager().unscheduleCollection( - Collections.singleton(resource.getId())); + PluginContainer.getInstance().getMeasurementManager() + .unscheduleCollection(Collections.singleton(resource.getId()));
if (this.resourceContainers.remove(resource.getUuid()) == null) { if (log.isDebugEnabled()) { @@ -1258,8 +1260,8 @@ public class InventoryManager extends AgentService implements ContainerService, logMessage.append("description, "); }
- logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [").append( - existingResource.toString()).append("]"); + logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [") + .append(existingResource.toString()).append("]");
log.info(logMessage.toString()); } else { @@ -1429,7 +1431,7 @@ public class InventoryManager extends AgentService implements ContainerService, } return; } - + ResourceComponent component = container.getResourceComponent();
// if the component already exists and is started, and the resource's plugin config has not changed, there is @@ -1490,8 +1492,8 @@ public class InventoryManager extends AgentService implements ContainerService, log.warn("Cannot give activated resource its discovery component. Cause: " + e); }
- ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(), type - .getPluginConfigurationDefinition()); + ConfigurationUtility.normalizeConfiguration(resource.getPluginConfiguration(), + type.getPluginConfigurationDefinition());
ResourceComponent parentComponent = null; if (resource.getParentResource() != null) { @@ -1855,8 +1857,7 @@ public class InventoryManager extends AgentService implements ContainerService, } } else { // This is very strange - there are no platform types - we should never be missing the built-in platform plugin. - log - .error("Missing platform plugin(s) - falling back to dummy platform impl; this should only occur in tests!"); + log.error("Missing platform plugin(s) - falling back to dummy platform impl; this should only occur in tests!"); // TODO: Set sysprop (e.g. rhq.test.mode=true) in integration tests, // and throw a runtime exception here if that sysprop is not set. return getTestPlatform(); @@ -2049,7 +2050,7 @@ public class InventoryManager extends AgentService implements ContainerService, public boolean hasUpgradeMergeFailed() { return resourceUpgradeDelegate.hasUpgradeMergeFailed(); } - + /** * Always use this before accessing the event listeners because this ensures * thread safety. @@ -2176,9 +2177,10 @@ public class InventoryManager extends AgentService implements ContainerService, try { ResourceDiscoveryContext context = new ResourceDiscoveryContext(resourceType, parentComponent, parentResourceContext, SystemInfoFactory.createSystemInfo(), processScanResults, - Collections.EMPTY_LIST, this.configuration.getContainerName(), this.configuration - .getPluginContainerDeployment()); - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer, discoveryComponent, context); + Collections.EMPTY_LIST, this.configuration.getContainerName(), + this.configuration.getPluginContainerDeployment()); + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer, + discoveryComponent, context); newResources = new HashSet<Resource>(); if ((discoveredResources != null) && (!discoveredResources.isEmpty())) { IdentityHashMap<Configuration, DiscoveredResourceDetails> pluginConfigObjects = new IdentityHashMap<Configuration, DiscoveredResourceDetails>(); @@ -2403,8 +2405,8 @@ public class InventoryManager extends AgentService implements ContainerService, if (log.isDebugEnabled()) { log.debug("Merging [" + modifiedResourceIds.size() + "] modified Resources into local inventory..."); } - Set<Resource> modifiedResources = configuration.getServerServices().getDiscoveryServerService().getResources( - modifiedResourceIds, false); + Set<Resource> modifiedResources = configuration.getServerServices().getDiscoveryServerService() + .getResources(modifiedResourceIds, false); syncSchedules(modifiedResources); // RHQ-792, mtime is the indicator that schedules should be sync'ed too for (Resource modifiedResource : modifiedResources) { mergeResource(modifiedResource); @@ -2620,12 +2622,12 @@ public class InventoryManager extends AgentService implements ContainerService,
private void upgradeResources() { try { - + if (!configuration.isInsideAgent()) { log.debug("Skipping resource upgrade in embedded mode."); return; } - + log.debug("Executing resource upgrade.");
boolean syncResult = handleReport(new InventoryReport(getAgent()), true); @@ -2635,7 +2637,7 @@ public class InventoryManager extends AgentService implements ContainerService, }
upgradeResource(getPlatform()); - + log.debug("Sending the upgrade requests to the server."); resourceUpgradeDelegate.sendRequests();
commit 9050f4bfab5114ff31e19cb9c04b2d087dba2bff Author: Lukas Krejci lkrejci@redhat.com Date: Mon Oct 4 14:04:52 2010 +0200
Adding the test for handling the failure to upgrade some of the resources on the leaf of the plugin dependency graph.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ForwardingProxy.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ForwardingProxy.java new file mode 100644 index 0000000..7c7d277 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ForwardingProxy.java @@ -0,0 +1,72 @@ +/* + * 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.core.pc.upgrade; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * This class provides a simple proxy that just forwards the calls to the + * actual object. + * <p> + * This seemingly pointless behavior is useful when dealing with the classes + * loaded in different classloaders. + * <p> + * The arguments passed to the method invocations of the proxy must unfortunately be "understandable" + * both in the "current" classloader and in the context of the classloader that loaded the target object. + * I don't know about a generic solution to this problem. + * A partial solution would be to serialize the arguments and deserialize them in the context + * of the target classloader but that doesn't cut it for non-serializable classes obviously. + * + * @author Lukas Krejci + */ +public class ForwardingProxy { + + private static class ForwardingHandler implements InvocationHandler { + private Object target; + + public ForwardingHandler(Object target) { + this.target = target; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Method targetMethod = findMethodOnTarget(method); + + return targetMethod.invoke(target, args); + } + + private Method findMethodOnTarget(Method method) throws SecurityException, NoSuchMethodException { + Class<?>[] origParamTypes = method.getParameterTypes(); + + return target.getClass().getMethod(method.getName(), origParamTypes); + } + } + + public static <T> T forward(Object target, Class<T> targetInterface, Class<?>... additionalInterfaces) { + Class<?>[] interfaces = new Class<?>[additionalInterfaces.length + 1]; + interfaces[0] = targetInterface; + System.arraycopy(additionalInterfaces, 0, interfaces, 1, additionalInterfaces.length); + + Object proxy = Proxy.newProxyInstance(targetInterface.getClassLoader(), interfaces, new ForwardingHandler(target)); + return targetInterface.cast(proxy); + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java index 5949b76..7eafafc 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java @@ -20,14 +20,17 @@ package org.rhq.core.pc.upgrade;
import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail;
import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -36,10 +39,20 @@ import org.jmock.Expectations; import org.jmock.Mockery; import org.testng.annotations.Test;
+import org.rhq.core.clientapi.agent.PluginContainerException; +import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException; import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceErrorType; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.inventory.InventoryManager; +import org.rhq.core.pc.inventory.ResourceContainer; +import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState; +import org.rhq.core.pc.upgrade.plugins.multi.base.BaseResourceComponentInterface; import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
/** @@ -76,7 +89,7 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase private static final String TEST_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-2.0.0.jar";
private static final String UPGRADED_RESOURCE_KEY_PREFIX = "UPGRADED"; - + private static final HashMap<String, List<String>> DEPS;
static { @@ -100,9 +113,12 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase private static final ResType SIBLING_TYPE = new ResType("TestResourceSibling", "test"); private static final ResType PARENT_TYPE = new ResType("TestResourceParent", "test"); private static final ResType PARENT_DEP_TYPE = new ResType("ParentDependency", "parentdep"); - private static final ResType PARENT_SIBLING_TYPE = new ResType("ParentDepSibling", "parentsibling"); + private static final ResType PARENT_DEP_SIBLING_TYPE = new ResType("ParentDepSibling", "parentsibling"); private static final ResType ROOT_TYPE = new ResType("Root", "root");
+ private static List<ResType> ALL_TYPES = Arrays.asList(TEST_TYPE, SIBLING_TYPE, PARENT_TYPE, PARENT_DEP_TYPE, + PARENT_DEP_SIBLING_TYPE, ROOT_TYPE); + protected Collection<String> getRequiredPlugins() { return Arrays.asList(BASE_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, ROOT_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME, @@ -129,26 +145,20 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase });
//now let's run with v2 plugins and check the layout of the inventory - executeTestWithPlugins( - getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME), - new AbstractTestPayload(false, Arrays.asList(TEST_TYPE, SIBLING_TYPE, PARENT_TYPE, PARENT_DEP_TYPE, - PARENT_SIBLING_TYPE, ROOT_TYPE)) { + executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME), + new AbstractTestPayload(false, ALL_TYPES) {
public void test(Map<ResType, Set<Resource>> resources) { checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
checkNumberOfResources(resources, ROOT_TYPE, 1); checkNumberOfResources(resources, PARENT_DEP_TYPE, 1); - checkNumberOfResources(resources, PARENT_SIBLING_TYPE, 1); - checkNumberOfResources(resources, PARENT_TYPE, 2); - checkNumberOfResources(resources, SIBLING_TYPE, 30); - checkNumberOfResources(resources, TEST_TYPE, 30); - + //check that the resources are upgraded - checkResourcesUpgraded(resources.get(PARENT_SIBLING_TYPE)); - checkResourcesUpgraded(resources.get(PARENT_TYPE)); - checkResourcesUpgraded(resources.get(SIBLING_TYPE)); - checkResourcesUpgraded(resources.get(TEST_TYPE)); + checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1); + checkResourcesUpgraded(resources.get(PARENT_TYPE), 2); + checkResourcesUpgraded(resources.get(SIBLING_TYPE), 30); + checkResourcesUpgraded(resources.get(TEST_TYPE), 30); }
public Expectations getExpectations(Mockery context) throws Exception { @@ -162,10 +172,88 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase }
@Test - public void testFailureOnLeaf() { - //TODO implement - //check that the system behaves correctly if there is an upgrade failure - //at the leaf node of the plugin dep graph + public void testFailureOnLeaf() throws Exception { + setCurrentServerSideInventory(new FakeServerInventory()); + + executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME), + new AbstractTestPayload(true, Collections.<ResType> emptyList()) { + public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) { + //in here we set up the failures that are going to happen when + //the v2 plugins are run + + Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0); + assertNotNull(parent0, "Failed to find the parent to setup the failures for."); + Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1); + assertNotNull(parent1, "Failed to find the parent to setup the failures for."); + + addChildrenToFail(parent0, TEST_TYPE, 1, 2); + addChildrenToFail(parent1, SIBLING_TYPE, 1); + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); + + executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME), + new AbstractTestPayload(false, ALL_TYPES) { + public void test(Map<ResType, Set<Resource>> resources) { + checkPresenceOfResourceTypes(resources, getExpectedResourceTypes()); + + checkNumberOfResources(resources, ROOT_TYPE, 1); + checkNumberOfResources(resources, PARENT_DEP_TYPE, 1); + checkNumberOfResources(resources, PARENT_TYPE, 2); + + checkResourcesUpgraded(resources.get(PARENT_TYPE), 2); + checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1); + + Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0); + Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1); + + Set<Resource> siblingsUnderParent0 = filterResources(parent0.getChildResources(), SIBLING_TYPE); + Set<Resource> testsUnderParent0 = filterResources(parent0.getChildResources(), TEST_TYPE); + Set<Resource> siblingsUnderParent1 = filterResources(parent1.getChildResources(), SIBLING_TYPE); + Set<Resource> testsUnderParent1 = filterResources(parent1.getChildResources(), TEST_TYPE); + + checkResourcesUpgraded(siblingsUnderParent0, 15); + checkResourcesUpgraded(testsUnderParent1, 15); + + //there should be no newly discovered sibling resources of the failed ones + assertEquals(testsUnderParent0.size(), 10); + assertEquals(siblingsUnderParent1.size(), 10); + + //check that the failed resources have the error attached to them + //we find the resource instance from the map provided to this method + //because that map contains the resources as found on the server-side + //(i.e. they include error objects). + Resource failedTest1 = getEqualFrom(resources.get(TEST_TYPE), + findResourceWithOrdinal(testsUnderParent0, 1)); + Resource failedTest2 = getEqualFrom(resources.get(TEST_TYPE), + findResourceWithOrdinal(testsUnderParent0, 2)); + + checkResourceFailedUpgrade(failedTest1); + checkResourceFailedUpgrade(failedTest2); + checkOthersUpgraded(testsUnderParent0, failedTest1, failedTest2); + + Resource failedSibling = getEqualFrom(resources.get(SIBLING_TYPE), + findResourceWithOrdinal(siblingsUnderParent1, 1)); + + checkResourceFailedUpgrade(failedSibling); + checkOthersUpgraded(siblingsUnderParent1, failedSibling); + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); }
@Test @@ -180,13 +268,14 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase protected void defineDefaultExpectations(Expectations expectations) { super.defineDefaultExpectations(expectations); try { - expectations.allowing(getCurrentDiscoveryServerService()) - .mergeInventoryReport(expectations.with(Expectations.any(InventoryReport.class))); + expectations.allowing(getCurrentDiscoveryServerService()).mergeInventoryReport( + expectations.with(Expectations.any(InventoryReport.class))); expectations.will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
- expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources(expectations.with(Expectations.any(Set.class))); + expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources( + expectations.with(Expectations.any(Set.class))); expectations.will(getCurrentServerSideInventory().upgradeResources()); - + expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources( expectations.with(Expectations.any(Set.class)));
@@ -214,10 +303,112 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase private static void checkNumberOfResources(Map<ResType, Set<Resource>> resources, ResType type, int count) { assertEquals(resources.get(type).size(), count, "Unexpected number of " + type + " discovered."); } - - private static void checkResourcesUpgraded(Set<Resource> resources) { - for(Resource res : resources) { - assertTrue(res.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + res + " doesn't seem to be upgraded even though it should."); + + private static void checkResourcesUpgraded(Set<Resource> resources, int expectedSize) { + assertEquals(resources.size(), expectedSize, "The set of resources has unexpected size."); + for (Resource res : resources) { + assertTrue(res.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + res + + " doesn't seem to be upgraded even though it should."); + + ResourceContainer rc = PluginContainer.getInstance().getInventoryManager().getResourceContainer(res); + + assertEquals(rc.getResourceComponentState(), ResourceComponentState.STARTED, + "A resource that successfully upgraded should be started."); + } + } + + private static void checkResourceFailedUpgrade(Resource resource) { + assertFalse(resource.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + resource + + " seems to be upgraded even though it shouldn't."); + assertTrue(resource.getResourceErrors(ResourceErrorType.UPGRADE).size() == 1, + "The failed resource should have an error associated with it."); + + ResourceContainer rc = PluginContainer.getInstance().getInventoryManager().getResourceContainer(resource); + + assertEquals(rc.getResourceComponentState(), ResourceComponentState.STOPPED, + "A resource that failed to upgrade should be stopped."); + } + + private static void checkOthersUpgraded(Set<Resource> resources, Resource... failedResource) { + Set<Resource> others = new HashSet<Resource>(resources); + others.removeAll(Arrays.asList(failedResource)); + checkResourcesUpgraded(others, others.size()); + } + + private void addChildrenToFail(Resource parent, ResType childResType, int... childrenOrdinals) { + InventoryManager inventoryManager = PluginContainer.getInstance().getInventoryManager(); + ResourceContainer parentContainer = inventoryManager.getResourceContainer(parent); + BaseResourceComponentInterface parentComponent = (BaseResourceComponentInterface) parentContainer + .getResourceComponent(); + + Map<String, Set<Integer>> childrenToFail = new HashMap<String, Set<Integer>>(); + Set<Integer> ordinals = new HashSet<Integer>(); + for (int i = 0; i < childrenOrdinals.length; ++i) { + ordinals.add(childrenOrdinals[i]); + } + + childrenToFail.put(childResType.getResourceTypeName(), ordinals); + + Configuration newPluginConfig = parentComponent.createPluginConfigurationWithMarkedFailures(childrenToFail); + + try { + int resourceId = parent.getId(); + inventoryManager.updatePluginConfiguration(resourceId, newPluginConfig); + } catch (InvalidPluginConfigurationClientException e) { + fail("Updating plugin configuration failed.", e); + } catch (PluginContainerException e) { + fail("Updating plugin configuration failed.", e); + } + } + + private Resource findResourceWithOrdinal(ResType resType, int ordinal) { + ResourceType resourceType = PluginContainer.getInstance().getPluginManager().getMetadataManager() + .getType(resType.getResourceTypeName(), resType.getResourceTypePluginName()); + + InventoryManager inventoryManager = PluginContainer.getInstance().getInventoryManager(); + Set<Resource> resources = inventoryManager.getResourcesWithType(resourceType); + + return findResourceWithOrdinal(resources, ordinal); + } + + private Resource findResourceWithOrdinal(Set<Resource> resources, int ordinal) { + for (Resource r : resources) { + Configuration pluginConfig = r.getPluginConfiguration(); + String ordinalString = pluginConfig.getSimpleValue("ordinal", null); + + if (ordinalString != null && Integer.parseInt(ordinalString) == ordinal) { + return r; + } + } + + return null; + } + + private Set<Resource> filterResources(Set<Resource> resources, ResType resType) { + Set<Resource> ret = new HashSet<Resource>(resources); + + Iterator<Resource> it = ret.iterator(); + + while (it.hasNext()) { + ResourceType resourceType = it.next().getResourceType(); + + if (!resourceType.getName().equals(resType.getResourceTypeName()) + || !resourceType.getPlugin().equals(resType.getResourceTypePluginName())) { + + it.remove(); + } } + + return ret; + } + + private static <T> T getEqualFrom(Collection<? extends T> collection, T object) { + for (T other : collection) { + if (object.equals(other)) { + return other; + } + } + + return null; } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index d47d00c..04858c6 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -37,12 +37,13 @@ import java.util.Set;
import org.jmock.Expectations; import org.jmock.Mockery; +import org.testng.annotations.Test; + import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.inventory.ResourceContainer; -import org.testng.annotations.Test;
/** * Test cases for resource upgrade. @@ -55,234 +56,255 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { private static final String PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-1.0.0.jar"; private static final String PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-2.0.0.jar"; private static final String FAILING_PLUGIN_FILE_NAME = "/resource-upgrade-test-plugin-3.0.0.jar"; - + private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest"; - private static final ResType SINGLETON_TYPE = new ResType(SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME); - + private static final ResType SINGLETON_TYPE = new ResType(SINGLETON_RESOURCE_TYPE_NAME, + SINGLETON_RESOURCE_TYPE_PLUGIN_NAME); + private static List<ResType> getMyExpectedTypes() { return Arrays.asList(SINGLETON_TYPE); } - + protected Collection<String> getRequiredPlugins() { return Arrays.asList(PLUGIN_V1_FILENAME, PLUGIN_V2_FILENAME, FAILING_PLUGIN_FILE_NAME); } - + @Test public void testIgnoreUncommittedResources() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.NEW); - - TestPayload testNoChange = new AbstractTestPayload(false, getMyExpectedTypes()) { + + TestPayload testNoChange = new AbstractTestPayload(false, getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> discoveredResources) { - assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); } - + public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this); - - between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); } }; } }; - + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), testNoChange); } - + @Test public void testUpgradeData() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); upgradeTest(false); } - + @Test public void testInventoryReinitializationFromServerDuringUpgrade() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); upgradeTest(true); } - + @Test public void testSkipUpgradeWhenServerUnavailable() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED); - + getCurrentServerSideInventory().setFailing(true);
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> discoveredResources) { - assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next(); - + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); } - + @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this); - - between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); - + never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); } }; } }; - + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test); } - + @Test public void testUpgradeWithPlatformDeletedOnServer() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED); - - TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> discoveredResources) { - assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next(); - + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); assertEquals(discoveredResource.getDescription(), "resource-description-v2");
- ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + ResourceContainer container = PluginContainer.getInstance().getInventoryManager() + .getResourceContainer(discoveredResource); File dataDir = container.getResourceContext().getDataDirectory(); - + File marker = new File(dataDir, "upgrade-succeeded"); - - assertFalse(marker.exists(), "The upgrade seems to have occured even though there shouldn't have been a resource to upgrade."); + + assertFalse(marker.exists(), + "The upgrade seems to have occured even though there shouldn't have been a resource to upgrade."); } - + @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this); - + //the first merge will be triggered from within the upgrade process and we are //going to report null sync. - oneOf(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + oneOf(getCurrentDiscoveryServerService()) + .mergeInventoryReport(with(any(InventoryReport.class))); will(getCurrentServerSideInventory().clearPlatform()); - + //the rest of the inventory merges are executed by discoveries, so let's import the //discovered stuff into the server-side inventory. - between(1, 3).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + between(1, 3).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); - + never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); } }; } }; - + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test); } - + @Test public void testUpgradeFailureHandling() throws Exception { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED); - - TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) { - assertEquals(resourceUpgradeTestResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(resourceUpgradeTestResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = resourceUpgradeTestResources.get(SINGLETON_TYPE).iterator().next(); - - assertTrue(discoveredResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side."); - + + assertTrue(discoveredResource.getResourceErrors().size() > 0, + "There should be upgrade errors persisted on the server side."); + //the discovery of the failed resource mustn't have run - ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + ResourceContainer container = PluginContainer.getInstance().getInventoryManager() + .getResourceContainer(discoveredResource); File dataDir = container.getResourceContext().getDataDirectory(); - + File marker = new File(dataDir, "failing-discovery-ran"); - - assertFalse(marker.exists(), "The discovery of the resource type with a failed upgraded resource must not be executed but it was."); + + assertFalse(marker.exists(), + "The discovery of the resource type with a failed upgraded resource must not be executed but it was."); } - + @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this); - - between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); - + oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); will(getCurrentServerSideInventory().upgradeResources()); } }; } }; - + executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), test); } - + private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { cleanDataDir(); - executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true, getMyExpectedTypes()) { + executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true, + getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> discoveredResources) { - assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next(); - + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); } - + public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this); - - between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(requiredInventoryStatus)); } }; } - }); - + }); + }
- private void upgradeTest(boolean clearInventoryDat) throws Exception { initialSyncAndDiscovery(InventoryStatus.COMMITTED); - - executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat, getMyExpectedTypes()) { + + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat, + getMyExpectedTypes()) { public void test(Map<ResType, Set<Resource>> discoveredResources) { - assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); - + assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1, + "Expected single test resource but multiple found."); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next(); - + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); assertEquals(discoveredResource.getDescription(), "resource-description-v2"); - - ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + + ResourceContainer container = PluginContainer.getInstance().getInventoryManager() + .getResourceContainer(discoveredResource); File dataDir = container.getResourceContext().getDataDirectory(); - + File marker = new File(dataDir, "upgrade-succeeded"); - - assertTrue(marker.exists(), "The upgrade success marker file wasn't found. This means the upgrade didn't actually run."); + + assertTrue(marker.exists(), + "The upgrade success marker file wasn't found. This means the upgrade didn't actually run."); }
@SuppressWarnings("unchecked") @@ -290,10 +312,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { return new Expectations() { { defineDefaultExpectations(this); - - between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport( + with(any(InventoryReport.class))); will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); - + oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); will(getCurrentServerSideInventory().upgradeResources()); } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java index c5bbf3a..04d3767 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java @@ -19,11 +19,18 @@
package org.rhq.core.pc.upgrade.plugins.multi.base;
-import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; import java.util.Set;
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.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.measurement.AvailabilityType; import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; import org.rhq.core.pluginapi.inventory.ResourceComponent; @@ -33,13 +40,11 @@ import org.rhq.core.pluginapi.inventory.ResourceContext; * * @author Lukas Krejci */ -public class BaseResourceComponent<T extends ResourceComponent> implements ResourceComponent<T> { +public class BaseResourceComponent<T extends ResourceComponent> implements ResourceComponent<T>, BaseResourceComponentInterface {
private ResourceContext<T> context; private final Log log = LogFactory.getLog(getClass());
- private Set<Integer> childrenToFailUpgrade; - public AvailabilityType getAvailability() { return AvailabilityType.UP; } @@ -57,11 +62,57 @@ public class BaseResourceComponent<T extends ResourceComponent> implements Resou return context.getPluginConfiguration().getSimple("ordinal").getIntegerValue(); }
- public Set<Integer> getChildrenToFailUpgrade() { - return childrenToFailUpgrade == null ? Collections.<Integer>emptySet() : childrenToFailUpgrade; + public Map<String, Set<Integer>> getChildrenToFailUpgrade() { + + Map<String, Set<Integer>> ret = new HashMap<String, Set<Integer>>(); + + Configuration pluginConfig = context.getPluginConfiguration(); + PropertyList childrenToFail = pluginConfig.getList("childrenToFail"); + + if (childrenToFail != null) { + for(Property p : childrenToFail.getList()) { + PropertyMap entry = (PropertyMap) p; + + String type = entry.getSimpleValue("type", null); + + PropertyList typeList = entry.getList("children"); + + if (type != null && typeList != null) { + Set<Integer> ordinals = new HashSet<Integer>(); + + for(Property pp : typeList.getList()) { + ordinals.add(((PropertySimple)pp).getIntegerValue()); + } + + ret.put(type, ordinals); + } + } + } + + return ret; }
- public void setChildrenToFailUpgrade(Set<Integer> childrenToFailUpgrade) { - this.childrenToFailUpgrade = childrenToFailUpgrade; + public Configuration createPluginConfigurationWithMarkedFailures(Map<String, Set<Integer>> childrenToFailUpgrade) { + Configuration ret = context.getPluginConfiguration().clone(); + PropertyList list = new PropertyList("childrenToFail"); + + for(Map.Entry<String, Set<Integer>> entry : childrenToFailUpgrade.entrySet()) { + PropertyMap configEntry = new PropertyMap("childrenInType"); + configEntry.put(new PropertySimple("type", entry.getKey())); + + PropertyList typeList = new PropertyList("children"); + + for(Integer childOrdinal : entry.getValue()) { + typeList.add(new PropertySimple("ordinal", childOrdinal)); + } + + configEntry.put(typeList); + + list.add(configEntry); + } + + ret.put(list); + + return ret; } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponentInterface.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponentInterface.java new file mode 100644 index 0000000..1c9bef0 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponentInterface.java @@ -0,0 +1,36 @@ +/* + * 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.core.pc.upgrade.plugins.multi.base; + +import java.util.Map; +import java.util.Set; + +import org.rhq.core.domain.configuration.Configuration; + +/** + * This is to support proxying to required methods from the tests. + * + * @author Lukas Krejci + */ +public interface BaseResourceComponentInterface { + + Configuration createPluginConfigurationWithMarkedFailures(Map<String, Set<Integer>> childrenToFailUpgrade); + +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java index ec1cb20..5b8af94 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java @@ -19,6 +19,8 @@
package org.rhq.core.pc.upgrade.plugins.multi.base;
+import java.util.Set; + import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; @@ -41,7 +43,10 @@ public class BaseUpgradingDiscoveryComponent<T extends BaseResourceComponent> ex boolean fail = Boolean.getBoolean(pluginConfig.getSimpleValue("failUpgrade", "false"));
if (!fail && parent != null) { - fail = parent.getChildrenToFailUpgrade().contains(Integer.valueOf(ordinal)); + String typeName = inventoriedResource.getResourceType().getName(); + Set<Integer> failingOrdinals = parent.getChildrenToFailUpgrade().get(typeName); + + fail = failingOrdinals != null && failingOrdinals.contains(Integer.valueOf(ordinal)); }
if (fail) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/NothingDiscoveringDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/NothingDiscoveringDiscoveryComponent.java new file mode 100644 index 0000000..b6189e5 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/NothingDiscoveringDiscoveryComponent.java @@ -0,0 +1,42 @@ +/* + * 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.core.pc.upgrade.plugins.multi.base; + +import java.util.Collections; +import java.util.Set; + +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; + +/** + * + * @author Lukas Krejci + */ +public class NothingDiscoveringDiscoveryComponent<T extends ResourceComponent> implements ResourceDiscoveryComponent<T> { + + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<T> context) + throws InvalidPluginConfigurationException, Exception { + + return Collections.emptySet(); + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml index d3ea7b7..e3b4f9b 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml @@ -11,7 +11,7 @@
<depends plugin="base" useClasses="true"/>
- <server name="Bogus" class="BaseDiscoveryComponent"> + <server name="Bogus" class="BaseDiscoveryComponent" discovery="NothingDiscoveringDiscoveryComponent"> <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> <service name="TestResourceSibling" discovery="BaseDiscoveryComponent" diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml index f7f7a2c..e7792b9 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml @@ -10,7 +10,7 @@
<depends plugin="base" useClasses="true"/>
- <server name="Bogus" class="BaseDiscoveryComponent"> + <server name="Bogus" class="BaseDiscoveryComponent" discovery="NothingDiscoveringDiscoveryComponent"> <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> <service name="TestResourceSibling" discovery="BaseUpgradingDiscoveryComponent"
commit 3e06a613d311af3100a6d0a605a43a07564c9406 Merge: e68906f... 614e969... Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 21:12:36 2010 -0400
Merge branch 'master' into master-jay
commit e68906f5c7e3048921143a9d029a9e421c019f1d Merge: a524764... 54400ac... Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 18:18:10 2010 -0400
Merge branch 'master' into master-jay
Conflicts: modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeView.java modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java
diff --cc .classpath index 0a567d7,0a567d7..9a892fa --- a/.classpath +++ b/.classpath @@@ -255,5 -255,5 +255,6 @@@ <classpathentry exported="true" kind="var" path="M2_REPO/ca/nanometrics/gflot/1.0.0/gflot-1.0.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/commons-jxpath/commons-jxpath/1.3/commons-jxpath-1.3.jar"/> ++ <classpathentry exported="true" kind="var" path="M2_REPO/com/google/code/gwt-log/gwt-log/3.0.3/gwt-log-3.0.3.jar"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath>
commit a5247649b27165b9f2356a2d0d8dc983eaf7f8db Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 18:00:25 2010 -0400
Reverting a change made in 6415ed10e3b0d967b712a7be0aa0a3fcf4ce95cb, it breaks rendering of single-element paths (like "#Bundles or #Reports). The BookmarkableView's renderView needs to be invoked.
I didn't see any ill effect of adding this back in, so I'm not sure of the intent of the original change. May need more work.
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 34cf23e..d685c41 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 @@ -300,12 +300,19 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { }
if (this.currentCanvas instanceof BookmarkableView) { - viewPath.next(); - if (!viewPath.isEnd()) { - ((BookmarkableView) this.currentCanvas).renderView(viewPath); - } + ((BookmarkableView) this.currentCanvas).renderView(viewPath.next()); }
+ // reverting this is as it breaks rendering of single-element paths (like "#Bundles or + // #Reports. the BookmarkableView's renderView needs to be invoked. + // + //if (this.currentCanvas instanceof BookmarkableView) { + // viewPath.next(); + // if (!viewPath.isEnd()) { + // ((BookmarkableView) this.currentCanvas).renderView(viewPath); + // } + //} + refreshBreadCrumbTrail(); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleView.java index fb382fa..4dc2182 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/bundle/list/BundleView.java @@ -45,6 +45,7 @@ import org.rhq.enterprise.gui.coregui.client.Breadcrumb; import org.rhq.enterprise.gui.coregui.client.CoreGUI; import org.rhq.enterprise.gui.coregui.client.ViewId; import org.rhq.enterprise.gui.coregui.client.ViewPath; +import org.rhq.enterprise.gui.coregui.client.bundle.BundleTopView; import org.rhq.enterprise.gui.coregui.client.bundle.deploy.BundleDeployWizard; import org.rhq.enterprise.gui.coregui.client.bundle.deployment.BundleDeploymentView; import org.rhq.enterprise.gui.coregui.client.bundle.destination.BundleDestinationListView; @@ -98,7 +99,7 @@ public class BundleView extends LocatableVLayout implements BookmarkableView {
this.bundle = bundle;
- addMember(new BackButton(extendLocatorId("BackButton"), "Back to All Bundles", "Bundles")); + addMember(new BackButton(extendLocatorId("BackButton"), "Back to All Bundles", BundleTopView.VIEW_ID));
headerLabel = new HeaderLabel("subsystems/bundle/Bundle_24.png", bundle.getName());
commit fe8861d6f05baadd45f2ee9cad1deec2236970bf Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 16:27:38 2010 -0400
add jxpath test dep lib
diff --git a/.classpath b/.classpath index c13d973..0a567d7 100644 --- a/.classpath +++ b/.classpath @@ -254,5 +254,6 @@ <classpathentry exported="true" kind="var" path="M2_REPO/com/smartgwt/smartgwt/2.2/smartgwt-2.2.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/ca/nanometrics/gflot/1.0.0/gflot-1.0.0.jar"/> <classpathentry exported="true" kind="var" path="M2_REPO/com/jcraft/jsch/0.1.29/jsch-0.1.29.jar"/> + <classpathentry exported="true" kind="var" path="M2_REPO/commons-jxpath/commons-jxpath/1.3/commons-jxpath-1.3.jar"/> <classpathentry kind="output" path="eclipse-classes"/> </classpath>
commit 346c2223929d9d776a5bdc280fe87fcd159e2cb2 Merge: af34961... 77a5659... Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 10:04:07 2010 -0400
Merge branch 'master' into master-jay
commit 77a56598165197564c6e165211a04ec31a9979f8 Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 28 12:35:44 2010 -0400
AutoGroup/ResourceTree work - Fix up breadcrumbs for AutoGroup selections and also fix up some path - issues that were happening when selecting AG resources.
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 bb39f2d..34cf23e 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 @@ -254,10 +254,13 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { if (viewPath.matches("(" + ResourceTopView.VIEW_ID + "|" + ResourceGroupTopView.VIEW_ID + ")/[^/]*")) { // e.g. "Resource/10001" if (!currentViewPath.startsWith(viewPath)) { - // The Resource that was selected is not the same Resource that was previously selected - - // grab the end portion of the previous history URL and append it to the new history URL, - // so the same tab is selected for the new Resource. - String suffix = currentViewPath.replaceFirst("^[^/]*/[^/]*", ""); + // The Node that was selected is not the same Node that was previously selected - it + // may not even be the same node type. For example, the user could have moved from a + // resource to an autogroup in the same tree. Try to keep the tab selection sticky as best as + // possible while moving from one view to another by grabbing the end portion of the previous + // history URL and append it to the new history URL. The suffix is assumed to follow the + // ID (numeric) portion of the currentViewPath. + String suffix = currentViewPath.replaceFirst("\D*[^/]*", ""); viewPath += suffix; } } 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 6a7cba9..0d16bea 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 @@ -236,7 +236,6 @@ public class ResourceTreeView extends LocatableVLayout { // get back to this node given the id of the backing group (from the viewpath) autoGroupNodeMap.put(result.getId(), agNode); callback.onSuccess(result); - //renderAutoGroup(result); } }); } else { @@ -302,6 +301,23 @@ public class ResourceTreeView extends LocatableVLayout { } }
+ private void adjustBreadcrumb(TreeNode node, ViewId viewId) { + if (node instanceof ResourceTreeNode) { + Resource nr = ((ResourceTreeNode) node).getResource(); + String display = node.getName() + " <span class="subtitle">" + nr.getResourceType().getName() + "</span>"; + String icon = "types/" + nr.getResourceType().getCategory().getDisplayName() + "_up_16.png"; + + viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); + + } else if (node instanceof AutoGroupTreeNode) { + String name = ((AutoGroupTreeNode) node).getBackingGroupName(); + String display = node.getName() + " <span class="subtitle">" + name + "</span>"; + String icon = "types/" + ((AutoGroupTreeNode) node).getResourceType().getCategory() + "_up_16.png"; + + viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); + } + } + private void showContextMenu(AutoGroupTreeNode agNode) { getAutoGroupBackingGroup(agNode, new AsyncCallback<ResourceGroup>() { public void onFailure(Throwable caught) { @@ -680,23 +696,6 @@ public class ResourceTreeView extends LocatableVLayout { } }
- private void adjustBreadcrumb(TreeNode node, ViewId viewId) { - if (node instanceof ResourceTreeNode) { - - Resource nr = ((ResourceTreeNode) node).getResource(); - String display = node.getName() + " <span class="subtitle">" + nr.getResourceType().getName() + "</span>"; - String icon = "types/" + nr.getResourceType().getCategory().getDisplayName() + "_up_16.png"; - - viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); - - } else { - - // if (node.getName() != null) { - // viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), node.getName(), null, true)); - // } - } - } - /*private List<Resource> preload(final List<Resource> lineage) {
final ArrayList<Resource> list = new ArrayList<Resource>(lineage); @@ -730,8 +729,9 @@ public class ResourceTreeView extends LocatableVLayout { currentViewId = viewPath.getCurrent(); String currentViewIdPath = currentViewId.getPath(); if ("AutoGroup".equals(currentViewIdPath)) { - ViewId nextViewId = viewPath.getNext(); - Integer autoGroupId = Integer.parseInt(nextViewId.getPath()); + // Move the currentViewId to the ID portion to play better with other code + currentViewId = viewPath.getNext(); + Integer autoGroupId = Integer.parseInt(currentViewId.getPath()); setSelectedAutoGroup(autoGroupId); } else { Integer resourceId = Integer.parseInt(currentViewId.getPath());
commit af349612d16eb487345a7bf9d9b2921c7854e475 Author: Jay Shaughnessy jshaughn@redhat.com Date: Fri Oct 1 09:57:45 2010 -0400
ResourceTree Authz work - support for locked nodes - support for autogroups for non-inventory managers. Now that AGs are backed by compat groups it's necessary for non-inv-managers to be able to create and access the private groups that they own. Private groups (aka subject-owned groups) are new, they are basically groups that are tagged with the creating subjectId. Those groups can be created (via a new slsb call) and fetched (via a new ResourceGroupCriteria filter) w/o inventory manager perms. - note: i had to move rhq_subject to auth-schema from authz-schema and slightly change the dbsetup order to make it ok for rhq_resource_group to reference rhq_subject. - schema spec bumped to 2.97 - added ResourceLineageComposite to combine Resource and locked/viewable info.
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 02aa606..4035ed5 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -22,7 +22,7 @@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.96</db.schema.version> + <db.schema.version>2.97</db.schema.version> </properties>
<dependencies> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup-build.xml b/modules/core/dbutils/src/main/scripts/dbsetup-build.xml index f4993e5..b0ee520 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup-build.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup-build.xml @@ -39,7 +39,7 @@ To run the default target, you must set one of the following properties to true: <property name="dbsetup.scripts.dir" value="${basedir}/src/main/scripts/dbsetup" /> <property name="dbsetup.output.dir" value="${basedir}/target/dbsetup" /> <!-- away from classes so it doesn't go into the jar --> <!-- define the setup creation processing order. note, removals are done in the reverse order --> - <property name="dbsetup.subsystems" value="config,cluster,inventory,auth,authz,search,dashboard,operation,event,alert,sysconfig,scheduler,amps,measurement,content,resource-request,jms,obsolete"/> + <property name="dbsetup.subsystems" value="config,cluster,auth,inventory,authz,search,dashboard,operation,event,alert,sysconfig,scheduler,amps,measurement,content,resource-request,jms,obsolete"/> <property name="dbsetup.combined.schema" value="${dbsetup.output.dir}/all-schema.xml" /> <property name="dbsetup.combined.data" value="${dbsetup.output.dir}/all-data.xml" /> <property name="dbsetup.tstamp.file" value="${dbsetup.output.dir}/dbsetup-combine.tstamp" /> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/auth-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/auth-schema.xml index d24b386..9b77256 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/auth-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/auth-schema.xml @@ -16,5 +16,24 @@ </index>
</table> + + <table name="RHQ_SUBJECT"> + <column name="ID" default="sequence-only" initial="10001" + primarykey="true" required="true" type="INTEGER"/> + <column name="NAME" required="true" size="100" type="VARCHAR2"/> + <column name="CONFIGURATION_ID" type="INTEGER" references="RHQ_CONFIG"/> + <column name="FIRST_NAME" required="false" size="100" type="VARCHAR2"/> + <column name="LAST_NAME" required="false" size="100" type="VARCHAR2"/> + <column name="EMAIL_ADDRESS" size="100" type="VARCHAR2"/> + <column name="SMS_ADDRESS" size="100" type="VARCHAR2"/> + <column name="PHONE_NUMBER" size="100" type="VARCHAR2"/> + <column name="DEPARTMENT" size="100" type="VARCHAR2"/> + <column name="FACTIVE" required="true" type="BOOLEAN" default="true"/> + <column name="FSYSTEM" required="true" type="BOOLEAN" default="false"/> + + <index name="RHQ_SUBJECT_AUTH_KEY" unique="true"> + <field ref="NAME"/> + </index> + </table>
</dbsetup> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/authz-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/authz-schema.xml index 8d9f738..b1385e9 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/authz-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/authz-schema.xml @@ -50,25 +50,6 @@ </constraint> </table>
- <table name="RHQ_SUBJECT"> - <column name="ID" default="sequence-only" initial="10001" - primarykey="true" required="true" type="INTEGER"/> - <column name="NAME" required="true" size="100" type="VARCHAR2"/> - <column name="CONFIGURATION_ID" type="INTEGER" references="RHQ_CONFIG"/> - <column name="FIRST_NAME" required="false" size="100" type="VARCHAR2"/> - <column name="LAST_NAME" required="false" size="100" type="VARCHAR2"/> - <column name="EMAIL_ADDRESS" size="100" type="VARCHAR2"/> - <column name="SMS_ADDRESS" size="100" type="VARCHAR2"/> - <column name="PHONE_NUMBER" size="100" type="VARCHAR2"/> - <column name="DEPARTMENT" size="100" type="VARCHAR2"/> - <column name="FACTIVE" required="true" type="BOOLEAN" default="true"/> - <column name="FSYSTEM" required="true" type="BOOLEAN" default="false"/> - - <index name="RHQ_SUBJECT_AUTH_KEY" unique="true"> - <field ref="NAME"/> - </index> - </table> - <table name="RHQ_SUBJECT_ROLE_MAP"> <column name="SUBJECT_ID" required="true" type="INTEGER" references="RHQ_SUBJECT"/> <column name="ROLE_ID" required="true" type="INTEGER" references="RHQ_ROLE"/> diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml index 6246880..5d89c2d 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/inventory-schema.xml @@ -168,11 +168,14 @@
<column name="CATEGORY" type="VARCHAR2" size="20" required="true"/>
+ <!-- This is only set if this is a subject-owned group (like an autogroup) --> + <column name="SUBJECT_ID" type="INTEGER" references="RHQ_SUBJECT"/> + <!-- These two only set if this is a backing group for a resource auto-cluster --> <column name="CLUSTER_KEY" type="VARCHAR2" size="4000" required="false"/> <column name="CLUSTER_RESOURCE_GROUP_ID" type="INTEGER" references="RHQ_RESOURCE_GROUP"/>
- <!-- This only set if this is a backing group for a resource auto-group --> + <!-- This is only set if this is a backing group for a resource auto-group --> <column name="AUTO_GROUP_PARENT_RESOURCE_ID" type="INTEGER" references="RHQ_RESOURCE"/>
<column name="VISIBLE" type="BOOLEAN"/> 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 f0940ab..b477b09 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -3226,9 +3226,21 @@ REFERENCES RHQ_RESOURCE (ID) </statement> </schema-directSQL> - </schemaSpec> - + + <schemaSpec version="2.97"> + <!-- Support subject-owned groups (e.g. autogroups) --> + <schema-addColumn table="RHQ_RESOURCE_GROUP" column="SUBJECT_ID" columnType="INTEGER" /> + <schema-directSQL> + <statement desc="Creating RHQ_RESOURCE_GROUP foreign key relation to RHQ_SUBJECT for owned groups"> + ALTER TABLE RHQ_RESOURCE_GROUP + ADD CONSTRAINT RHQ_RG_SUBJECT_ID_FK + FOREIGN KEY (SUBJECT_ID) + REFERENCES RHQ_SUBJECT (ID) + </statement> + </schema-directSQL> + </schemaSpec> + </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java index 477a128..4a93c1f 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/auth/Subject.java @@ -24,11 +24,13 @@ package org.rhq.core.domain.auth;
import java.io.Serializable; import java.util.HashSet; +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; @@ -37,6 +39,7 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.QueryHint; import javax.persistence.SequenceGenerator; @@ -47,6 +50,7 @@ import org.jetbrains.annotations.NotNull;
import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.Recordizable;
/** @@ -271,6 +275,10 @@ public class Subject implements Serializable, Recordizable { @ManyToMany private java.util.Set<Role> ldapRoles;
+ // When a subject is removed any owned groups should also be removed + @OneToMany(mappedBy = "subject", fetch = FetchType.LAZY) + private List<ResourceGroup> ownedGroups = null; + @Transient private Integer sessionId = null;
@@ -448,6 +456,14 @@ public class Subject implements Serializable, Recordizable { getLdapRoles().remove(role); }
+ public List<ResourceGroup> getOwnedGroups() { + return ownedGroups; + } + + public void setOwnedGroups(List<ResourceGroup> ownedGroups) { + this.ownedGroups = ownedGroups; + } + @Override public String toString() { return "org.rhq.core.domain.auth.Subject[id=" + id + ",name=" + name + "]"; diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java index 2278c7f..835821a 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/criteria/ResourceGroupCriteria.java @@ -46,6 +46,7 @@ public class ResourceGroupCriteria extends TaggedCriteria { private Boolean filterRecursive; private Integer filterResourceTypeId; // requires overrides private String filterResourceTypeName; // requires overrides + private Integer filterSubjectId; // requires overrides private Integer filterAutoGroupParentResourceId; // requires overrides private String filterPluginName; // requires overrides private GroupCategory filterGroupCategory; @@ -56,6 +57,7 @@ public class ResourceGroupCriteria extends TaggedCriteria { private Integer filterExplicitResourceTypeId; // requires overrides private String filterExplicitResourceTypeName; // requires overrides private Integer filterGroupDefinitionId; // requires overrides + private Boolean filterPrivate; /* if true, show only private groups for the calling user */ private Boolean filterVisible = true; /* only show visible groups by default */
private boolean fetchExplicitResources; @@ -74,6 +76,7 @@ public class ResourceGroupCriteria extends TaggedCriteria { filterOverrides.put("resourceTypeId", "resourceType.id = ?"); filterOverrides.put("resourceTypeName", "resourceType.name like ?"); filterOverrides.put("autoGroupParentResourceId", "autoGroupParentResource.id = ?"); + filterOverrides.put("subjectId", "subject.id = ?"); filterOverrides.put("pluginName", "resourceType.plugin like ?"); filterOverrides.put("downMemberCount", "" // + "id IN ( SELECT implicitGroup.id " // @@ -148,6 +151,14 @@ public class ResourceGroupCriteria extends TaggedCriteria { this.filterResourceTypeName = filterResourceTypeName; }
+ /** + * Requires MANAGE_INVENTORY. Use addFilterPrivate(true) to filter on the caller's private groups. + * @param filterSubjectId. + */ + public void addFilterSubjectId(Integer filterSubjectId) { + this.filterSubjectId = filterSubjectId; + } + public void addFilterAutoGroupParentResourceId(Integer filterAutoGroupParentResourceId) { this.filterAutoGroupParentResourceId = filterAutoGroupParentResourceId; } @@ -199,6 +210,14 @@ public class ResourceGroupCriteria extends TaggedCriteria { this.filterGroupDefinitionId = filterGroupDefinitionId; }
+ public void addFilterPrivate(Boolean filterPrivate) { + this.filterPrivate = filterPrivate; + } + + public boolean isFilterPrivate() { + return (Boolean.TRUE.equals(this.filterPrivate)); + } + public void addFilterVisible(Boolean filterVisible) { this.filterVisible = filterVisible; } @@ -258,8 +277,8 @@ public class ResourceGroupCriteria extends TaggedCriteria {
@Override public boolean isInventoryManagerRequired() { - // presently only inventory managers can view/manage group definitions - return this.filterGroupDefinitionId != null; + // presently only inventory managers can view/manage group definitions or see other user's private groups + return this.filterGroupDefinitionId != null || this.filterSubjectId != null; }
} diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java new file mode 100644 index 0000000..713a558 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/composite/ResourceLineageComposite.java @@ -0,0 +1,51 @@ +/* + * 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.core.domain.resource.composite; + +import java.io.Serializable; + +import org.rhq.core.domain.resource.Resource; + +/** + * @author jay shaughnessy + */ +public class ResourceLineageComposite implements Serializable { + private static final long serialVersionUID = 1L; + + private Resource resource; + private boolean isLocked; + + // for gwt serialization + @SuppressWarnings("unused") + private ResourceLineageComposite() { + } + + public ResourceLineageComposite(Resource resource, boolean isLocked) { + this.resource = resource; + this.isLocked = isLocked; + } + + public Resource getResource() { + return resource; + } + + public boolean isLocked() { + return isLocked; + } +} \ No newline at end of file diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ResourceGroup.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ResourceGroup.java index 46d6bcb..5250c11 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ResourceGroup.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/group/ResourceGroup.java @@ -55,6 +55,7 @@ import javax.xml.bind.annotation.XmlAccessorType; import org.jetbrains.annotations.NotNull;
import org.rhq.core.domain.alert.AlertDefinition; +import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.bundle.BundleDestination; import org.rhq.core.domain.configuration.group.AbstractGroupConfigurationUpdate; @@ -432,6 +433,12 @@ public class ResourceGroup extends Group { @ManyToOne private ResourceType resourceType; // if non-null, it implies a compatible group
+ // The group owner. Certain groups (like autogroups) are not associated with Roles. Instead, they + // are bound to specific owners. Subject-Owned groups defer to member-level authorization as needed. + @JoinColumn(name = "SUBJECT_ID", referencedColumnName = "ID", nullable = true) + @ManyToOne + private Subject subject = null; + @Column(name = "CLUSTER_KEY", nullable = true) private String clusterKey;
@@ -612,6 +619,25 @@ public class ResourceGroup extends Group { } }
+ public Subject getSubject() { + return subject; + } + + public void setSubject(Subject subject) { + if (this.id > 0 && null != this.subject) { + throw new IllegalStateException("The group owner can not be changed after the group is created."); + } + + this.subject = subject; + } + + /** + * @return true if this is a subject-owned group, private to the set subject + */ + public boolean isPrivateGroup() { + return (null != this.subject); + } + public String getClusterKey() { return clusterKey; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index b282e41..7ad683a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@ -32,6 +32,7 @@ import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.resource.composite.ProblemResourceComposite; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList;
@@ -44,9 +45,7 @@ public interface ResourceGWTService extends RemoteService {
PageList<ResourceComposite> findResourceCompositesByCriteria(ResourceCriteria criteria);
- List<Resource> getResourceLineage(int resourceId); - - List<Resource> getResourceLineageAndSiblings(int resourceId); + List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId);
List<RecentlyAddedResourceComposite> findRecentlyAddedResources(long ctime, int maxItems);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java index d968e19..f48fd96 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGroupGWTService.java @@ -37,6 +37,14 @@ public interface ResourceGroupGWTService extends RemoteService {
GroupDefinition createGroupDefinition(GroupDefinition groupDefinition);
+ /** + * The owner will be set to the session subject. + * @param group + * @param resourceIds initial members + * @return + */ + ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds); + ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds);
void deleteGroupDefinitions(int[] groupDefinitionIds); 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 50700f2..33b22e9 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 @@ -243,4 +243,9 @@ public abstract class AbstractTwoLevelTabSetView<T, U extends Layout> extends Lo public String getSubTabName() { return subTabName; } + + public String getBaseViewPath() { + return baseViewPath; + } + } 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 e5bfc72..90388fc 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 @@ -271,7 +271,12 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource
ResourceGroupCriteria criteria = new ResourceGroupCriteria(); criteria.addFilterId(groupId); - criteria.addFilterVisible(null); + + // for autogroups we need to add more criteria + if (AUTO_GROUP_VIEW_PATH.equals(getBaseViewPath())) { + criteria.addFilterVisible(null); + criteria.addFilterPrivate(true); + }
GWTServiceLookup.getResourceGroupService().findResourceGroupCompositesByCriteria(criteria, new AsyncCallback<PageList<ResourceGroupComposite>>() { @@ -281,6 +286,11 @@ public class ResourceGroupDetailView extends AbstractTwoLevelTabSetView<Resource }
public void onSuccess(PageList<ResourceGroupComposite> result) { + if (result.isEmpty()) { + CoreGUI.getErrorHandler().handleError( + "Failed to load group composite for group with id " + groupId); + } + groupComposite = result.get(0); loadResourceType(groupComposite, viewPath, globalPermissions); } 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 71e6c61..f1dad07 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 @@ -23,6 +23,7 @@ import com.smartgwt.client.widgets.tree.TreeNode;
import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Resource; +import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.ResourceTreeDatasource.ResourceTreeNode; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableTreeGrid;
/** @@ -40,15 +41,19 @@ public class CustomResourceTreeGrid extends LocatableTreeGrid { if (record instanceof TreeNode) { boolean open = getTree().isOpen((TreeNode) record);
- if (record instanceof ResourceTreeDatasource.ResourceTreeNode) { - Resource resource = ((ResourceTreeDatasource.ResourceTreeNode) record).getResource(); + if (record instanceof ResourceTreeNode) { + ResourceTreeNode node = (ResourceTreeNode) record;
- boolean up = resource.getCurrentAvailability().getAvailabilityType() == AvailabilityType.UP; + if (node.isLocked()) { + return "global/Locked_16.png";
- String category = resource.getResourceType().getCategory().getDisplayName(); - - return "types/" + category + "_" + (up ? "up" : "down") + "_16.png"; + } else { + Resource resource = ((ResourceTreeDatasource.ResourceTreeNode) record).getResource(); + String category = resource.getResourceType().getCategory().getDisplayName(); + boolean up = resource.getCurrentAvailability().getAvailabilityType() == AvailabilityType.UP;
+ return "types/" + category + "_" + (up ? "up" : "down") + "_16.png"; + } } else { return "resources/folder_group_" + (open ? "opened" : "closed") + ".png"; } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java index 3ad6835..5f9e07c 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceTreeDatasource.java @@ -30,7 +30,6 @@ import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.data.DataSourceField; -import com.smartgwt.client.data.fields.DataSourceImageField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.rpc.RPCResponse; import com.smartgwt.client.types.DSDataFormat; @@ -38,8 +37,6 @@ import com.smartgwt.client.types.DSProtocol; import com.smartgwt.client.widgets.tree.TreeNode;
import org.rhq.core.domain.criteria.ResourceCriteria; -import org.rhq.core.domain.measurement.AvailabilityType; -import org.rhq.core.domain.measurement.ResourceAvailability; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceSubCategory; @@ -61,15 +58,17 @@ import org.rhq.enterprise.gui.coregui.client.util.StringUtility; */ public class ResourceTreeDatasource extends DataSource { private List<Resource> initialData; + private List<Resource> lockedData;
private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService();
- public ResourceTreeDatasource(List<Resource> initialData) { + public ResourceTreeDatasource(List<Resource> initialData, List<Resource> lockedData) { setClientOnly(false); setDataProtocol(DSProtocol.CLIENTCUSTOM); setDataFormat(DSDataFormat.CUSTOM);
this.initialData = initialData; + this.lockedData = (null != lockedData) ? lockedData : new ArrayList<Resource>();
DataSourceField idDataField = new DataSourceTextField("id", "ID"); idDataField.setPrimaryKey(true); @@ -80,22 +79,12 @@ public class ResourceTreeDatasource extends DataSource { DataSourceTextField descriptionDataField = new DataSourceTextField("description", "Description"); descriptionDataField.setCanEdit(false);
- DataSourceImageField availabilityDataField = new DataSourceImageField("currentAvailability", "Availability"); - descriptionDataField.setCanEdit(false); - DataSourceTextField parentIdField = new DataSourceTextField("parentId", "Parent ID"); parentIdField.setForeignKey("id"); - // parentIdField.setRootValue(rootId); - - // DataSourceTextField parentKeyField = new DataSourceTextField("parentKey", "Parent KEY"); - // parentKeyField.setForeignKey("id"); - // parentKeyField.setRootValue(rootId); - - // nameDataField.setType(FieldType.);
setDropExtraFields(false);
- setFields(idDataField, nameDataField, descriptionDataField, availabilityDataField); + setFields(idDataField, nameDataField, descriptionDataField); }
@Override @@ -127,7 +116,7 @@ public class ResourceTreeDatasource extends DataSource { }
public void executeFetch(final String requestId, final DSRequest request, final DSResponse response) { - final long start = System.currentTimeMillis(); + //final long start = System.currentTimeMillis();
String parentResourceId = request.getCriteria().getAttribute("parentId"); // System.out.println("All attributes: " + Arrays.toString(request.getCriteria().getAttributes())); @@ -173,7 +162,7 @@ public class ResourceTreeDatasource extends DataSource { ResourceTypeRepository.MetadataType.subCategory), new ResourceTypeRepository.ResourceTypeLoadedCallback() { public void onResourceTypeLoaded(List<Resource> result) { - TreeNode[] treeNodes = buildNodes(result); + TreeNode[] treeNodes = buildNodes(result, lockedData); response.setData(treeNodes); processResponse(requestId, response); response.setStatus(DSResponse.STATUS_SUCCESS); @@ -187,11 +176,11 @@ public class ResourceTreeDatasource extends DataSource { * @param resources * @return */ - public static TreeNode[] buildNodes(List<Resource> resources) { + public static TreeNode[] buildNodes(List<Resource> resources, List<Resource> lockedData) { ResourceTreeNode[] nodes = new ResourceTreeNode[resources.size()]; for (int i = 0; i < resources.size(); i++) { Resource resource = resources.get(i); - ResourceTreeNode node = new ResourceTreeNode(resource); + ResourceTreeNode node = new ResourceTreeNode(resource, lockedData.contains(resource)); nodes[i] = node; }
@@ -350,9 +339,11 @@ public class ResourceTreeDatasource extends DataSource {
public static class ResourceTreeNode extends EnhancedTreeNode { private Resource resource; + private boolean isLocked;
- private ResourceTreeNode(Resource resource) { + private ResourceTreeNode(Resource resource, boolean isLocked) { this.resource = resource; + this.isLocked = isLocked;
String id = idOf(resource); setID(id); @@ -369,21 +360,12 @@ public class ResourceTreeDatasource extends DataSource { setParentID(parentId); setAttribute(Attributes.PARENT_ID, parentId);
- // System.out.println(id + " / " + parentId); - // setAttribute("parentKey", resource.getParentResource() == null ? 0 : (resource.getParentResource().getId() + resource.getResourceType().getName())); - String name = resource.getName(); setName(name); setAttribute(Attributes.NAME, name);
setAttribute(Attributes.DESCRIPTION, resource.getDescription());
- ResourceAvailability currentAvail = resource.getCurrentAvailability(); - setAttribute( - "currentAvailability", - (null != currentAvail && currentAvail.getAvailabilityType() == AvailabilityType.UP) ? "/images/icons/availability_green_16.png" - : "/images/icons/availability_red_16.png"); - Set<ResourceType> childTypes = resource.getResourceType().getChildResourceTypes(); setIsFolder((childTypes != null && !childTypes.isEmpty())); } @@ -392,6 +374,10 @@ public class ResourceTreeDatasource extends DataSource { return this.resource; }
+ public boolean isLocked() { + return isLocked; + } + public static String idOf(Resource resource) { return idOf(resource.getId()); } 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 0d16bea..4cea21b 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 @@ -63,6 +63,7 @@ import org.rhq.core.domain.operation.OperationDefinition; 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.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageList; import org.rhq.enterprise.gui.coregui.client.Breadcrumb; @@ -142,14 +143,20 @@ public class ResourceTreeView extends LocatableVLayout { if (!selectionEvent.isRightButtonDown() && selectionEvent.getState()) { ListGridRecord selectedRecord = treeGrid.getSelectedRecord(); if (selectedRecord instanceof ResourceTreeNode) { - System.out.println("AutoGroup Node selected in tree: " + selectedRecord); - ResourceTreeNode resourceNode = (ResourceTreeNode) selectedRecord; - selectedNodeId = resourceNode.getID(); - String viewPath = "Resource/" + resourceNode.getResource().getId(); - String currentViewPath = History.getToken(); - if (!currentViewPath.startsWith(viewPath)) { - CoreGUI.goToView(viewPath); + + if (!resourceNode.isLocked()) { + System.out.println("Resource Node selected in tree: " + selectedRecord); + + selectedNodeId = resourceNode.getID(); + String viewPath = "Resource/" + resourceNode.getResource().getId(); + String currentViewPath = History.getToken(); + if (!currentViewPath.startsWith(viewPath)) { + CoreGUI.goToView(viewPath); + } + } else { + // TODO: Can we select the previous node? Or do we need a "Locked" hover etc... + treeGrid.deselectAllRecords(); } } else if (selectedRecord instanceof AutoGroupTreeNode) { System.out.println("AutoGroup Node selected in tree: " + selectedRecord); @@ -183,7 +190,9 @@ public class ResourceTreeView extends LocatableVLayout { if (event.getNode() instanceof AutoGroupTreeNode) { showContextMenu((AutoGroupTreeNode) event.getNode()); } else if (event.getNode() instanceof ResourceTreeNode) { - showContextMenu((ResourceTreeNode) event.getNode()); + if (!((ResourceTreeNode) event.getNode()).isLocked()) { + showContextMenu((ResourceTreeNode) event.getNode()); + } } } }); @@ -207,6 +216,7 @@ public class ResourceTreeView extends LocatableVLayout {
// get the backing group if it exists, otherwise create the group ResourceGroupCriteria criteria = new ResourceGroupCriteria(); + criteria.addFilterPrivate(true); criteria.addFilterResourceTypeId(agNode.getResourceType().getId()); criteria.addFilterAutoGroupParentResourceId(agNode.getParentResource().getId()); criteria.addFilterVisible(false); @@ -224,8 +234,7 @@ public class ResourceTreeView extends LocatableVLayout { backingGroup.setAutoGroupParentResource(agNode.getParentResource()); backingGroup.setResourceType(agNode.getResourceType()); backingGroup.setVisible(false); - backingGroup.setRecursive(false); - resourceGroupService.createResourceGroup(backingGroup, childIds, + resourceGroupService.createPrivateResourceGroup(backingGroup, childIds, new AsyncCallback<ResourceGroup>() { public void onFailure(Throwable caught) { CoreGUI.getErrorHandler().handleError("Failed to create resource autogroup", caught); @@ -596,65 +605,79 @@ public class ResourceTreeView extends LocatableVLayout { selectedNodeId = ResourceTreeNode.idOf(selectedResourceId);
final ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); - // This is an expensive call, but loads all nodes that are visible in the tree given a selected resource - resourceService.getResourceLineageAndSiblings(selectedResourceId, new AsyncCallback<List<Resource>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to lookup platform for tree", caught); - }
- public void onSuccess(List<Resource> result) { - Resource root = result.get(0); + // This is an expensive call, but loads all nodes that are visible in the tree given a selected resource + resourceService.getResourceLineageAndSiblings(selectedResourceId, + new AsyncCallback<List<ResourceLineageComposite>>() {
- if (!root.equals(ResourceTreeView.this.rootResource)) { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to lookup platform for tree", caught); + }
- if (treeGrid != null) { - treeGrid.destroy(); - } - buildTree(); + public void onSuccess(List<ResourceLineageComposite> result) { + Resource root = result.get(0).getResource();
- setRootResource(root); + final List<Resource> lineage = new ArrayList<Resource>(result.size()); + final List<Resource> lockedData = new ArrayList<Resource>();
- // seed datasource with initial resource list - ResourceTreeDatasource dataSource = new ResourceTreeDatasource(result); - treeGrid.setDataSource(dataSource); + for (ResourceLineageComposite r : result) { + lineage.add(r.getResource()); + if (r.isLocked()) { + lockedData.add(r.getResource()); + } + }
- addMember(treeGrid); + if (!root.equals(ResourceTreeView.this.rootResource)) {
- treeGrid.fetchData(treeGrid.getCriteria(), new DSCallback() { - public void execute(DSResponse response, Object rawData, DSRequest request) { - System.out.println("Done fetching data for tree."); - updateSelection(); + if (treeGrid != null) { + treeGrid.destroy(); } - }); + buildTree();
- updateSelection(); + setRootResource(root);
- } else { - ResourceTypeRepository.Cache.getInstance().loadResourceTypes( - result, - EnumSet.of(ResourceTypeRepository.MetadataType.operations, - ResourceTypeRepository.MetadataType.children, - ResourceTypeRepository.MetadataType.subCategory), - new ResourceTypeRepository.ResourceTypeLoadedCallback() { - public void onResourceTypeLoaded(List<Resource> result) { - treeGrid.getTree().linkNodes(ResourceTreeDatasource.buildNodes(result)); - - TreeNode selectedNode = treeGrid.getTree().findById(selectedNodeId); - if (selectedNode != null) { - updateSelection(); - - } else { - CoreGUI.getMessageCenter().notify( - new Message("Failed to select Resource [" + selectedResourceId + "] in tree.", - Message.Severity.Warning)); - } + // seed datasource with initial resource list and which ancestor resources are locked + ResourceTreeDatasource dataSource = new ResourceTreeDatasource(lineage, lockedData); + treeGrid.setDataSource(dataSource);
+ addMember(treeGrid); + + treeGrid.fetchData(treeGrid.getCriteria(), new DSCallback() { + public void execute(DSResponse response, Object rawData, DSRequest request) { + System.out.println("Done fetching data for tree."); + updateSelection(); } });
+ updateSelection(); + + } else { + ResourceTypeRepository.Cache.getInstance().loadResourceTypes( + lineage, + EnumSet.of(ResourceTypeRepository.MetadataType.operations, + ResourceTypeRepository.MetadataType.children, + ResourceTypeRepository.MetadataType.subCategory), + new ResourceTypeRepository.ResourceTypeLoadedCallback() { + public void onResourceTypeLoaded(List<Resource> result) { + treeGrid.getTree() + .linkNodes(ResourceTreeDatasource.buildNodes(lineage, lockedData)); + + TreeNode selectedNode = treeGrid.getTree().findById(selectedNodeId); + if (selectedNode != null) { + updateSelection(); + + } else { + CoreGUI.getMessageCenter().notify( + new Message("Failed to select Resource [" + selectedResourceId + + "] in tree.", Message.Severity.Warning)); + } + + } + }); + + } } - } - }); + }); }
public void setSelectedAutoGroup(final Integer selectedAutoGroupId) { diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index 66a25be..2e2f6d6 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -39,6 +39,7 @@ import org.rhq.core.domain.resource.composite.DisambiguationReport; import org.rhq.core.domain.resource.composite.ProblemResourceComposite; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.util.IntExtractor; @@ -167,13 +168,8 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re } };
- public List<Resource> getResourceLineage(int resourceId) { - return SerialUtility.prepare(resourceManager.getResourceLineage(resourceId), - "ResourceService.getResourceLineage"); - } - - public List<Resource> getResourceLineageAndSiblings(int resourceId) { - return SerialUtility.prepare(resourceManager.getResourceLineageAndSiblings(resourceId), + public List<ResourceLineageComposite> getResourceLineageAndSiblings(int resourceId) { + return SerialUtility.prepare(resourceManager.getResourceLineageAndSiblings(getSessionSubject(), resourceId), "ResourceService.getResourceLineageAndSiblings"); }
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java index 1ddecc3..2015091 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGroupGWTServiceImpl.java @@ -87,6 +87,17 @@ public class ResourceGroupGWTServiceImpl extends AbstractGWTServiceImpl implemen } }
+ public ResourceGroup createPrivateResourceGroup(ResourceGroup group, int[] resourceIds) { + try { + Subject user = getSessionSubject(); + group = groupManager.createPrivateResourceGroup(user, group); + groupManager.setAssignedResources(user, group.getId(), resourceIds, true); + return SerialUtility.prepare(group, "ResourceGroupService.createResourceGroup"); + } catch (Throwable t) { + throw new RuntimeException(ThrowableUtil.getAllMessages(t)); + } + } + public ResourceGroup createResourceGroup(ResourceGroup group, int[] resourceIds) { try { Subject user = getSessionSubject(); diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java index 4e1a53d..37ec2c9 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/auth/SubjectManagerBean.java @@ -48,6 +48,7 @@ import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.authz.Role; import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.criteria.SubjectCriteria; +import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.server.PersistenceUtility; @@ -58,6 +59,7 @@ import org.rhq.enterprise.server.authz.PermissionException; import org.rhq.enterprise.server.authz.RequiredPermission; import org.rhq.enterprise.server.core.CustomJaasDeploymentServiceMBean; import org.rhq.enterprise.server.exception.LoginException; +import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; import org.rhq.enterprise.server.system.SystemManagerLocal; import org.rhq.enterprise.server.util.CriteriaQueryGenerator; import org.rhq.enterprise.server.util.CriteriaQueryRunner; @@ -69,7 +71,6 @@ import org.rhq.enterprise.server.util.CriteriaQueryRunner; */ @Stateless public class SubjectManagerBean implements SubjectManagerLocal, SubjectManagerRemote { - @SuppressWarnings("unused") private final Log log = LogFactory.getLog(SubjectManagerBean.class);
@PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME) @@ -79,6 +80,10 @@ public class SubjectManagerBean implements SubjectManagerLocal, SubjectManagerRe private AuthorizationManagerLocal authorizationManager;
@EJB + @IgnoreDependency + private ResourceGroupManagerLocal resourceGroupManager; + + @EJB private SystemManagerLocal systemManager;
@EJB @@ -508,6 +513,25 @@ public class SubjectManagerBean implements SubjectManagerLocal, SubjectManagerRe deletePrincipal(subject, doomedSubject); }
+ // one more thing, delete any owned groups + List<ResourceGroup> ownedGroups = doomedSubject.getOwnedGroups(); + if (!ownedGroups.isEmpty()) { + int size = ownedGroups.size(); + int[] ownedGroupIds = new int[size]; + for (int i = 0; (i < size); ++i) { + ownedGroupIds[i] = ownedGroups.get(i).getId(); + } + try { + resourceGroupManager.deleteResourceGroups(subject, ownedGroupIds); + } catch (Throwable t) { + if (log.isDebugEnabled()) { + log.error("Error deleting owned group " + ownedGroupIds, t); + } else { + log.error("Error deleting owned group " + ownedGroupIds + ": " + t.getMessage()); + } + } + } + deleteSubject(subject, doomedSubject); }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java index d675177..1a14a56 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/authz/AuthorizationManagerBean.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.server.authz;
+import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.List; @@ -32,6 +33,8 @@ import javax.persistence.Query; import org.rhq.core.domain.auth.Subject; import org.rhq.core.domain.authz.Permission; import org.rhq.core.domain.authz.Permission.Target; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.group.ResourceGroup; import org.rhq.enterprise.server.RHQConstants;
/** @@ -117,12 +120,33 @@ public class AuthorizationManagerBean implements AuthorizationManagerLocal { return true; }
- Query query = entityManager.createNamedQuery(Subject.QUERY_HAS_GROUP_PERMISSION); - query.setParameter("subject", subject); - query.setParameter("permission", permission); - query.setParameter("groupId", groupId); - long count = (Long) query.getSingleResult(); - return (count != 0); + ResourceGroup group = entityManager.find(ResourceGroup.class, groupId); + Subject owner = group.getSubject(); + + if (null == owner) { + // role-owned group + Query query = entityManager.createNamedQuery(Subject.QUERY_HAS_GROUP_PERMISSION); + query.setParameter("subject", subject); + query.setParameter("permission", permission); + query.setParameter("groupId", groupId); + long count = (Long) query.getSingleResult(); + return (count != 0); + + } else { + // don't let a user other than the owner do anything with this group + if (!subject.equals(owner)) { + return false; + } + + // subject-owned group, requires perm check against each group member + Set<Resource> members = group.getExplicitResources(); + List<Integer> memberIds = new ArrayList<Integer>(members.size()); + for (Resource member : members) { + memberIds.add(member.getId()); + } + + return hasResourcePermission(owner, permission, memberIds); + } }
public boolean hasResourcePermission(Subject subject, Permission permission, int resourceId) { 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 0528b06..bf213c0 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 @@ -94,6 +94,7 @@ import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.composite.ResourceHealthComposite; import org.rhq.core.domain.resource.composite.ResourceIdFlyWeight; import org.rhq.core.domain.resource.composite.ResourceInstallCount; +import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.resource.composite.ResourcePermission; import org.rhq.core.domain.resource.composite.ResourceWithAvailability; import org.rhq.core.domain.resource.flyweight.FlyweightCache; @@ -721,27 +722,68 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage return resourceLineage; }
- public List<Resource> getResourceLineageAndSiblings(int resourceId) { - List<Resource> resourceLineage = getResourceLineage(resourceId); - List<Resource> result = new LinkedList<Resource>(); + public List<ResourceLineageComposite> getResourceLineageAndSiblings(Subject subject, int resourceId) { + boolean isInventoryManager = authorizationManager.isInventoryManager(subject);
- Resource platform = resourceLineage.get(0); - result.add(platform); - for (Resource resource : resourceLineage) { - if (resource.getParentResource() != null) { - // This ensures Hibernate actually fetches the parent Resource. - resource.getParentResource().getId(); - } - Set<Resource> childResources = resource.getChildResources(); - result.addAll(childResources); - for (Resource childResource : childResources) { - // This ensures Hibernate actually fetches the parent Resource. - childResource.getParentResource().getId(); - Set<Resource> grandchildResources = childResource.getChildResources(); - result.addAll(grandchildResources); - for (Resource grandchildResource : grandchildResources) { + // get the raw resource lineage up to the platform. We'll check the auth below + List<Resource> rawResourceLineage = getResourceLineage(resourceId); + int depth = rawResourceLineage.size(); + Resource parent = (depth > 1) ? rawResourceLineage.get(depth - 2) : null; + + // record which of the raw ancestry is locked from view + List<ResourceLineageComposite> resourceLineage = new ArrayList<ResourceLineageComposite>(rawResourceLineage + .size()); + for (Resource resource : rawResourceLineage) { + resourceLineage.add(new ResourceLineageComposite(resource, !authorizationManager.canViewResource(subject, + resource.getId()))); + } + + // fill out the tree, including only the direct ancestors and all viewable relations + List<ResourceLineageComposite> result = new LinkedList<ResourceLineageComposite>(); + + for (ResourceLineageComposite ancestor : resourceLineage) { + // always include a direct ancestor + result.add(ancestor); + + // if the ancestor is not locked, include relevant children. Also, always show viewable + // siblings of the target resource. + if (!ancestor.isLocked() || ancestor.getResource() == parent) { + + // get children + Set<Resource> children = ancestor.getResource().getChildResources(); + // only add the viewable children + List<Resource> viewableChildren = new ArrayList<Resource>(children.size()); + for (Resource child : children) { + boolean isCommitted = (child.getInventoryStatus() == InventoryStatus.COMMITTED); + boolean isViewable = (isInventoryManager || authorizationManager.canViewResource(subject, child + .getId())); + if (isCommitted && isViewable) { + // if not a direct ancestor add to the list (direct ancestors already added by default) + if (!rawResourceLineage.contains(child)) { + child.getParentResource().getId(); + result.add(new ResourceLineageComposite(child, false)); + } + viewableChildren.add(child); + } + } + + // get grandchildren + for (Resource child : viewableChildren) { // This ensures Hibernate actually fetches the parent Resource. - grandchildResource.getParentResource().getId(); + child.getParentResource().getId(); + Set<Resource> grandChildren = child.getChildResources(); + for (Resource grandChild : grandChildren) { + boolean isCommitted = (grandChild.getInventoryStatus() == InventoryStatus.COMMITTED); + boolean isViewable = (isInventoryManager || authorizationManager.canViewResource(subject, + grandChild.getId())); + if (isCommitted && isViewable) { + // if not a direct ancestor add to the list (direct ancestors already added by default) + if (!rawResourceLineage.contains(grandChild)) { + grandChild.getParentResource().getId(); + result.add(new ResourceLineageComposite(grandChild, false)); + } + } + } } } } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java index 78ece78..6f2ae41 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java @@ -43,6 +43,7 @@ import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.resource.composite.ResourceHealthComposite; import org.rhq.core.domain.resource.composite.ResourceIdFlyWeight; import org.rhq.core.domain.resource.composite.ResourceInstallCount; +import org.rhq.core.domain.resource.composite.ResourceLineageComposite; import org.rhq.core.domain.resource.composite.ResourceWithAvailability; import org.rhq.core.domain.resource.flyweight.ResourceFlyweight; import org.rhq.core.domain.resource.group.ResourceGroup; @@ -156,11 +157,13 @@ public interface ResourceManagerLocal {
/** * Returns the lineage of a resource plus all the siblings of the resources in the lineage. This is - * useful for prepopulating all the resources visible in an expanded tree. + * useful for prepopulating all the resources visible in an expanded tree. Composites are returned + * that indicate whether the resource is viewable or should be locked in the tree. + * * @param resourceId id of resource - * @return resoure lineage and siblings + * @return resource lineage and siblings */ - List<Resource> getResourceLineageAndSiblings(int resourceId); + List<ResourceLineageComposite> getResourceLineageAndSiblings(Subject subject, int resourceId);
/** * Looks up the root of a subtree in the inventory. This will generally find the platform on which diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java index 0e7500f..f75d32d 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerBean.java @@ -146,6 +146,15 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso } }
+ public ResourceGroup createPrivateResourceGroup(Subject subject, // + @XmlJavaTypeAdapter(ResourceGroupAdapter.class) ResourceGroup group) { + + group.setSubject(subject); + group.setRecursive(false); + + return resourceGroupManager.createResourceGroup(subjectManager.getOverlord(), group); + } + @RequiredPermission(Permission.MANAGE_INVENTORY) public ResourceGroup createResourceGroup(Subject user, // @XmlJavaTypeAdapter(ResourceGroupAdapter.class) ResourceGroup group) { @@ -1017,8 +1026,9 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso */ public PageList<ResourceGroupComposite> findResourceGroupCompositesByCriteria(Subject subject, ResourceGroupCriteria criteria) { - CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ; + + CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria); + String replacementSelectList = "" + " new org.rhq.core.domain.resource.group.composite.ResourceGroupComposite( " + " ( SELECT COUNT(avail) FROM resourcegroup.explicitResources res JOIN res.currentAvailability avail ) AS explicitCount," @@ -1028,17 +1038,6 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso + " resourcegroup ) "; generator.alterProjection(replacementSelectList);
- if (criteria.isSecurityManagerRequired() - && !authorizationManager.hasGlobalPermission(subject, Permission.MANAGE_SECURITY)) { - throw new PermissionException("Subject [" + subject.getName() - + "] requires SecurityManager permission for requested query criteria."); - } - - if (authorizationManager.isInventoryManager(subject) == false) { - generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.GROUP, null, - subject.getId()); - } - CriteriaQueryRunner<ResourceGroupComposite> queryRunner = new CriteriaQueryRunner<ResourceGroupComposite>( criteria, generator, entityManager); PageList<ResourceGroupComposite> results = queryRunner.execute(); @@ -1299,18 +1298,35 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso public void setAssignedResources(Subject subject, int groupId, int[] resourceIds, boolean setType) throws ResourceGroupDeleteException {
+ ResourceGroup group = entityManager.find(ResourceGroup.class, groupId); + if (group.isPrivateGroup()) { + List<Integer> ids = new ArrayList<Integer>(resourceIds.length); + for (int id : resourceIds) { + ids.add(id); + } + if (!authorizationManager.canViewResources(subject, ids)) { + throw new PermissionException("Subject [" + subject.getName() + + "] does not have VIEW permission for all specified resources."); + } + } else { + if (!authorizationManager.isInventoryManager(subject)) { + throw new PermissionException("Subject [" + subject.getName() + + "] is not authorized for [ MANAGE_INVENTORY ]. Required for changing group membership "); + } + } + List<Integer> currentMembers = resourceManager.findExplicitResourceIdsByResourceGroup(groupId);
List<Integer> newMembers = ArrayUtils.wrapInList(resourceIds); // members needing addition newMembers.removeAll(currentMembers); if (newMembers.size() > 0) { - addResourcesToGroup(subject, groupId, ArrayUtils.unwrapCollection(newMembers)); + addResourcesToGroup(subjectManager.getOverlord(), groupId, ArrayUtils.unwrapCollection(newMembers)); }
List<Integer> extraMembers = new ArrayList<Integer>(currentMembers); // members needing removal extraMembers.removeAll(ArrayUtils.wrapInList(resourceIds)); if (extraMembers.size() > 0) { - removeResourcesFromGroup(subject, groupId, ArrayUtils.unwrapCollection(extraMembers)); + removeResourcesFromGroup(subjectManager.getOverlord(), groupId, ArrayUtils.unwrapCollection(extraMembers)); }
// As a result of the membership change ensure that the group type is set correctly. @@ -1461,28 +1477,45 @@ public class ResourceGroupManagerBean implements ResourceGroupManagerLocal, Reso
@SuppressWarnings("unchecked") public PageList<ResourceGroup> findResourceGroupsByCriteria(Subject subject, ResourceGroupCriteria criteria) { - CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); - ;
+ CriteriaQueryGenerator generator = getCriteriaQueryGenerator(subject, criteria); + + CriteriaQueryRunner<ResourceGroup> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); + PageList<ResourceGroup> result = queryRunner.execute(); + return result; + } + + private CriteriaQueryGenerator getCriteriaQueryGenerator(Subject subject, ResourceGroupCriteria criteria) { if (criteria.isSecurityManagerRequired() && !authorizationManager.hasGlobalPermission(subject, Permission.MANAGE_SECURITY)) { throw new PermissionException("Subject [" + subject.getName() + "] requires SecurityManager permission for requested query criteria."); }
- if (criteria.isInventoryManagerRequired() - && !authorizationManager.hasGlobalPermission(subject, Permission.MANAGE_INVENTORY)) { + boolean isInventoryManager = authorizationManager.isInventoryManager(subject); + boolean groupAuthzRequired = (!(criteria.isFilterPrivate() || isInventoryManager)); + + if (criteria.isInventoryManagerRequired() && !isInventoryManager) { throw new PermissionException("Subject [" + subject.getName() + "] requires InventoryManager permission for requested query criteria."); }
- if (authorizationManager.isInventoryManager(subject) == false) { + // if we're searching for private groups set the subject filter to the current user's subjectId + // setting it here prevents the caller from spoofing a different user. This is why the subject and + // private filters are different. The suject filter can specifiy any use and therefore requires + // inventory manager. + if (criteria.isFilterPrivate()) { + criteria.addFilterPrivate(null); + criteria.addFilterSubjectId(subject.getId()); + } + + CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria); + if (groupAuthzRequired) { generator.setAuthorizationResourceFragment(CriteriaQueryGenerator.AuthorizationTokenType.GROUP, null, subject.getId()); }
- CriteriaQueryRunner<ResourceGroup> queryRunner = new CriteriaQueryRunner(criteria, generator, entityManager); - return queryRunner.execute(); + return generator; }
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java index de96dbf..a0481b1 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/ResourceGroupManagerLocal.java @@ -42,6 +42,28 @@ import org.rhq.core.domain.util.PageList; @Local public interface ResourceGroupManagerLocal {
+ /** + * NOTE: This is only used to support AutoGroups currently but the idea may be expanded in the future. + * + * Creates a private, "user-owned" (aka "subject-owned") resource group. This group differs from a role-owned + * group in that it can not be assigned to a role, instead it is owned by the user that creates it. It comprises + * only a set of resources for which the user has, minimally, view permission. Since a user's view permissions + * can change, membership and authz checking must be performed as needed when taking any action on the group. + * <br/><br/> + * A user does not need MANAGE_INVENTORY to create a sub-group because it is private to his view. + * <br/><br/> + * This call does not populate the group with members, it only creates the group. The group is automatically set + * to be non-recursive. + * <br/><br/> + * All user-owned groups are deleted if the the user is deleted. + * + * @param user The user for which the group will be created. + * @param group The group characteristics. Any membership defined here is ignored. The recursivity setting is + * ignored. + * @return The new group. + */ + ResourceGroup createPrivateResourceGroup(Subject user, ResourceGroup group); + ResourceGroup getResourceGroupById(Subject user, int id, GroupCategory category) throws ResourceGroupNotFoundException;
@@ -108,7 +130,10 @@ public interface ResourceGroupManagerLocal { /** * This method ensures that the explicit group membership is set to the specified resources. Members * will be added or removed as necessary. Make sure you pass the correct value for the <setType> - * parameter. + * parameter. + * <br/><br/> + * For global groups requires MANAGE_INVENTORY. For private groups requires VIEW permission on all specified + * resources. * * @param subject * @param groupId
commit e6dd8c2618a009053b06c3f63fff808fc5e64dbf Merge: 14fd25e... 3c5a00e... Author: Lukas Krejci lkrejci@redhat.com Date: Fri Oct 1 12:58:36 2010 +0200
Merge branch 'master' into resource-upgrade
commit 14fd25e86c1a4013c1047c343f3860720a3f9c68 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Oct 1 12:55:37 2010 +0200
Adapted the resource upgrade test infrastructure to work with the new requirements of the failure handling tests and added the first round of the failure handling tests.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java index adb3989..39597ee 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -59,68 +59,69 @@ public class FakeServerInventory { private Map<String, Resource> resourceStore = new HashMap<String, Resource>(); private int counter; private boolean failing; - + private static final Comparator<Resource> ID_COMPARATOR = new Comparator<Resource>() { public int compare(Resource o1, Resource o2) { return o1.getId() - o2.getId(); } }; - + private static final Comparator<Resource> RESOURCE_TYPE_COMPARATOR = new Comparator<Resource>() { public int compare(Resource o1, Resource o2) { return o1.getResourceType().equals(o2.getResourceType()) ? 0 : o1.getId() - o2.getId(); } }; - + public FakeServerInventory() { this(false); } - + public FakeServerInventory(boolean failing) { this.failing = failing; } - + //need to synchronize, because resource upgrade is async and can overlap with //resource discovery. public synchronized CustomAction mergeInventoryReport(final InventoryStatus requiredInventoryStatus) { return new CustomAction("updateServerSideInventory") { public Object invoke(Invocation invocation) throws Throwable { throwIfFailing(); - + InventoryReport inventoryReport = (InventoryReport) invocation.getParameter(0); - - for(Resource res : inventoryReport.getAddedRoots()) { + + for (Resource res : inventoryReport.getAddedRoots()) { + Resource persisted = fakePersist(res, requiredInventoryStatus, new HashSet<String>()); + if (res.getParentResource() == Resource.ROOT) { - platform = fakePersist(res, requiredInventoryStatus, new HashSet<String>()); - break; + platform = persisted; } } return getSyncInfo(); - } + } }; } - + public synchronized CustomAction clearPlatform() { return new CustomAction("updateServerSideInventory - report platform deleted on the server") { public Object invoke(Invocation invocation) throws Throwable { throwIfFailing(); - + platform = null; - + return getSyncInfo(); } }; } - + public synchronized CustomAction upgradeResources() { return new CustomAction("upgradeServerSideInventory") { - @SuppressWarnings({"serial", "unchecked"}) + @SuppressWarnings({ "serial", "unchecked" }) public Object invoke(Invocation invocation) throws Throwable { throwIfFailing(); - + Set<ResourceUpgradeRequest> requests = (Set<ResourceUpgradeRequest>) invocation.getParameter(0); Set<ResourceUpgradeResponse> responses = new HashSet<ResourceUpgradeResponse>(); - + for (final ResourceUpgradeRequest request : requests) { Resource resource = findResource(platform, new Resource() { public int getId() { @@ -134,16 +135,18 @@ public class FakeServerInventory { if (request.getNewName() != null) { resource.setName(request.getNewName()); } - + if (request.getNewResourceKey() != null) { resource.setResourceKey(request.getNewResourceKey()); } - + if (request.getUpgradeErrorMessage() != null) { - ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, request.getUpgradeErrorMessage(), request.getUpgradeErrorStackTrace(), request.getTimestamp()); + ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, + request.getUpgradeErrorMessage(), request.getUpgradeErrorStackTrace(), + request.getTimestamp()); resource.getResourceErrors().add(error); } - + ResourceUpgradeResponse resp = new ResourceUpgradeResponse(); resp.setResourceId(resource.getId()); resp.setUpgradedResourceName(resource.getName()); @@ -156,21 +159,21 @@ public class FakeServerInventory { } }; } - + public synchronized CustomAction getResources() { return new CustomAction("getResources") { @SuppressWarnings("unchecked") public Object invoke(Invocation invocation) throws Throwable { throwIfFailing(); - - Set<Integer> resourceIds = (Set<Integer>)invocation.getParameter(0); + + Set<Integer> resourceIds = (Set<Integer>) invocation.getParameter(0); boolean includeDescendants = (Boolean) invocation.getParameter(1); - + return getResources(resourceIds, includeDescendants); } - }; + }; } - + public boolean isFailing() { return failing; } @@ -191,12 +194,12 @@ public class FakeServerInventory { } return result; } - + @SuppressWarnings("serial") - private Set<Resource> getResources(Set<Integer> resourceIds, boolean includeDescendants) { + private Set<Resource> getResources(Set<Integer> resourceIds, boolean includeDescendants) { Set<Resource> result = new HashSet<Resource>(); - - for(final Integer id : resourceIds) { + + for (final Integer id : resourceIds) { Resource r = findResource(platform, new Resource() { public int getId() { return id; @@ -204,19 +207,20 @@ public class FakeServerInventory { }, ID_COMPARATOR); if (r != null) { result.add(r); - + if (includeDescendants) { - for(Resource child : r.getChildResources()) { + for (Resource child : r.getChildResources()) { result.addAll(getResources(Collections.singleton(child.getId()), true)); } } } } - + return result; } - - private Resource fakePersist(Resource agentSideResource, InventoryStatus requiredInventoryStatus, Set<String> inProgressUUIds) { + + private Resource fakePersist(Resource agentSideResource, InventoryStatus requiredInventoryStatus, + Set<String> inProgressUUIds) { Resource persisted = resourceStore.get(agentSideResource.getUuid()); if (!inProgressUUIds.add(agentSideResource.getUuid())) { return persisted; @@ -237,94 +241,114 @@ public class FakeServerInventory { persisted.setInventoryStatus(requiredInventoryStatus); persisted.setResourceKey(agentSideResource.getResourceKey()); persisted.setResourceType(agentSideResource.getResourceType()); - + Resource parent = agentSideResource.getParentResource(); if (parent != null && parent != Resource.ROOT) { - persisted.setParentResource(fakePersist(agentSideResource.getParentResource(), requiredInventoryStatus, inProgressUUIds)); + persisted.setParentResource(fakePersist(agentSideResource.getParentResource(), requiredInventoryStatus, + inProgressUUIds)); } else { persisted.setParentResource(parent); }
Set<Resource> childResources = new HashSet<Resource>(); persisted.setChildResources(childResources); - for(Resource child : agentSideResource.getChildResources()) { + for (Resource child : agentSideResource.getChildResources()) { childResources.add(fakePersist(child, requiredInventoryStatus, inProgressUUIds)); } - + inProgressUUIds.remove(agentSideResource.getUuid()); - + return persisted; } - + private ResourceSyncInfo getSyncInfo() { return platform != null ? convert(platform) : null; } - + private void throwIfFailing() { if (failing) { throw new RuntimeException("Fake server inventory is in the failing mode."); } } - + private static ResourceSyncInfo convert(Resource root) { + return convertInternal(root, new HashMap<String, ResourceSyncInfo>()); + } + + private static ResourceSyncInfo convertInternal(Resource root, Map<String, ResourceSyncInfo> intermediateResults) { + ResourceSyncInfo ret = intermediateResults.get(root.getUuid()); + + if (ret != null) { + return ret; + } + try { - ResourceSyncInfo ret = new ResourceSyncInfo(); - + ret = new ResourceSyncInfo(); + + intermediateResults.put(root.getUuid(), ret); + Class<ResourceSyncInfo> clazz = ResourceSyncInfo.class;
getPrivateField(clazz, "id").set(ret, root.getId()); getPrivateField(clazz, "uuid").set(ret, root.getUuid()); getPrivateField(clazz, "mtime").set(ret, root.getMtime()); getPrivateField(clazz, "inventoryStatus").set(ret, root.getInventoryStatus()); - getPrivateField(clazz, "parent").set(ret, null); - + + ResourceSyncInfo parent = root.getParentResource() == null ? null : convertInternal( + root.getParentResource(), intermediateResults); + + getPrivateField(clazz, "parent").set(ret, parent); + Set<ResourceSyncInfo> children = new LinkedHashSet<ResourceSyncInfo>(); - for(Resource child : root.getChildResources()) { - ResourceSyncInfo syncChild = convert(child); - getPrivateField(clazz, "parent").set(syncChild, ret); - - children.add(convert(child)); - } + for (Resource child : root.getChildResources()) { + ResourceSyncInfo syncChild = convertInternal(child, intermediateResults); + + children.add(syncChild); + } getPrivateField(clazz, "childSyncInfos").set(ret, children); - + return ret; } catch (Exception e) { fail("Failed to convert resource " + root + " to a ResourceSyncInfo. This should not happen.", e); return null; } - } - + } + private static Field getPrivateField(Class<?> clazz, String fieldName) throws NoSuchFieldException { Field field = clazz.getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } - + return field; } - + private static Resource findResource(Resource root, Resource template, Comparator<Resource> comparator) { - if (root == null) return null; + if (root == null) + return null; if (comparator.compare(root, template) == 0) { return root; } else { - for(Resource child : root.getChildResources()) { + for (Resource child : root.getChildResources()) { Resource found = findResource(child, template, comparator); - if (found != null) return found; + if (found != null) + return found; } } - + return null; - } - - private static void findResources(Resource root, Resource template, Set<Resource> result, Comparator<Resource> comparator) { - if (root == null) return; + } + + private static void findResources(Resource root, Resource template, Set<Resource> result, + Comparator<Resource> comparator) { + if (root == null) + return; if (comparator.compare(root, template) == 0) { result.add(root); } else { - for(Resource child : root.getChildResources()) { + for (Resource child : root.getChildResources()) { findResources(child, template, result, comparator); } - } + } } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java index 25eca30..5949b76 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java @@ -19,11 +19,29 @@
package org.rhq.core.pc.upgrade;
+import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + import java.util.Arrays; import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set;
+import org.jmock.Expectations; +import org.jmock.Mockery; import org.testng.annotations.Test;
+import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; +import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.resource.InventoryStatus; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + /** * The plugins and their resource types form the following dependency structure: * <pre> @@ -35,6 +53,10 @@ import org.testng.annotations.Test; * </pre> * The dependencies in the above "chart" are formed using either the <code><runs-inside></code> * or <code>sourcePlugin/sourceType</code> approaches just to test that both are handled correctly. + * <p> + * The <code>parentdep</code>, <code>parentsibling</code>, <code>test</code> and <code>sibling</code> plugins are present + * in two versions and support the {@link ResourceUpgradeFacet}, while the rest of the plugins is + * present only in single version. * * @author Lukas Krejci */ @@ -53,29 +75,149 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase private static final String TEST_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-1.0.0.jar"; private static final String TEST_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-2.0.0.jar";
+ private static final String UPGRADED_RESOURCE_KEY_PREFIX = "UPGRADED"; + + private static final HashMap<String, List<String>> DEPS; + + static { + DEPS = new HashMap<String, List<String>>(); + + DEPS.put(BASE_PLUGIN_NAME, Collections.<String> emptyList()); + DEPS.put(PARENT_DEP_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME)); + DEPS.put(PARENT_DEP_V2_PLUGIN_NAME, DEPS.get(PARENT_DEP_V1_PLUGIN_NAME)); + DEPS.put(PARENT_SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME)); + DEPS.put(PARENT_SIBLING_V2_PLUGIN_NAME, DEPS.get(PARENT_SIBLING_V1_PLUGIN_NAME)); + DEPS.put(ROOT_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME)); + DEPS.put(SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME)); + DEPS.put(SIBLING_V2_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME)); + DEPS.put(TEST_V1_PLUGIN_NAME, + Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME)); + DEPS.put(TEST_V2_PLUGIN_NAME, + Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME)); + } + + private static final ResType TEST_TYPE = new ResType("TestResource", "test"); + private static final ResType SIBLING_TYPE = new ResType("TestResourceSibling", "test"); + private static final ResType PARENT_TYPE = new ResType("TestResourceParent", "test"); + private static final ResType PARENT_DEP_TYPE = new ResType("ParentDependency", "parentdep"); + private static final ResType PARENT_SIBLING_TYPE = new ResType("ParentDepSibling", "parentsibling"); + private static final ResType ROOT_TYPE = new ResType("Root", "root"); + protected Collection<String> getRequiredPlugins() { return Arrays.asList(BASE_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, ROOT_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME, TEST_V1_PLUGIN_NAME, TEST_V2_PLUGIN_NAME); } - + @Test - public void testSuccess() { - //TODO implement - //check that all the stuff is properly upgraded on success + public void testSuccess() throws Exception { + setCurrentServerSideInventory(new FakeServerInventory()); + + //let it all run in v1 + executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME), + new AbstractTestPayload(true, Collections.<ResType> emptyList()) { + public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) { + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); + + //now let's run with v2 plugins and check the layout of the inventory + executeTestWithPlugins( + getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME), + new AbstractTestPayload(false, Arrays.asList(TEST_TYPE, SIBLING_TYPE, PARENT_TYPE, PARENT_DEP_TYPE, + PARENT_SIBLING_TYPE, ROOT_TYPE)) { + + public void test(Map<ResType, Set<Resource>> resources) { + checkPresenceOfResourceTypes(resources, getExpectedResourceTypes()); + + checkNumberOfResources(resources, ROOT_TYPE, 1); + checkNumberOfResources(resources, PARENT_DEP_TYPE, 1); + checkNumberOfResources(resources, PARENT_SIBLING_TYPE, 1); + checkNumberOfResources(resources, PARENT_TYPE, 2); + checkNumberOfResources(resources, SIBLING_TYPE, 30); + checkNumberOfResources(resources, TEST_TYPE, 30); + + //check that the resources are upgraded + checkResourcesUpgraded(resources.get(PARENT_SIBLING_TYPE)); + checkResourcesUpgraded(resources.get(PARENT_TYPE)); + checkResourcesUpgraded(resources.get(SIBLING_TYPE)); + checkResourcesUpgraded(resources.get(TEST_TYPE)); + } + + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + } + }; + } + }); } - + @Test public void testFailureOnLeaf() { //TODO implement //check that the system behaves correctly if there is an upgrade failure //at the leaf node of the plugin dep graph } - + @Test public void testFailureOnDependencies() { //TODO implement //check that stuff works if there is an upgrade failure on some of the resources //in the plugin some "in the middle" of the plugin dep graph } + + @SuppressWarnings("unchecked") + @Override + protected void defineDefaultExpectations(Expectations expectations) { + super.defineDefaultExpectations(expectations); + try { + expectations.allowing(getCurrentDiscoveryServerService()) + .mergeInventoryReport(expectations.with(Expectations.any(InventoryReport.class))); + expectations.will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); + + expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources(expectations.with(Expectations.any(Set.class))); + expectations.will(getCurrentServerSideInventory().upgradeResources()); + + expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources( + expectations.with(Expectations.any(Set.class))); + + } catch (InvalidInventoryReportException e) { + //this is not going to happen because we're mocking the invocation + } + } + + private Set<String> getAllDepsFor(String... plugins) { + HashSet<String> deps = new HashSet<String>(); + for (String plugin : plugins) { + deps.add(plugin); + deps.addAll(DEPS.get(plugin)); + } + + return deps; + } + + private static void checkPresenceOfResourceTypes(Map<ResType, Set<Resource>> resources, Set<ResType> expectedTypes) { + for (ResType resType : expectedTypes) { + assertNotNull(resources.get(resType), "Expecting some resources of type " + resType); + } + } + + private static void checkNumberOfResources(Map<ResType, Set<Resource>> resources, ResType type, int count) { + assertEquals(resources.get(type).size(), count, "Unexpected number of " + type + " discovered."); + } + + private static void checkResourcesUpgraded(Set<Resource> resources) { + for(Resource res : resources) { + assertTrue(res.getResourceKey().startsWith(UPGRADED_RESOURCE_KEY_PREFIX), "Resource " + res + " doesn't seem to be upgraded even though it should."); + } + } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 8cfec36..d47d00c 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -31,6 +31,8 @@ import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.List; +import java.util.Map; import java.util.Set;
import org.jmock.Expectations; @@ -54,8 +56,13 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { private static final String PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-2.0.0.jar"; private static final String FAILING_PLUGIN_FILE_NAME = "/resource-upgrade-test-plugin-3.0.0.jar";
- static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; - static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest"; + private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; + private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest"; + private static final ResType SINGLETON_TYPE = new ResType(SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME); + + private static List<ResType> getMyExpectedTypes() { + return Arrays.asList(SINGLETON_TYPE); + }
protected Collection<String> getRequiredPlugins() { return Arrays.asList(PLUGIN_V1_FILENAME, PLUGIN_V2_FILENAME, FAILING_PLUGIN_FILE_NAME); @@ -66,11 +73,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.NEW);
- TestPayload testNoChange = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> discoveredResources) { + TestPayload testNoChange = new AbstractTestPayload(false, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> discoveredResources) { assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = discoveredResources.iterator().next(); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); @@ -111,11 +118,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
getCurrentServerSideInventory().setFailing(true);
- TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> discoveredResources) { + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> discoveredResources) { assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = discoveredResources.iterator().next(); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); @@ -145,11 +152,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> discoveredResources) { + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> discoveredResources) { assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = discoveredResources.iterator().next(); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); @@ -193,11 +200,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> resourceUpgradeTestResources) { + TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) { assertEquals(resourceUpgradeTestResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = resourceUpgradeTestResources.iterator().next(); + Resource discoveredResource = resourceUpgradeTestResources.get(SINGLETON_TYPE).iterator().next();
assertTrue(discoveredResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side.");
@@ -231,11 +238,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { cleanDataDir(); - executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> discoveredResources) { + executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> discoveredResources) { assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = discoveredResources.iterator().next(); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); @@ -260,11 +267,11 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { private void upgradeTest(boolean clearInventoryDat) throws Exception { initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { - public void test(Set<Resource> discoveredResources) { + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat, getMyExpectedTypes()) { + public void test(Map<ResType, Set<Resource>> discoveredResources) { assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
- Resource discoveredResource = discoveredResources.iterator().next(); + Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java index 3aa772b..0aefafd 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java @@ -25,6 +25,9 @@ import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; import java.util.Set;
import org.apache.commons.io.FileUtils; @@ -73,6 +76,78 @@ public abstract class ResourceUpgradeTestBase { private ResourceFactoryServerService currentResourceFactoryServerService; private FakeServerInventory currentServerSideInventory;
+ protected static class ResType { + private String resourceTypeName; + private String resourceTypePluginName; + + public ResType(String resourceTypeName, String resourceTypePluginName) { + super(); + this.resourceTypeName = resourceTypeName; + this.resourceTypePluginName = resourceTypePluginName; + } + + public String getResourceTypeName() { + return resourceTypeName; + } + + public String getResourceTypePluginName() { + return resourceTypePluginName; + } + + @Override + public int hashCode() { + return resourceTypeName.hashCode() * resourceTypePluginName.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + + if (!(other instanceof ResType)) { + return false; + } + + ResType o = (ResType)other; + + return resourceTypeName.equals(o.getResourceTypeName()) && resourceTypePluginName.equals(o.getResourceTypePluginName()); + } + + @Override + public String toString() { + return "ResType[name='" + resourceTypeName + "', plugin='" + resourceTypePluginName + "']"; + } + } + + protected interface TestPayload { + Expectations getExpectations(Mockery context) throws Exception; + + void test(Map<ResType,Set<Resource>> resourceUpgradeTestResources); + + boolean isClearInventoryDat(); + + Set<ResType> getExpectedResourceTypes(); + } + + protected static abstract class AbstractTestPayload implements TestPayload { + private boolean clearInventoryDat; + private Set<ResType> resourceTypes; + + public AbstractTestPayload(boolean clearInventoryDat, Collection<ResType> resourceTypes) { + this.clearInventoryDat = clearInventoryDat; + this.resourceTypes = new HashSet<ResType>(resourceTypes); + } + + public boolean isClearInventoryDat() { + return clearInventoryDat; + } + + public Set<ResType> getExpectedResourceTypes() { + return resourceTypes; + } + } + @BeforeClass public void init() { tmpDir = getTmpDirectory(); @@ -81,21 +156,21 @@ public abstract class ResourceUpgradeTestBase { dataDir = new File(tmpDir, DATA_DIR_NAME); assertTrue(dataDir.mkdir(), "Could not create plugin container data directory."); } - + @BeforeClass public void verifyPluginsExist() { for (String plugin : getRequiredPlugins()) { verifyPluginExists(plugin); } } - + @AfterClass public void undeployPlugins() throws IOException { FileUtils.deleteDirectory(tmpDir); } - + protected abstract Collection<String> getRequiredPlugins(); - + protected void setCurrentServerSideInventory(FakeServerInventory currentServerSideInventory) { this.currentServerSideInventory = currentServerSideInventory; } @@ -103,8 +178,9 @@ public abstract class ResourceUpgradeTestBase { protected FakeServerInventory getCurrentServerSideInventory() { return currentServerSideInventory; } - - protected void setCurrentResourceFactoryServerService(ResourceFactoryServerService currentResourceFactoryServerService) { + + protected void setCurrentResourceFactoryServerService( + ResourceFactoryServerService currentResourceFactoryServerService) { this.currentResourceFactoryServerService = currentResourceFactoryServerService; }
@@ -178,24 +254,24 @@ public abstract class ResourceUpgradeTestBase {
protected static File getTmpDirectory() { File ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); - + while (ret.exists() || !ret.mkdir()) { ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); } - + return ret; }
private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception { PluginContainerConfiguration conf = new PluginContainerConfiguration(); - + conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME)); conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME)); conf.setInsideAgent(true); //pc must think it's inside an agent so that it persists the inventory between restarts conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory())); - conf.setCreateResourceClassloaders(false); - + conf.setCreateResourceClassloaders(false); + //we're not interested in any scans happening out of our control conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE); conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE); @@ -204,7 +280,7 @@ public abstract class ResourceUpgradeTestBase { conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE); conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE); conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE); - + setCurrentBundleServerService(context.mock(BundleServerService.class)); setCurrentConfigurationServerService(context.mock(ConfigurationServerService.class)); setCurrentContentServerService(context.mock(ContentServerService.class)); @@ -214,7 +290,7 @@ public abstract class ResourceUpgradeTestBase { setCurrentMeasurementServerService(context.mock(MeasurementServerService.class)); setCurrentOperationServerService(context.mock(OperationServerService.class)); setCurrentResourceFactoryServerService(context.mock(ResourceFactoryServerService.class)); - + ServerServices serverServices = new ServerServices(); serverServices.setBundleServerService(getCurrentBundleServerService()); serverServices.setConfigurationServerService(getCurrentConfigurationServerService()); @@ -225,9 +301,9 @@ public abstract class ResourceUpgradeTestBase { serverServices.setMeasurementServerService(getCurrentMeasurementServerService()); serverServices.setOperationServerService(getCurrentOperationServerService()); serverServices.setResourceFactoryServerService(getCurrentResourceFactoryServerService()); - + conf.setServerServices(serverServices); - + return conf; }
@@ -236,104 +312,76 @@ public abstract class ResourceUpgradeTestBase { */ protected void verifyPluginExists(String pluginResourcePath) { URL url = getClass().getResource(pluginResourcePath); - + File pluginFile = FileUtils.toFile(url); - + assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar could not be found."); }
private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws IOException { URL pluginUrl = getClass().getResource(pluginResourcePath); - + File pluginFile = new File(pluginResourcePath); String pluginFileName = pluginFile.getName(); - - FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName)); - } - - protected interface TestPayload { - Expectations getExpectations(Mockery context) throws Exception; - void test(Set<Resource> resourceUpgradeTestResources); - boolean isClearInventoryDat(); - String getResourceTypeName(); - String getResourceTypePluginName(); - } - - protected static abstract class AbstractTestPayload implements TestPayload { - private boolean clearInventoryDat; - private String resourceTypeName; - private String resourceTypePluginName; - - public AbstractTestPayload(boolean clearInventoryDat, String resourceTypeName, String resourceTypePluginName) { - this.clearInventoryDat = clearInventoryDat; - this.resourceTypeName = resourceTypeName; - this.resourceTypePluginName = resourceTypePluginName; - } - - public boolean isClearInventoryDat() { - return clearInventoryDat; - } - - public String getResourceTypeName() { - return resourceTypeName; - } - - public String getResourceTypePluginName() { - return resourceTypePluginName; - } - }
- /** - * - */ - public ResourceUpgradeTestBase() { - super(); + FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName)); }
private Set<Resource> getTestingResources(String resourceTypeName, String resourceTypePluginName) { - ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType(resourceTypeName, resourceTypePluginName); - + ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager() + .getType(resourceTypeName, resourceTypePluginName); + return getCurrentServerSideInventory().findResourcesByType(resType); }
protected void executeTestWithPlugins(Set<String> pluginResourcePaths, TestPayload test) throws Exception { FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); - - for(String pluginResourcePath : pluginResourcePaths) { + + for (String pluginResourcePath : pluginResourcePaths) { copyPlugin(pluginResourcePath, pluginDir); } - + Mockery context = new Mockery(); - + PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context); - + if (test.isClearInventoryDat()) { File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); inventoryDat.delete(); } - + context.checking(test.getExpectations(context)); - + PluginContainer.getInstance().setConfiguration(pcConfig); PluginContainer.getInstance().initialize(); - + try { //give the pc the time to finish resource upgrade Thread.sleep(1000); - + //execute full discovery InventoryManager im = PluginContainer.getInstance().getInventoryManager(); im.executeServerScanImmediately(); - im.executeServiceScanImmediately(); - - Set<Resource> resources = getTestingResources(test.getResourceTypeName(), test.getResourceTypePluginName()); - + + //do the service scan a couple of times so that we can commit + //the resources deep in the type hierarchy + for(int i = 0; i < 10; ++i) { + im.executeServiceScanImmediately(); + } + + Map<ResType, Set<Resource>> resources = new HashMap<ResType, Set<Resource>>(); + + for(ResType type : test.getExpectedResourceTypes()) { + Set<Resource> rs = getTestingResources(type.getResourceTypeName(), type.getResourceTypePluginName()); + resources.put(type, rs); + } + test.test(resources); - + context.assertIsSatisfied(); } finally { - PluginContainer.getInstance().shutdown(); - } + PluginContainer.getInstance().shutdown(); + } }
@SuppressWarnings("unchecked") @@ -346,11 +394,13 @@ public abstract class ResourceUpgradeTestBase { expectations.ignoring(getCurrentMeasurementServerService()); expectations.ignoring(getCurrentOperationServerService()); expectations.ignoring(getCurrentResourceFactoryServerService()); - + //just ignore these invocations if we get a availability scan in the PC... - expectations.allowing(getCurrentDiscoveryServerService()).mergeAvailabilityReport(expectations.with(Expectations.any(AvailabilityReport.class))); - - expectations.allowing(getCurrentDiscoveryServerService()).getResources(expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); + expectations.allowing(getCurrentDiscoveryServerService()).mergeAvailabilityReport( + expectations.with(Expectations.any(AvailabilityReport.class))); + + expectations.allowing(getCurrentDiscoveryServerService()).getResources( + expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); expectations.will(getCurrentServerSideInventory().getResources()); }
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java index 61d4fe0..a03dff5 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java @@ -46,15 +46,25 @@ public class BaseDiscoveryComponent<T extends ResourceComponent> implements Reso String keyTemplate = pluginConfig.getSimpleValue("key", null); int count = pluginConfig.getSimple("count").getIntegerValue();
- int parentN = context.getParentResourceContext().getPluginConfiguration().getSimple("ordinal") - .getIntegerValue(); + int parentN = 0; + + if (context.getParentResourceContext() != null) { + PropertySimple parentOrdinalProperty = context.getParentResourceContext().getPluginConfiguration() + .getSimple("ordinal"); + + if (parentOrdinalProperty != null) { + parentN = parentOrdinalProperty.getIntegerValue(); + } + }
for (int i = 0; i < count; ++i) {
String key = getResourceKey(keyTemplate, i, parentN);
+ pluginConfig = context.getDefaultPluginConfiguration(); + pluginConfig.put(new PropertySimple("ordinal", i)); - + DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(), key, key, null, null, pluginConfig, null);
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java index beb36db..ec1cb20 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java @@ -28,34 +28,36 @@ import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; * * @author Lukas Krejci */ -public class BaseUpgradingDiscoveryComponent<T extends BaseResourceComponent> extends BaseDiscoveryComponent<T> implements ResourceUpgradeFacet<T> { +public class BaseUpgradingDiscoveryComponent<T extends BaseResourceComponent> extends BaseDiscoveryComponent<T> + implements ResourceUpgradeFacet<T> {
public ResourceUpgradeReport upgrade(ResourceUpgradeContext<T> inventoriedResource) { Configuration pluginConfig = inventoriedResource.getPluginConfiguration(); - + BaseResourceComponent<?> parent = inventoriedResource.getParentResourceComponent(); int ordinal = pluginConfig.getSimple("ordinal").getIntegerValue(); int parentOrdinal = parent == null ? 0 : parent.getOrdinal(); - + boolean fail = Boolean.getBoolean(pluginConfig.getSimpleValue("failUpgrade", "false")); - + if (!fail && parent != null) { fail = parent.getChildrenToFailUpgrade().contains(Integer.valueOf(ordinal)); } - + if (fail) { throw new RuntimeException("Failing the resource upgrade purposefully."); } - + String newKey = pluginConfig.getSimpleValue("upgradedKey", null); - + if (newKey == null) { return null; } - + ResourceUpgradeReport report = new ResourceUpgradeReport(); - + report.setNewResourceKey(getResourceKey(newKey, ordinal, parentOrdinal)); - return null; + + return report; } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml index f5e6920..608793c 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml @@ -22,8 +22,8 @@
<plugin-configuration> <c:simple-property name="count" default="1" /> - <c:simple-property name="key" default="test-resource-parent-sibling-%n,parent-%p" /> - <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + <c:simple-property name="key" default="test-resource-parent-dep-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-dep-sibling-%n,parent-%p" /> </plugin-configuration>
</server> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml index d138066..ddda11a 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml @@ -22,7 +22,7 @@
<plugin-configuration> <c:simple-property name="count" default="1" /> - <c:simple-property name="key" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + <c:simple-property name="key" default="UPGRADED-test-resource-parent-dep-sibling-%n,parent-%p" /> </plugin-configuration>
</server> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml index 44a1033..d3ea7b7 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml @@ -11,10 +11,18 @@
<depends plugin="base" useClasses="true"/>
- <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> - <service name="TestResourceSibling" - discovery="BaseDiscoveryComponent" - class="BaseResourceComponent" /> + <server name="Bogus" class="BaseDiscoveryComponent"> + <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> + <service name="TestResourceSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="10" /> + <c:simple-property name="key" default="test-resource-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + </service>
+ </server> </plugin>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml index aeab68f..f7f7a2c 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml @@ -10,10 +10,16 @@
<depends plugin="base" useClasses="true"/>
+ <server name="Bogus" class="BaseDiscoveryComponent"> <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> <service name="TestResourceSibling" discovery="BaseUpgradingDiscoveryComponent" - class="BaseResourceComponent" /> - + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="15" /> <!-- This intentionally differs from v1 --> + <c:simple-property name="key" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + </service> + </server> </plugin>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml index e934494..ebe9793 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml @@ -37,13 +37,8 @@ </plugin-configuration> </service>
- <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling"> - <plugin-configuration> - <c:simple-property name="count" default="10" /> - <c:simple-property name="key" default="test-resource-sibling-%n,parent-%p" /> - <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> - </plugin-configuration> - </service> + <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling" + class="BaseResourceComponent" discovery="BaseDiscoveryComponent" /> </server>
</plugin> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml index 96658e3..3d709b0 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml @@ -26,7 +26,7 @@ </plugin-configuration>
<service name="TestResource" - discovery="BaseDiscoveryComponent" + discovery="BaseUpgradingDiscoveryComponent" class="BaseResourceComponent"> <plugin-configuration> <c:simple-property name="count" default="15" /> <!-- This intentionally differs from v1 --> @@ -35,13 +35,8 @@
</service>
- <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling"> - <plugin-configuration> - <c:simple-property name="count" default="15" /> <!-- This intentionally differs from v1 --> - <c:simple-property name="key" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> - </plugin-configuration> - </service> - + <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling" + class="BaseResourceComponent" discovery="BaseUpgradingDiscoveryComponent" /> </server>
</plugin>
commit c99d68dd036f243a2f28e000e10385d27bbdb785 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 13:53:45 2010 +0200
Adding a skeleton of what will need to be tested for upgrade failure handling.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java new file mode 100644 index 0000000..25eca30 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java @@ -0,0 +1,81 @@ +/* + * 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.core.pc.upgrade; + +import java.util.Arrays; +import java.util.Collection; + +import org.testng.annotations.Test; + +/** + * The plugins and their resource types form the following dependency structure: + * <pre> + * Root(root) + * / \ + * ParentDependency(parentdep) ParentDepSibling(parentsibling) + * / \ + * TestResource(test) TestResourceSibling(sibling) + * </pre> + * The dependencies in the above "chart" are formed using either the <code><runs-inside></code> + * or <code>sourcePlugin/sourceType</code> approaches just to test that both are handled correctly. + * + * @author Lukas Krejci + */ +@Test(sequential = true, invocationCount = 1) +public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase { + + //plugin names + private static final String BASE_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-base-1.0.0.jar"; + private static final String PARENT_DEP_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar"; + private static final String PARENT_DEP_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar"; + private static final String PARENT_SIBLING_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar"; + private static final String PARENT_SIBLING_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar"; + private static final String ROOT_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-root-1.0.0.jar"; + private static final String SIBLING_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-sibling-1.0.0.jar"; + private static final String SIBLING_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-sibling-2.0.0.jar"; + private static final String TEST_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-1.0.0.jar"; + private static final String TEST_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-2.0.0.jar"; + + protected Collection<String> getRequiredPlugins() { + return Arrays.asList(BASE_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, + PARENT_SIBLING_V1_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, ROOT_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME, + SIBLING_V2_PLUGIN_NAME, TEST_V1_PLUGIN_NAME, TEST_V2_PLUGIN_NAME); + } + + @Test + public void testSuccess() { + //TODO implement + //check that all the stuff is properly upgraded on success + } + + @Test + public void testFailureOnLeaf() { + //TODO implement + //check that the system behaves correctly if there is an upgrade failure + //at the leaf node of the plugin dep graph + } + + @Test + public void testFailureOnDependencies() { + //TODO implement + //check that stuff works if there is an upgrade failure on some of the resources + //in the plugin some "in the middle" of the plugin dep graph + } +}
commit 4f504f582fc9040bcf5ed7f7dd24cfd3bc2adbad Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 13:49:24 2010 +0200
some more minor changes to class structure and plugin names.
diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index 035bf36..4d6e753 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -281,7 +281,7 @@ <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v1/org/rhq/core/pc/upgrade/plugins/multi/v1"> <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v1/*.class" /> </copy> --> - <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-1.0.0.jar"> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-test-1.0.0.jar"> <fileset dir="${project.build.testOutputDirectory}/tmp/multi/v1" includes="**/*.class,**/rhq-plugin.xml" /> </jar>
@@ -291,7 +291,7 @@ <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v2/org/rhq/core/pc/upgrade/plugins/multi/v2"> <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v2/*.class" /> </copy> --> - <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-2.0.0.jar"> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-test-2.0.0.jar"> <fileset dir="${project.build.testOutputDirectory}/tmp/multi/v2" includes="**/*.class,**/rhq-plugin.xml" /> </jar>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index e13ea3d..8cfec36 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -28,6 +28,8 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
import java.io.File; +import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.Set;
@@ -38,7 +40,6 @@ import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.inventory.ResourceContainer; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
/** @@ -56,11 +57,8 @@ public class ResourceUpgradeTest extends ResourceUpgradeTestBase { static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest";
- @BeforeClass - public void sanityCheck() { - verifyPluginExists(PLUGIN_V1_FILENAME); - verifyPluginExists(PLUGIN_V2_FILENAME); - verifyPluginExists(FAILING_PLUGIN_FILE_NAME); + protected Collection<String> getRequiredPlugins() { + return Arrays.asList(PLUGIN_V1_FILENAME, PLUGIN_V2_FILENAME, FAILING_PLUGIN_FILE_NAME); }
@Test diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java index f03f2a4..3aa772b 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java @@ -24,6 +24,7 @@ import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; +import java.util.Collection; import java.util.Set;
import org.apache.commons.io.FileUtils; @@ -53,7 +54,7 @@ import org.testng.annotations.BeforeClass; * * @author Lukas Krejci */ -public class ResourceUpgradeTestBase { +public abstract class ResourceUpgradeTestBase {
private static final String PLUGINS_DIR_NAME = "plugins"; private static final String DATA_DIR_NAME = "data"; @@ -81,11 +82,20 @@ public class ResourceUpgradeTestBase { assertTrue(dataDir.mkdir(), "Could not create plugin container data directory."); }
+ @BeforeClass + public void verifyPluginsExist() { + for (String plugin : getRequiredPlugins()) { + verifyPluginExists(plugin); + } + } + @AfterClass public void undeployPlugins() throws IOException { FileUtils.deleteDirectory(tmpDir); }
+ protected abstract Collection<String> getRequiredPlugins(); + protected void setCurrentServerSideInventory(FakeServerInventory currentServerSideInventory) { this.currentServerSideInventory = currentServerSideInventory; }
commit b97e79bcbd5c557fba29030f7aa0f8b4c629c56f Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 13:48:28 2010 +0200
Simplify plugin names, declare correct discovery components for upgrade failure test plugins.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml index 7edfba1..d262c75 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<plugin name="ResourceUpgradeMultiTestBase" +<plugin name="base" displayName="" description="" package="org.rhq.core.pc.upgrade.plugins.multi.base" diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml index 3612974..8cadc84 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestParentDep" +<plugin name="parentdep" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,15 +9,15 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestRoot"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="root"/>
<server name="ParentDependency" discovery="BaseDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + <parent-resource-type name="Root" plugin="root"/> </runs-inside>
<plugin-configuration> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml index 6b95114..8169122 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestParentDep" +<plugin name="parentdep" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,15 +9,15 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestRoot"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="root"/>
<server name="ParentDependency" - discovery="BaseDiscoveryComponent" + discovery="BaseUpgradingDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + <parent-resource-type name="Root" plugin="root"/> </runs-inside>
<plugin-configuration> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml index fbade54..f5e6920 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestParentSibling" +<plugin name="parentsibling" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,15 +9,15 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestRoot"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="root"/>
<server name="ParentDepSibling" discovery="BaseDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + <parent-resource-type name="Root" plugin="root"/> </runs-inside>
<plugin-configuration> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml index f16d526..d138066 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestParentSibling" +<plugin name="parentsibling" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,15 +9,15 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestRoot"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="root"/>
<server name="ParentDepSibling" - discovery="BaseDiscoveryComponent" + discovery="BaseUpgradingDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + <parent-resource-type name="Root" plugin="root"/> </runs-inside>
<plugin-configuration> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml index b5efbb1..e95c9bd 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestRoot" +<plugin name="root" displayName="" description="" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,6 +9,8 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
+ <depends plugin="base" useClasses="true"/> + <server name="Root" discovery="BaseDiscoveryComponent" class="BaseResourceComponent"> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml index f87ef4d..44a1033 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTestSibling" +<plugin name="sibling" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,30 +9,12 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestParentDep"/> + <depends plugin="base" useClasses="true"/>
- <server name="TestResourceParentSibling" - discovery="BaseDiscoveryComponent" - class="BaseResourceComponent"> - - <plugin-configuration> - <c:simple-property name="count" default="2" /> - <c:simple-property name="key" default="test-resource-parent-sibling-%n,parent-%p" /> - <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> - </plugin-configuration> - - <service name="TestResourceSibling" + <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> + <service name="TestResourceSibling" discovery="BaseDiscoveryComponent" - class="BaseResourceComponent"> - <plugin-configuration> - <c:simple-property name="count" default="10" /> - <c:simple-property name="key" default="test-resource-sibling-%n,parent-%p" /> - <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> - </plugin-configuration> - - </service> - </server> + class="BaseResourceComponent" />
</plugin>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml index e6ab95f..aeab68f 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<plugin name="ResourceUpgradeMultiTestSibling" +<plugin name="sibling" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -8,34 +8,12 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestParentDep"/> + <depends plugin="base" useClasses="true"/>
- <server name="TestResourceParentSibling" - discovery="BaseUpgradingDiscoveryComponent" - class="BaseResourceComponent"> - - <runs-inside> - <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> - </runs-inside> - - <plugin-configuration> - <c:simple-property name="count" default="2" /> - <c:simple-property name="key" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> - </plugin-configuration> - - <service name="TestResourceSibling" - discovery="BaseDiscoveryComponent" - class="BaseResourceComponent"> - <plugin-configuration> - <c:simple-property name="count" default="15" /> - <c:simple-property name="key" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> - </plugin-configuration> - - </service> - - - </server> + <!-- This service is put in the type hierarchy in the v1/v2 test plugins --> + <service name="TestResourceSibling" + discovery="BaseUpgradingDiscoveryComponent" + class="BaseResourceComponent" />
</plugin>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml index 32ad438..e934494 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?>
-<plugin name="ResourceUpgradeMultiTest" +<plugin name="test" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -9,15 +9,16 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestParentDep"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="parentdep"/> + <depends plugin="sibling" />
<server name="TestResourceParent" discovery="BaseDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> + <parent-resource-type name="ParentDependency" plugin="parentdep"/> </runs-inside>
<plugin-configuration> @@ -29,13 +30,20 @@ <service name="TestResource" discovery="BaseDiscoveryComponent" class="BaseResourceComponent"> - <plugin-configuration> - <c:simple-property name="count" default="10" /> - <c:simple-property name="key" default="test-resource-%n,parent-%p" /> - <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-%n,parent-%p" /> - </plugin-configuration> - - </service> + <plugin-configuration> + <c:simple-property name="count" default="10" /> + <c:simple-property name="key" default="test-resource-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-%n,parent-%p" /> + </plugin-configuration> + </service> + + <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling"> + <plugin-configuration> + <c:simple-property name="count" default="10" /> + <c:simple-property name="key" default="test-resource-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + </service> </server>
</plugin> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml index 824d3fe..96658e3 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<plugin name="ResourceUpgradeMultiTest" +<plugin name="test" displayName="Resource Upgrade Multi Test" description="Resource Upgrade Multi Test" package="org.rhq.core.pc.upgrade.plugins.multi.base" @@ -8,15 +8,16 @@ xmlns="urn:xmlns:rhq-plugin" xmlns:c="urn:xmlns:rhq-configuration">
- <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> - <depends plugin="ResourceUpgradeMultiTestParentDep"/> + <depends plugin="base" useClasses="true"/> + <depends plugin="parentdep"/> + <depends plugin="sibling"/>
<server name="TestResourceParent" discovery="BaseUpgradingDiscoveryComponent" class="BaseResourceComponent">
<runs-inside> - <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> + <parent-resource-type name="ParentDependency" plugin="parentdep"/> </runs-inside>
<plugin-configuration> @@ -27,13 +28,19 @@ <service name="TestResource" discovery="BaseDiscoveryComponent" class="BaseResourceComponent"> - <plugin-configuration> - <c:simple-property name="count" default="15" /> - <c:simple-property name="key" default="UPGRADED-test-resource-%n,parent-%p" /> - </plugin-configuration> + <plugin-configuration> + <c:simple-property name="count" default="15" /> <!-- This intentionally differs from v1 --> + <c:simple-property name="key" default="UPGRADED-test-resource-%n,parent-%p" /> + </plugin-configuration>
</service>
+ <service name="TestResourceSibling" sourcePlugin="sibling" sourceType="TestResourceSibling"> + <plugin-configuration> + <c:simple-property name="count" default="15" /> <!-- This intentionally differs from v1 --> + <c:simple-property name="key" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + </service>
</server>
commit 097f744dec27c5584cf6203bbaff6fc041753b26 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 13:12:09 2010 +0200
Extracted a base class from the upgrade test in preparation for adding another round of tests.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 0a2a660..e13ea3d 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -23,43 +23,23 @@
package org.rhq.core.pc.upgrade;
-import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue;
import java.io.File; -import java.io.IOException; -import java.net.URL; import java.util.Collections; import java.util.Set;
-import org.apache.commons.io.FileUtils; import org.jmock.Expectations; import org.jmock.Mockery; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import org.rhq.core.clientapi.server.bundle.BundleServerService; -import org.rhq.core.clientapi.server.configuration.ConfigurationServerService; -import org.rhq.core.clientapi.server.content.ContentServerService; -import org.rhq.core.clientapi.server.core.CoreServerService; -import org.rhq.core.clientapi.server.discovery.DiscoveryServerService; import org.rhq.core.clientapi.server.discovery.InventoryReport; -import org.rhq.core.clientapi.server.event.EventServerService; -import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService; -import org.rhq.core.clientapi.server.measurement.MeasurementServerService; -import org.rhq.core.clientapi.server.operation.OperationServerService; -import org.rhq.core.domain.discovery.AvailabilityReport; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.pc.PluginContainer; -import org.rhq.core.pc.PluginContainerConfiguration; -import org.rhq.core.pc.ServerServices; -import org.rhq.core.pc.inventory.InventoryManager; import org.rhq.core.pc.inventory.ResourceContainer; -import org.rhq.core.pc.plugin.FileSystemPluginFinder; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test;
/** * Test cases for resource upgrade. @@ -67,39 +47,14 @@ import org.rhq.core.pc.plugin.FileSystemPluginFinder; * @author Lukas Krejci */ @Test(sequential = true, invocationCount = 1) -public class ResourceUpgradeTest { +public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
private static final String PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-1.0.0.jar"; private static final String PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-2.0.0.jar"; private static final String FAILING_PLUGIN_FILE_NAME = "/resource-upgrade-test-plugin-3.0.0.jar";
- private static final String PLUGINS_DIR_NAME = "plugins"; - private static final String DATA_DIR_NAME = "data"; - private static final String TMP_DIR_NAME = "tmp"; - - private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; - private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest"; - - private File tmpDir; - private File pluginDir; - private File dataDir; - - private BundleServerService currentBundleServerService; - private ConfigurationServerService currentConfigurationServerService; - private ContentServerService currentContentServerService; - private CoreServerService currentCoreServerService; - private DiscoveryServerService currentDiscoveryServerService; - private EventServerService currentEventServerService; - private MeasurementServerService currentMeasurementServerService; - private OperationServerService currentOperationServerService; - private ResourceFactoryServerService currentResourceFactoryServerService; - - private FakeServerInventory currentServerSideInventory; - - @AfterClass - public void undeployPlugins() throws IOException { - FileUtils.deleteDirectory(tmpDir); - } + static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; + static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest";
@BeforeClass public void sanityCheck() { @@ -108,18 +63,9 @@ public class ResourceUpgradeTest { verifyPluginExists(FAILING_PLUGIN_FILE_NAME); }
- @BeforeClass(dependsOnMethods = "sanityCheck") - public void init() { - tmpDir = getTmpDirectory(); - pluginDir = new File(tmpDir, PLUGINS_DIR_NAME); - assertTrue(pluginDir.mkdir(), "Could not create plugin deploy directory."); - dataDir = new File(tmpDir, DATA_DIR_NAME); - assertTrue(dataDir.mkdir(), "Could not create plugin container data directory."); - } - @Test public void testIgnoreUncommittedResources() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.NEW);
TestPayload testNoChange = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { @@ -138,8 +84,8 @@ public class ResourceUpgradeTest { { defineDefaultExpectations(this);
- between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED)); } }; } @@ -150,22 +96,22 @@ public class ResourceUpgradeTest {
@Test public void testUpgradeData() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); upgradeTest(false); }
@Test public void testInventoryReinitializationFromServerDuringUpgrade() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); upgradeTest(true); }
@Test public void testSkipUpgradeWhenServerUnavailable() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- currentServerSideInventory.setFailing(true); + getCurrentServerSideInventory().setFailing(true);
TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { public void test(Set<Resource> discoveredResources) { @@ -184,10 +130,10 @@ public class ResourceUpgradeTest { { defineDefaultExpectations(this);
- between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
- never(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); } }; } @@ -198,7 +144,7 @@ public class ResourceUpgradeTest {
@Test public void testUpgradeWithPlatformDeletedOnServer() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { @@ -227,15 +173,15 @@ public class ResourceUpgradeTest {
//the first merge will be triggered from within the upgrade process and we are //going to report null sync. - oneOf(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.clearPlatform()); + oneOf(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().clearPlatform());
//the rest of the inventory merges are executed by discoveries, so let's import the //discovered stuff into the server-side inventory. - between(1, 3).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + between(1, 3).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
- never(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); } }; } @@ -246,7 +192,7 @@ public class ResourceUpgradeTest {
@Test public void testUpgradeFailureHandling() throws Exception { - currentServerSideInventory = new FakeServerInventory(); + setCurrentServerSideInventory(new FakeServerInventory()); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { @@ -272,11 +218,11 @@ public class ResourceUpgradeTest { { defineDefaultExpectations(this);
- between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
- oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); - will(currentServerSideInventory.upgradeResources()); + oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); + will(getCurrentServerSideInventory().upgradeResources()); } }; } @@ -297,20 +243,21 @@ public class ResourceUpgradeTest { assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); } - + public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { defineDefaultExpectations(this);
- between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(requiredInventoryStatus)); + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(requiredInventoryStatus)); } }; } });
} +
private void upgradeTest(boolean clearInventoryDat) throws Exception { initialSyncAndDiscovery(InventoryStatus.COMMITTED); @@ -339,189 +286,14 @@ public class ResourceUpgradeTest { { defineDefaultExpectations(this);
- between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + between(1, 4).of(getCurrentDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class))); + will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
- oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); - will(currentServerSideInventory.upgradeResources()); + oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class))); + will(getCurrentServerSideInventory().upgradeResources()); } }; } }); } - - private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception { - PluginContainerConfiguration conf = new PluginContainerConfiguration(); - - conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); - conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME)); - conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME)); - conf.setInsideAgent(true); //pc must think it's inside an agent so that it persists the inventory between restarts - conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory())); - conf.setCreateResourceClassloaders(false); - - //we're not interested in any scans happening out of our control - conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE); - conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE); - conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE); - conf.setEventSenderInitialDelay(Long.MAX_VALUE); - conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE); - conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE); - conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE); - - currentBundleServerService = context.mock(BundleServerService.class); - currentConfigurationServerService = context.mock(ConfigurationServerService.class); - currentContentServerService = context.mock(ContentServerService.class); - currentCoreServerService = context.mock(CoreServerService.class); - currentDiscoveryServerService = context.mock(DiscoveryServerService.class); - currentEventServerService = context.mock(EventServerService.class); - currentMeasurementServerService = context.mock(MeasurementServerService.class); - currentOperationServerService = context.mock(OperationServerService.class); - currentResourceFactoryServerService = context.mock(ResourceFactoryServerService.class); - - ServerServices serverServices = new ServerServices(); - serverServices.setBundleServerService(currentBundleServerService); - serverServices.setConfigurationServerService(currentConfigurationServerService); - serverServices.setContentServerService(currentContentServerService); - serverServices.setCoreServerService(currentCoreServerService); - serverServices.setDiscoveryServerService(currentDiscoveryServerService); - serverServices.setEventServerService(currentEventServerService); - serverServices.setMeasurementServerService(currentMeasurementServerService); - serverServices.setOperationServerService(currentOperationServerService); - serverServices.setResourceFactoryServerService(currentResourceFactoryServerService); - - conf.setServerServices(serverServices); - - return conf; - } - - /** - * @param pluginResourcePath - */ - private void verifyPluginExists(String pluginResourcePath) { - URL url = getClass().getResource(pluginResourcePath); - - File pluginFile = FileUtils.toFile(url); - - assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar could not be found."); - } - - private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws IOException { - URL pluginUrl = getClass().getResource(pluginResourcePath); - - File pluginFile = new File(pluginResourcePath); - String pluginFileName = pluginFile.getName(); - - FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName)); - } - - private static File getTmpDirectory() { - File ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); - - while (ret.exists() || !ret.mkdir()) { - ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); - } - - return ret; - } - - private interface TestPayload { - Expectations getExpectations(Mockery context) throws Exception; - void test(Set<Resource> resourceUpgradeTestResources); - boolean isClearInventoryDat(); - String getResourceTypeName(); - String getResourceTypePluginName(); - } - - private static abstract class AbstractTestPayload implements TestPayload { - private boolean clearInventoryDat; - private String resourceTypeName; - private String resourceTypePluginName; - - public AbstractTestPayload(boolean clearInventoryDat, String resourceTypeName, String resourceTypePluginName) { - this.clearInventoryDat = clearInventoryDat; - this.resourceTypeName = resourceTypeName; - this.resourceTypePluginName = resourceTypePluginName; - } - - public boolean isClearInventoryDat() { - return clearInventoryDat; - } - - public String getResourceTypeName() { - return resourceTypeName; - } - - public String getResourceTypePluginName() { - return resourceTypePluginName; - } - } - - private Set<Resource> getTestingResources(String resourceTypeName, String resourceTypePluginName) { - ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType(resourceTypeName, resourceTypePluginName); - - return currentServerSideInventory.findResourcesByType(resType); - } - - private void executeTestWithPlugins(Set<String> pluginResourcePaths, TestPayload test) throws Exception { - FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); - - for(String pluginResourcePath : pluginResourcePaths) { - copyPlugin(pluginResourcePath, pluginDir); - } - - Mockery context = new Mockery(); - - PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context); - - if (test.isClearInventoryDat()) { - File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); - inventoryDat.delete(); - } - - context.checking(test.getExpectations(context)); - - PluginContainer.getInstance().setConfiguration(pcConfig); - PluginContainer.getInstance().initialize(); - - try { - //give the pc the time to finish resource upgrade - Thread.sleep(1000); - - //execute full discovery - InventoryManager im = PluginContainer.getInstance().getInventoryManager(); - im.executeServerScanImmediately(); - im.executeServiceScanImmediately(); - - Set<Resource> resources = getTestingResources(test.getResourceTypeName(), test.getResourceTypePluginName()); - - test.test(resources); - - context.assertIsSatisfied(); - } finally { - PluginContainer.getInstance().shutdown(); - } - } - - @SuppressWarnings("unchecked") - private void defineDefaultExpectations(Expectations expectations) { - expectations.ignoring(currentBundleServerService); - expectations.ignoring(currentConfigurationServerService); - expectations.ignoring(currentContentServerService); - expectations.ignoring(currentCoreServerService); - expectations.ignoring(currentEventServerService); - expectations.ignoring(currentMeasurementServerService); - expectations.ignoring(currentOperationServerService); - expectations.ignoring(currentResourceFactoryServerService); - - //just ignore these invocations if we get a availability scan in the PC... - expectations.allowing(currentDiscoveryServerService).mergeAvailabilityReport(expectations.with(Expectations.any(AvailabilityReport.class))); - - expectations.allowing(currentDiscoveryServerService).getResources(expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); - expectations.will(currentServerSideInventory.getResources()); - } - - private void cleanDataDir() throws IOException { - FileUtils.cleanDirectory(new File(tmpDir, DATA_DIR_NAME)); - } } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java new file mode 100644 index 0000000..f03f2a4 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java @@ -0,0 +1,350 @@ +/* + * 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.core.pc.upgrade; + +import static org.testng.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Set; + +import org.apache.commons.io.FileUtils; +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.rhq.core.clientapi.server.bundle.BundleServerService; +import org.rhq.core.clientapi.server.configuration.ConfigurationServerService; +import org.rhq.core.clientapi.server.content.ContentServerService; +import org.rhq.core.clientapi.server.core.CoreServerService; +import org.rhq.core.clientapi.server.discovery.DiscoveryServerService; +import org.rhq.core.clientapi.server.event.EventServerService; +import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService; +import org.rhq.core.clientapi.server.measurement.MeasurementServerService; +import org.rhq.core.clientapi.server.operation.OperationServerService; +import org.rhq.core.domain.discovery.AvailabilityReport; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.PluginContainerConfiguration; +import org.rhq.core.pc.ServerServices; +import org.rhq.core.pc.inventory.InventoryManager; +import org.rhq.core.pc.plugin.FileSystemPluginFinder; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; + +/** + * + * @author Lukas Krejci + */ +public class ResourceUpgradeTestBase { + + private static final String PLUGINS_DIR_NAME = "plugins"; + private static final String DATA_DIR_NAME = "data"; + private static final String TMP_DIR_NAME = "tmp"; + private File tmpDir; + private File pluginDir; + private File dataDir; + private BundleServerService currentBundleServerService; + private ConfigurationServerService currentConfigurationServerService; + private ContentServerService currentContentServerService; + private CoreServerService currentCoreServerService; + private DiscoveryServerService currentDiscoveryServerService; + private EventServerService currentEventServerService; + private MeasurementServerService currentMeasurementServerService; + private OperationServerService currentOperationServerService; + private ResourceFactoryServerService currentResourceFactoryServerService; + private FakeServerInventory currentServerSideInventory; + + @BeforeClass + public void init() { + tmpDir = getTmpDirectory(); + pluginDir = new File(tmpDir, PLUGINS_DIR_NAME); + assertTrue(pluginDir.mkdir(), "Could not create plugin deploy directory."); + dataDir = new File(tmpDir, DATA_DIR_NAME); + assertTrue(dataDir.mkdir(), "Could not create plugin container data directory."); + } + + @AfterClass + public void undeployPlugins() throws IOException { + FileUtils.deleteDirectory(tmpDir); + } + + protected void setCurrentServerSideInventory(FakeServerInventory currentServerSideInventory) { + this.currentServerSideInventory = currentServerSideInventory; + } + + protected FakeServerInventory getCurrentServerSideInventory() { + return currentServerSideInventory; + } + + protected void setCurrentResourceFactoryServerService(ResourceFactoryServerService currentResourceFactoryServerService) { + this.currentResourceFactoryServerService = currentResourceFactoryServerService; + } + + protected ResourceFactoryServerService getCurrentResourceFactoryServerService() { + return currentResourceFactoryServerService; + } + + protected void setCurrentOperationServerService(OperationServerService currentOperationServerService) { + this.currentOperationServerService = currentOperationServerService; + } + + protected OperationServerService getCurrentOperationServerService() { + return currentOperationServerService; + } + + protected void setCurrentMeasurementServerService(MeasurementServerService currentMeasurementServerService) { + this.currentMeasurementServerService = currentMeasurementServerService; + } + + protected MeasurementServerService getCurrentMeasurementServerService() { + return currentMeasurementServerService; + } + + protected void setCurrentEventServerService(EventServerService currentEventServerService) { + this.currentEventServerService = currentEventServerService; + } + + protected EventServerService getCurrentEventServerService() { + return currentEventServerService; + } + + protected void setCurrentDiscoveryServerService(DiscoveryServerService currentDiscoveryServerService) { + this.currentDiscoveryServerService = currentDiscoveryServerService; + } + + protected DiscoveryServerService getCurrentDiscoveryServerService() { + return currentDiscoveryServerService; + } + + protected void setCurrentCoreServerService(CoreServerService currentCoreServerService) { + this.currentCoreServerService = currentCoreServerService; + } + + protected CoreServerService getCurrentCoreServerService() { + return currentCoreServerService; + } + + protected void setCurrentContentServerService(ContentServerService currentContentServerService) { + this.currentContentServerService = currentContentServerService; + } + + protected ContentServerService getCurrentContentServerService() { + return currentContentServerService; + } + + protected void setCurrentConfigurationServerService(ConfigurationServerService currentConfigurationServerService) { + this.currentConfigurationServerService = currentConfigurationServerService; + } + + protected ConfigurationServerService getCurrentConfigurationServerService() { + return currentConfigurationServerService; + } + + protected void setCurrentBundleServerService(BundleServerService currentBundleServerService) { + this.currentBundleServerService = currentBundleServerService; + } + + protected BundleServerService getCurrentBundleServerService() { + return currentBundleServerService; + } + + protected static File getTmpDirectory() { + File ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); + + while (ret.exists() || !ret.mkdir()) { + ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); + } + + return ret; + } + + private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception { + PluginContainerConfiguration conf = new PluginContainerConfiguration(); + + conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); + conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME)); + conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME)); + conf.setInsideAgent(true); //pc must think it's inside an agent so that it persists the inventory between restarts + conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory())); + conf.setCreateResourceClassloaders(false); + + //we're not interested in any scans happening out of our control + conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE); + conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setEventSenderInitialDelay(Long.MAX_VALUE); + conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE); + conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE); + + setCurrentBundleServerService(context.mock(BundleServerService.class)); + setCurrentConfigurationServerService(context.mock(ConfigurationServerService.class)); + setCurrentContentServerService(context.mock(ContentServerService.class)); + setCurrentCoreServerService(context.mock(CoreServerService.class)); + setCurrentDiscoveryServerService(context.mock(DiscoveryServerService.class)); + setCurrentEventServerService(context.mock(EventServerService.class)); + setCurrentMeasurementServerService(context.mock(MeasurementServerService.class)); + setCurrentOperationServerService(context.mock(OperationServerService.class)); + setCurrentResourceFactoryServerService(context.mock(ResourceFactoryServerService.class)); + + ServerServices serverServices = new ServerServices(); + serverServices.setBundleServerService(getCurrentBundleServerService()); + serverServices.setConfigurationServerService(getCurrentConfigurationServerService()); + serverServices.setContentServerService(getCurrentContentServerService()); + serverServices.setCoreServerService(getCurrentCoreServerService()); + serverServices.setDiscoveryServerService(getCurrentDiscoveryServerService()); + serverServices.setEventServerService(getCurrentEventServerService()); + serverServices.setMeasurementServerService(getCurrentMeasurementServerService()); + serverServices.setOperationServerService(getCurrentOperationServerService()); + serverServices.setResourceFactoryServerService(getCurrentResourceFactoryServerService()); + + conf.setServerServices(serverServices); + + return conf; + } + + /** + * @param pluginResourcePath + */ + protected void verifyPluginExists(String pluginResourcePath) { + URL url = getClass().getResource(pluginResourcePath); + + File pluginFile = FileUtils.toFile(url); + + assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar could not be found."); + } + + private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws IOException { + URL pluginUrl = getClass().getResource(pluginResourcePath); + + File pluginFile = new File(pluginResourcePath); + String pluginFileName = pluginFile.getName(); + + FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName)); + } + + protected interface TestPayload { + Expectations getExpectations(Mockery context) throws Exception; + void test(Set<Resource> resourceUpgradeTestResources); + boolean isClearInventoryDat(); + String getResourceTypeName(); + String getResourceTypePluginName(); + } + + protected static abstract class AbstractTestPayload implements TestPayload { + private boolean clearInventoryDat; + private String resourceTypeName; + private String resourceTypePluginName; + + public AbstractTestPayload(boolean clearInventoryDat, String resourceTypeName, String resourceTypePluginName) { + this.clearInventoryDat = clearInventoryDat; + this.resourceTypeName = resourceTypeName; + this.resourceTypePluginName = resourceTypePluginName; + } + + public boolean isClearInventoryDat() { + return clearInventoryDat; + } + + public String getResourceTypeName() { + return resourceTypeName; + } + + public String getResourceTypePluginName() { + return resourceTypePluginName; + } + } + + /** + * + */ + public ResourceUpgradeTestBase() { + super(); + } + + private Set<Resource> getTestingResources(String resourceTypeName, String resourceTypePluginName) { + ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType(resourceTypeName, resourceTypePluginName); + + return getCurrentServerSideInventory().findResourcesByType(resType); + } + + protected void executeTestWithPlugins(Set<String> pluginResourcePaths, TestPayload test) throws Exception { + FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); + + for(String pluginResourcePath : pluginResourcePaths) { + copyPlugin(pluginResourcePath, pluginDir); + } + + Mockery context = new Mockery(); + + PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context); + + if (test.isClearInventoryDat()) { + File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); + inventoryDat.delete(); + } + + context.checking(test.getExpectations(context)); + + PluginContainer.getInstance().setConfiguration(pcConfig); + PluginContainer.getInstance().initialize(); + + try { + //give the pc the time to finish resource upgrade + Thread.sleep(1000); + + //execute full discovery + InventoryManager im = PluginContainer.getInstance().getInventoryManager(); + im.executeServerScanImmediately(); + im.executeServiceScanImmediately(); + + Set<Resource> resources = getTestingResources(test.getResourceTypeName(), test.getResourceTypePluginName()); + + test.test(resources); + + context.assertIsSatisfied(); + } finally { + PluginContainer.getInstance().shutdown(); + } + } + + @SuppressWarnings("unchecked") + protected void defineDefaultExpectations(Expectations expectations) { + expectations.ignoring(getCurrentBundleServerService()); + expectations.ignoring(getCurrentConfigurationServerService()); + expectations.ignoring(getCurrentContentServerService()); + expectations.ignoring(getCurrentCoreServerService()); + expectations.ignoring(getCurrentEventServerService()); + expectations.ignoring(getCurrentMeasurementServerService()); + expectations.ignoring(getCurrentOperationServerService()); + expectations.ignoring(getCurrentResourceFactoryServerService()); + + //just ignore these invocations if we get a availability scan in the PC... + expectations.allowing(getCurrentDiscoveryServerService()).mergeAvailabilityReport(expectations.with(Expectations.any(AvailabilityReport.class))); + + expectations.allowing(getCurrentDiscoveryServerService()).getResources(expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); + expectations.will(getCurrentServerSideInventory().getResources()); + } + + protected void cleanDataDir() throws IOException { + FileUtils.cleanDirectory(new File(tmpDir, DATA_DIR_NAME)); + } +}
commit 1863f1ab0c4473e6a79c469c16b73b6810733325 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 12:58:32 2010 +0200
Preparing the upgrade tests to accept more complicated scenarios.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 1479345..0a2a660 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -77,6 +77,9 @@ public class ResourceUpgradeTest { private static final String DATA_DIR_NAME = "data"; private static final String TMP_DIR_NAME = "tmp";
+ private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource"; + private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest"; + private File tmpDir; private File pluginDir; private File dataDir; @@ -119,8 +122,12 @@ public class ResourceUpgradeTest { currentServerSideInventory = new FakeServerInventory(); initialSyncAndDiscovery(InventoryStatus.NEW);
- TestPayload testNoChange = new TestPayload() { - public void test(Resource discoveredResource) { + TestPayload testNoChange = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> discoveredResources) { + assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = discoveredResources.iterator().next(); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); @@ -138,7 +145,7 @@ public class ResourceUpgradeTest { } };
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, testNoChange); + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), testNoChange); }
@Test @@ -160,8 +167,12 @@ public class ResourceUpgradeTest {
currentServerSideInventory.setFailing(true);
- TestPayload test = new TestPayload() { - public void test(Resource discoveredResource) { + TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> discoveredResources) { + assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = discoveredResources.iterator().next(); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); @@ -182,7 +193,7 @@ public class ResourceUpgradeTest { } };
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, test); + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test); }
@Test @@ -190,8 +201,12 @@ public class ResourceUpgradeTest { currentServerSideInventory = new FakeServerInventory(); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- TestPayload test = new TestPayload() { - public void test(Resource discoveredResource) { + TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> discoveredResources) { + assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = discoveredResources.iterator().next(); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); assertEquals(discoveredResource.getDescription(), "resource-description-v2"); @@ -226,7 +241,7 @@ public class ResourceUpgradeTest { } };
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, test); + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test); }
@Test @@ -234,12 +249,16 @@ public class ResourceUpgradeTest { currentServerSideInventory = new FakeServerInventory(); initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- TestPayload test = new TestPayload() { - public void test(Resource resourceUpgradeTestResource) { - assertTrue(resourceUpgradeTestResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side."); + TestPayload test = new AbstractTestPayload(false, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> resourceUpgradeTestResources) { + assertEquals(resourceUpgradeTestResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = resourceUpgradeTestResources.iterator().next(); + + assertTrue(discoveredResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side.");
//the discovery of the failed resource mustn't have run - ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(resourceUpgradeTestResource); + ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); File dataDir = container.getResourceContext().getDataDirectory();
File marker = new File(dataDir, "failing-discovery-ran"); @@ -263,13 +282,17 @@ public class ResourceUpgradeTest { } };
- executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), false, test); + executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), test); }
private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { cleanDataDir(); - executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), true, new TestPayload() { - public void test(Resource discoveredResource) { + executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> discoveredResources) { + assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = discoveredResources.iterator().next(); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); assertEquals(discoveredResource.getName(), "resource-name-v1"); assertEquals(discoveredResource.getDescription(), "resource-description-v1"); @@ -292,8 +315,12 @@ public class ResourceUpgradeTest { private void upgradeTest(boolean clearInventoryDat) throws Exception { initialSyncAndDiscovery(InventoryStatus.COMMITTED);
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), clearInventoryDat, new TestPayload() { - public void test(Resource discoveredResource) { + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat, SINGLETON_RESOURCE_TYPE_NAME, SINGLETON_RESOURCE_TYPE_PLUGIN_NAME) { + public void test(Set<Resource> discoveredResources) { + assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found."); + + Resource discoveredResource = discoveredResources.iterator().next(); + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); assertEquals(discoveredResource.getName(), "resource-name-v2"); assertEquals(discoveredResource.getDescription(), "resource-description-v2"); @@ -400,16 +427,43 @@ public class ResourceUpgradeTest {
private interface TestPayload { Expectations getExpectations(Mockery context) throws Exception; - void test(Resource resourceUpgradeTestResource); + void test(Set<Resource> resourceUpgradeTestResources); + boolean isClearInventoryDat(); + String getResourceTypeName(); + String getResourceTypePluginName(); }
- private Set<Resource> getTestingResources() { - ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType("Resource", "ResourceUpgradeTest"); + private static abstract class AbstractTestPayload implements TestPayload { + private boolean clearInventoryDat; + private String resourceTypeName; + private String resourceTypePluginName; + + public AbstractTestPayload(boolean clearInventoryDat, String resourceTypeName, String resourceTypePluginName) { + this.clearInventoryDat = clearInventoryDat; + this.resourceTypeName = resourceTypeName; + this.resourceTypePluginName = resourceTypePluginName; + } + + public boolean isClearInventoryDat() { + return clearInventoryDat; + } + + public String getResourceTypeName() { + return resourceTypeName; + } + + public String getResourceTypePluginName() { + return resourceTypePluginName; + } + } + + private Set<Resource> getTestingResources(String resourceTypeName, String resourceTypePluginName) { + ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType(resourceTypeName, resourceTypePluginName);
return currentServerSideInventory.findResourcesByType(resType); }
- private void executeTestWithPlugins(Set<String> pluginResourcePaths, boolean clearInventoryDat, TestPayload test) throws Exception { + private void executeTestWithPlugins(Set<String> pluginResourcePaths, TestPayload test) throws Exception { FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
for(String pluginResourcePath : pluginResourcePaths) { @@ -420,7 +474,7 @@ public class ResourceUpgradeTest {
PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context);
- if (clearInventoryDat) { + if (test.isClearInventoryDat()) { File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); inventoryDat.delete(); } @@ -439,14 +493,9 @@ public class ResourceUpgradeTest { im.executeServerScanImmediately(); im.executeServiceScanImmediately();
- Set<Resource> resources = getTestingResources(); - - assertEquals(resources.size(), 1, "There should be only a single testing resource but " + resources - + " were found."); - - Resource discoveredResource = resources.iterator().next(); + Set<Resource> resources = getTestingResources(test.getResourceTypeName(), test.getResourceTypePluginName());
- test.test(discoveredResource); + test.test(resources);
context.assertIsSatisfied(); } finally {
commit 659920513807b095cdd0ac91c3f1c2e091d090a7 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 12:57:21 2010 +0200
Setting the height of the errorsGrid to a fixed value so that it stays at the bottom of the page.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index 95bec5f..b439d44 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@ -23,11 +23,7 @@ import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
-import com.smartgwt.client.data.DSCallback; -import com.smartgwt.client.data.DSRequest; -import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.types.GroupStartOpen; import com.smartgwt.client.widgets.HTMLPane; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Window; @@ -44,13 +40,11 @@ import com.smartgwt.client.widgets.grid.events.CellClickHandler; */ public class OverviewView extends LocatableVLayout {
- private ResourceComposite resourceComposite; private OverviewForm form; private Table errorsGrid;
public OverviewView(String locatorId, ResourceComposite resourceComposite) { super(locatorId); - this.resourceComposite = resourceComposite; form = new OverviewForm(extendLocatorId("form"), resourceComposite); errorsGrid = new Table(extendLocatorId("errors"), "Detected errors", null, null, new String[] { ResourceErrorsDataSource.DETAIL_ID });
@@ -61,7 +55,7 @@ public class OverviewView extends LocatableVLayout { errorsGrid.setDataSource(errors);
form.setHeight("*"); - errorsGrid.setHeight("10%"); + errorsGrid.setHeight(200); //this should be just enough to fit the maximum of 3 rows in this table (there's at most 1 error per type)
addMember(form); addMember(errorsGrid);
commit c704c79f4acfedf4d959de6d7d27db1b22efa1f3 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Sep 29 12:44:55 2010 +0200
Adding a bunch of test plugins for dependency resolution during resource upgrade failure handling.
diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index 4b09ef8..035bf36 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -195,6 +195,106 @@ <fileset dir="${project.build.testOutputDirectory}/tmp/failing" includes="**/*.class,**/rhq-plugin.xml" /> </jar>
+ <copy toDir="${project.build.testOutputDirectory}/tmp/multi/base/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml" /> + </copy> + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/base/org/rhq/core/pc/upgrade/plugins/multi/base"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/base/*.class" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-base-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/base" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentdep1/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentdep1/org/rhq/core/pc/upgrade/plugins/multi/parentdep1"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/parentdep1" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentdep2/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentdep2/org/rhq/core/pc/upgrade/plugins/multi/parentdep2"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/parentdep2" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentsibling1/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentsibling1/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/parentsibling1" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentsibling2/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/parentsibling2/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/parentsibling2" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/root/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/root/org/rhq/core/pc/upgrade/plugins/multi/root"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/root/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-root-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/root" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/sibling1/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/sibling1/org/rhq/core/pc/upgrade/plugins/multi/sibling1"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/sibling1/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-sibling-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/sibling1" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/sibling2/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/sibling2/org/rhq/core/pc/upgrade/plugins/multi/sibling2"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/sibling2/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-sibling-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/sibling2" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v1/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v1/org/rhq/core/pc/upgrade/plugins/multi/v1"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v1/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/v1" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + + <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v2/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml" /> + </copy> + <!-- <copy toDir="${project.build.testOutputDirectory}/tmp/multi/v2/org/rhq/core/pc/upgrade/plugins/multi/v2"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/multi/v2/*.class" /> + </copy> --> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-multi-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/multi/v2" includes="**/*.class,**/rhq-plugin.xml" /> + </jar> + <delete dir="${project.build.testOutputDirectory}/tmp"/> </tasks> </configuration> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java new file mode 100644 index 0000000..61d4fe0 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseDiscoveryComponent.java @@ -0,0 +1,70 @@ +/* + * 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.core.pc.upgrade.plugins.multi.base; + +import java.util.HashSet; +import java.util.Set; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; + +/** + * + * @author Lukas Krejci + */ +public class BaseDiscoveryComponent<T extends ResourceComponent> implements ResourceDiscoveryComponent<T> { + + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<T> context) + throws InvalidPluginConfigurationException, Exception { + + HashSet<DiscoveredResourceDetails> results = new HashSet<DiscoveredResourceDetails>(); + + Configuration pluginConfig = context.getDefaultPluginConfiguration(); + + String keyTemplate = pluginConfig.getSimpleValue("key", null); + int count = pluginConfig.getSimple("count").getIntegerValue(); + + int parentN = context.getParentResourceContext().getPluginConfiguration().getSimple("ordinal") + .getIntegerValue(); + + for (int i = 0; i < count; ++i) { + + String key = getResourceKey(keyTemplate, i, parentN); + + pluginConfig.put(new PropertySimple("ordinal", i)); + + DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(), key, key, null, + null, pluginConfig, null); + + results.add(detail); + } + + return results; + } + + protected static String getResourceKey(String template, int n, int parentN) { + return template.replace("%n", Integer.toString(n)).replace("%p", Integer.toString(parentN)); + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java new file mode 100644 index 0000000..c5bbf3a --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseResourceComponent.java @@ -0,0 +1,67 @@ +/* + * 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.core.pc.upgrade.plugins.multi.base; + +import java.util.Collections; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; + +/** + * + * @author Lukas Krejci + */ +public class BaseResourceComponent<T extends ResourceComponent> implements ResourceComponent<T> { + + private ResourceContext<T> context; + private final Log log = LogFactory.getLog(getClass()); + + private Set<Integer> childrenToFailUpgrade; + + public AvailabilityType getAvailability() { + return AvailabilityType.UP; + } + + public void start(ResourceContext<T> context) throws InvalidPluginConfigurationException, Exception { + log.info("Starting multi resource child component with resource key '" + context.getResourceKey() + "'."); + this.context = context; + } + + public void stop() { + log.info("Stopping multi resource child component with resource key '" + context.getResourceKey() + "'."); + } + + public int getOrdinal() { + return context.getPluginConfiguration().getSimple("ordinal").getIntegerValue(); + } + + public Set<Integer> getChildrenToFailUpgrade() { + return childrenToFailUpgrade == null ? Collections.<Integer>emptySet() : childrenToFailUpgrade; + } + + public void setChildrenToFailUpgrade(Set<Integer> childrenToFailUpgrade) { + this.childrenToFailUpgrade = childrenToFailUpgrade; + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java new file mode 100644 index 0000000..beb36db --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/BaseUpgradingDiscoveryComponent.java @@ -0,0 +1,61 @@ +/* + * 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.core.pc.upgrade.plugins.multi.base; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + +/** + * + * @author Lukas Krejci + */ +public class BaseUpgradingDiscoveryComponent<T extends BaseResourceComponent> extends BaseDiscoveryComponent<T> implements ResourceUpgradeFacet<T> { + + public ResourceUpgradeReport upgrade(ResourceUpgradeContext<T> inventoriedResource) { + Configuration pluginConfig = inventoriedResource.getPluginConfiguration(); + + BaseResourceComponent<?> parent = inventoriedResource.getParentResourceComponent(); + int ordinal = pluginConfig.getSimple("ordinal").getIntegerValue(); + int parentOrdinal = parent == null ? 0 : parent.getOrdinal(); + + boolean fail = Boolean.getBoolean(pluginConfig.getSimpleValue("failUpgrade", "false")); + + if (!fail && parent != null) { + fail = parent.getChildrenToFailUpgrade().contains(Integer.valueOf(ordinal)); + } + + if (fail) { + throw new RuntimeException("Failing the resource upgrade purposefully."); + } + + String newKey = pluginConfig.getSimpleValue("upgradedKey", null); + + if (newKey == null) { + return null; + } + + ResourceUpgradeReport report = new ResourceUpgradeReport(); + + report.setNewResourceKey(getResourceKey(newKey, ordinal, parentOrdinal)); + return null; + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml new file mode 100644 index 0000000..7edfba1 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/base/rhq-plugin.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<plugin name="ResourceUpgradeMultiTestBase" + displayName="" + description="" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <!-- + Only the inheriting plugins create the concrete resources based on the + classes defined in this abstract base plugin. + + These are the plugin configuration properties needed by the base plugin: + + key = the template to create the resource key from + count = the number of resources to discover + upgradedKey = this *must* be specified on the resource type *to be upgraded* and + *must* be the same as the key template on the resource type that + it is upgraded to (i.e. the plugin.v1.upgradedKey == plugin.v2.key) + + the discovery add a new property called "ordinal" to the plugin config + of the created resources, which contains the index of that resource amongst + its siblings. + + the key template can contain %n which is replaced by the ordinal and %p which + is replaced by the ordinal of its parent. + + + + if the discovery component of the concrete resource is (or inherits from) + BaseUpgradingDiscoveryComponent, it can specify further plugin config properties + influencing the upgrade: + + failUpgrade = true to throw an exception during upgrade + --> + +</plugin> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml new file mode 100644 index 0000000..3612974 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep1/rhq-plugin.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestParentDep" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestRoot"/> + + <server name="ParentDependency" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="1" /> + <c:simple-property name="key" default="test-resource-parent-dep-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-dep-%n,parent-%p" /> + </plugin-configuration> + + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml new file mode 100644 index 0000000..6b95114 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentdep2/rhq-plugin.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestParentDep" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestRoot"/> + + <server name="ParentDependency" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="1" /> + <c:simple-property name="key" default="UPGRADED-test-resource-parent-dep-%n,parent-%p" /> + </plugin-configuration> + + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml new file mode 100644 index 0000000..fbade54 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling1/rhq-plugin.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestParentSibling" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestRoot"/> + + <server name="ParentDepSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="1" /> + <c:simple-property name="key" default="test-resource-parent-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + </plugin-configuration> + + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml new file mode 100644 index 0000000..f16d526 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/parentsibling2/rhq-plugin.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestParentSibling" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestRoot"/> + + <server name="ParentDepSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="Root" plugin="ResourceUpgradeMultiTestRoot"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="1" /> + <c:simple-property name="key" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + </plugin-configuration> + + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml new file mode 100644 index 0000000..b5efbb1 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/root/rhq-plugin.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestRoot" + displayName="" + description="" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="Root" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <plugin-configuration> + <c:simple-property name="count" default="1" /> + <c:simple-property name="key" default="test-resource-root-%n" /> + </plugin-configuration> + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml new file mode 100644 index 0000000..f87ef4d --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling1/rhq-plugin.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTestSibling" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestParentDep"/> + + <server name="TestResourceParentSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <plugin-configuration> + <c:simple-property name="count" default="2" /> + <c:simple-property name="key" default="test-resource-parent-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + </plugin-configuration> + + <service name="TestResourceSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="10" /> + <c:simple-property name="key" default="test-resource-sibling-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + + </service> + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml new file mode 100644 index 0000000..e6ab95f --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/sibling2/rhq-plugin.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<plugin name="ResourceUpgradeMultiTestSibling" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestParentDep"/> + + <server name="TestResourceParentSibling" + discovery="BaseUpgradingDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="2" /> + <c:simple-property name="key" default="UPGRADED-test-resource-parent-sibling-%n,parent-%p" /> + </plugin-configuration> + + <service name="TestResourceSibling" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="15" /> + <c:simple-property name="key" default="UPGRADED-test-resource-sibling-%n,parent-%p" /> + </plugin-configuration> + + </service> + + + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml new file mode 100644 index 0000000..32ad438 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v1/rhq-plugin.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeMultiTest" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestParentDep"/> + + <server name="TestResourceParent" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="2" /> + <c:simple-property name="key" default="test-resource-parent-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-parent-%n,parent-%p" /> + </plugin-configuration> + + <service name="TestResource" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="10" /> + <c:simple-property name="key" default="test-resource-%n,parent-%p" /> + <c:simple-property name="upgradedKey" default="UPGRADED-test-resource-%n,parent-%p" /> + </plugin-configuration> + + </service> + </server> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml new file mode 100644 index 0000000..824d3fe --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/multi/v2/rhq-plugin.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<plugin name="ResourceUpgradeMultiTest" + displayName="Resource Upgrade Multi Test" + description="Resource Upgrade Multi Test" + package="org.rhq.core.pc.upgrade.plugins.multi.base" + version="2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <depends plugin="ResourceUpgradeMultiTestBase" useClasses="true"/> + <depends plugin="ResourceUpgradeMultiTestParentDep"/> + + <server name="TestResourceParent" + discovery="BaseUpgradingDiscoveryComponent" + class="BaseResourceComponent"> + + <runs-inside> + <parent-resource-type name="ParentDependency" plugin="ResourceUpgradeMultiTestParentDep"/> + </runs-inside> + + <plugin-configuration> + <c:simple-property name="count" default="2" /> + <c:simple-property name="key" default="UPGRADED-test-resource-parent-%n,parent-%p" /> + </plugin-configuration> + + <service name="TestResource" + discovery="BaseDiscoveryComponent" + class="BaseResourceComponent"> + <plugin-configuration> + <c:simple-property name="count" default="15" /> + <c:simple-property name="key" default="UPGRADED-test-resource-%n,parent-%p" /> + </plugin-configuration> + + </service> + + + </server> + +</plugin> +
commit 400635fb9e3cf30ac7d55d98330e4ad4e5c120b9 Merge: 1d94af7... 64abb7e... Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 28 12:45:20 2010 -0400
Merge branch 'master' into master-jay
commit 1d94af7604a60412da8017e721ef0bb36504d8fd Author: Jay Shaughnessy jshaughn@redhat.com Date: Tue Sep 28 12:35:44 2010 -0400
AutoGroup/ResourceTree work - Fix up breadcrumbs for AutoGroup selections and also fix up some path - issues that were happening when selecting AG resources.
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 b59edba..7c895e0 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 @@ -339,10 +339,13 @@ public class CoreGUI implements EntryPoint, ValueChangeHandler<String> { if (viewPath.matches("(Resource|ResourceGroup)/[^/]*")) { // e.g. "Resource/10001" if (!currentViewPath.startsWith(viewPath)) { - // The Resource that was selected is not the same Resource that was previously selected - - // grab the end portion of the previous history URL and append it to the new history URL, - // so the same tab is selected for the new Resource. - String suffix = currentViewPath.replaceFirst("^[^/]*/[^/]*", ""); + // The Node that was selected is not the same Node that was previously selected - it + // may not even be the same node type. For example, the user could have moved from a + // resource to an autogroup in the same tree. Try to keep the tab selection sticky as best as + // possible while moving from one view to another by grabbing the end portion of the previous + // history URL and append it to the new history URL. The suffix is assumed to follow the + // ID (numeric) portion of the currentViewPath. + String suffix = currentViewPath.replaceFirst("\D*[^/]*", ""); viewPath += suffix; } } 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 6a7cba9..0d16bea 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 @@ -236,7 +236,6 @@ public class ResourceTreeView extends LocatableVLayout { // get back to this node given the id of the backing group (from the viewpath) autoGroupNodeMap.put(result.getId(), agNode); callback.onSuccess(result); - //renderAutoGroup(result); } }); } else { @@ -302,6 +301,23 @@ public class ResourceTreeView extends LocatableVLayout { } }
+ private void adjustBreadcrumb(TreeNode node, ViewId viewId) { + if (node instanceof ResourceTreeNode) { + Resource nr = ((ResourceTreeNode) node).getResource(); + String display = node.getName() + " <span class="subtitle">" + nr.getResourceType().getName() + "</span>"; + String icon = "types/" + nr.getResourceType().getCategory().getDisplayName() + "_up_16.png"; + + viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); + + } else if (node instanceof AutoGroupTreeNode) { + String name = ((AutoGroupTreeNode) node).getBackingGroupName(); + String display = node.getName() + " <span class="subtitle">" + name + "</span>"; + String icon = "types/" + ((AutoGroupTreeNode) node).getResourceType().getCategory() + "_up_16.png"; + + viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); + } + } + private void showContextMenu(AutoGroupTreeNode agNode) { getAutoGroupBackingGroup(agNode, new AsyncCallback<ResourceGroup>() { public void onFailure(Throwable caught) { @@ -680,23 +696,6 @@ public class ResourceTreeView extends LocatableVLayout { } }
- private void adjustBreadcrumb(TreeNode node, ViewId viewId) { - if (node instanceof ResourceTreeNode) { - - Resource nr = ((ResourceTreeNode) node).getResource(); - String display = node.getName() + " <span class="subtitle">" + nr.getResourceType().getName() + "</span>"; - String icon = "types/" + nr.getResourceType().getCategory().getDisplayName() + "_up_16.png"; - - viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), display, icon, true)); - - } else { - - // if (node.getName() != null) { - // viewId.getBreadcrumbs().add(new Breadcrumb(node.getAttribute("id"), node.getName(), null, true)); - // } - } - } - /*private List<Resource> preload(final List<Resource> lineage) {
final ArrayList<Resource> list = new ArrayList<Resource>(lineage); @@ -730,8 +729,9 @@ public class ResourceTreeView extends LocatableVLayout { currentViewId = viewPath.getCurrent(); String currentViewIdPath = currentViewId.getPath(); if ("AutoGroup".equals(currentViewIdPath)) { - ViewId nextViewId = viewPath.getNext(); - Integer autoGroupId = Integer.parseInt(nextViewId.getPath()); + // Move the currentViewId to the ID portion to play better with other code + currentViewId = viewPath.getNext(); + Integer autoGroupId = Integer.parseInt(currentViewId.getPath()); setSelectedAutoGroup(autoGroupId); } else { Integer resourceId = Integer.parseInt(currentViewId.getPath());
commit c2f5b5363d1023106bc7e12a78999603c4c5f26e Author: Lukas Krejci lkrejci@redhat.com Date: Tue Sep 28 10:39:33 2010 +0200
remove the commented-out portions of the resource upgrade code.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 1b0ed8e..de52cd8 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1232,10 +1232,7 @@ public class InventoryManager extends AgentService implements ContainerService, for (ResourceUpgradeResponse upgradeResponse : serverUpdates) { String resourceKey = upgradeResponse.getUpgradedResourceKey(); String name = upgradeResponse.getUpgradedResourceName(); - //String version = upgradeReport.getNewVersion(); String description = upgradeResponse.getUpgradedResourceDescription(); - //Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); - //Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
//only bother if there's something to upgrade at all on this resource. if (resourceKey != null || name != null || description != null) { @@ -1256,23 +1253,11 @@ public class InventoryManager extends AgentService implements ContainerService, logMessage.append("name, "); }
- //if (version != null) { - // existingResource.setVersion(version); - //} - if (description != null) { existingResource.setDescription(description); logMessage.append("description, "); }
- //if (pluginConfiguration != null) { - // existingResource.setPluginConfiguration(pluginConfiguration); - //} - // - //if (resourceConfiguration != null) { - // existingResource.setResourceConfiguration(resourceConfiguration); - //} - logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [").append( existingResource.toString()).append("]");
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 51287b7..e4cbf03 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -495,10 +495,7 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot
String resourceKey = upgradeRequest.getNewResourceKey(); String name = upgradeRequest.getNewName(); -// String version = upgradeReport.getNewVersion(); String description = upgradeRequest.getNewDescription(); -// Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); -// Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
if (resourceKey != null || name != null || description != null) { StringBuilder logMessage = new StringBuilder("Resource [") @@ -516,38 +513,12 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot } ret.setUpgradedResourceName(resource.getName());
-// if (version != null) { -// changed = updateResourceVersion(resource, version) || changed; -// } - if (allowGenericPropertiesUpgrade && needsUpgrade(resource.getDescription(), description)) { resource.setDescription(description); logMessage.append("description, "); } ret.setUpgradedResourceDescription(resource.getDescription()); - -// if (pluginConfiguration != null) { -// if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { -// log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + -// resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); -// changed = true; -// resource.setPluginConfiguration(pluginConfiguration); -// } -// } -// -// if (resourceConfiguration != null) { -// if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { -// //XXX Will this create a new history entry? -// -// log.info("Resource [" + resource + "] upgraded its resource configuration from [" + -// resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); -// -// changed = true; -// resource.setResourceConfiguration(resourceConfiguration); -// } -// } - - + //finally let's remove the potential previous upgrade error. we've now successfully //upgraded the resource. List<ResourceError> upgradeErrors = resourceManager.findResourceErrors(subjectManager.getOverlord(), resource.getId(), ResourceErrorType.UPGRADE);
commit 0ae5aa90c40d239e294857a961596ee500643dee Author: Lukas Krejci lkrejci@redhat.com Date: Tue Sep 28 10:36:32 2010 +0200
Clear the upgrade errors if the upgrade for given resource succeeds.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index a480fb7..51287b7 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -481,7 +481,7 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot * @param existingResource * @param upgradeRequest * @param allowGenericPropertiesUpgrade name and description are only upgraded if this is true - * @return true if the resource was changed, false otherwise + * @return response to the upgrade request detailing what has been accepted on the server side */ private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeRequest upgradeRequest, boolean allowGenericPropertiesUpgrade) { if (upgradeRequest.getUpgradeErrorMessage() != null) { @@ -547,6 +547,14 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot // } // }
+ + //finally let's remove the potential previous upgrade error. we've now successfully + //upgraded the resource. + List<ResourceError> upgradeErrors = resourceManager.findResourceErrors(subjectManager.getOverlord(), resource.getId(), ResourceErrorType.UPGRADE); + for(ResourceError error : upgradeErrors) { + entityManager.remove(error); + } + logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [").append(resource.toString()).append("]");
commit c1b1f4dfdcf05c39879133c9fb562f8ecada6690 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Sep 24 14:32:23 2010 +0200
Handling the resource upgrade failure by disabling discovery of its siblings of the same type.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 563a786..1b0ed8e 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -192,7 +192,7 @@ public class InventoryManager extends AgentService implements ContainerService, /** * Handles the resource upgrade during the initialization of the inventory manager. */ - private ResourceUpgradeDelegate resourceUpgradeDelegate; + private ResourceUpgradeDelegate resourceUpgradeDelegate = new ResourceUpgradeDelegate(this);
public InventoryManager() { super(DiscoveryAgentService.class); @@ -222,7 +222,6 @@ public class InventoryManager extends AgentService implements ContainerService, //try the resource upgrade before we have any schedulers set up //so that we don't get any interventions from concurrently running //discoveries. - resourceUpgradeDelegate = new ResourceUpgradeDelegate(this); upgradeResources();
availabilityCollectors = new AvailabilityCollectorThreadPool(); @@ -282,15 +281,24 @@ public class InventoryManager extends AgentService implements ContainerService, * an empty set if nothing is discovered. This may return <code>null</code> if for some reason * we could not invoke the discovery component. * + * @param parentResourceContainer the container of the resource under which we are going to execute the discovery * @param component the discovery component that will actually go out and discover resources * @param context the context for use by the discovery component * @return the details of all discovered resources, may be empty or <code>null</code> * * @throws Exception if the discovery component threw an exception */ - public Set<DiscoveredResourceDetails> invokeDiscoveryComponent(ResourceDiscoveryComponent component, + public Set<DiscoveredResourceDetails> invokeDiscoveryComponent(ResourceContainer parentResourceContainer, ResourceDiscoveryComponent component, ResourceDiscoveryContext context) throws Exception {
+ Resource parentResource = parentResourceContainer == null ? null : parentResourceContainer.getResource(); + + if (resourceUpgradeDelegate.hasUpgradeFailedInChildren(parentResource, context.getResourceType())) { + log.debug("Discovery of [" + context.getResourceType() + "] has been disallowed under " + (parentResource == null ? " the platform " : parentResource) + + " because some of its siblings failed to upgrade."); + return null; + } + long timeout = getDiscoveryComponentTimeout(context.getResourceType());
try { @@ -687,7 +695,7 @@ public class InventoryManager extends AgentService implements ContainerService,
// Ask the plugin's discovery component to find the new resource, throwing exceptions if it cannot be // found at all. - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(discoveryComponent, + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentResourceContainer, discoveryComponent, discoveryContext); if ((discoveredResources == null) || discoveredResources.isEmpty()) { log.info("Plugin Error: During manual add, discovery component method [" @@ -1207,7 +1215,7 @@ public class InventoryManager extends AgentService implements ContainerService, return resourceContainer.updateAvailability(availabilityType); }
- public void mergeResourceFromUpgrade(Set<ResourceUpgradeRequest> upgradeRequests) { + public void mergeResourcesFromUpgrade(Set<ResourceUpgradeRequest> upgradeRequests) { Set<ResourceUpgradeResponse> serverUpdates = null; try { ServerServices serverServices = this.configuration.getServerServices(); @@ -1430,6 +1438,13 @@ public class InventoryManager extends AgentService implements ContainerService, @SuppressWarnings("unchecked") public void activateResource(Resource resource, @NotNull ResourceContainer container, boolean updatedPluginConfig) throws InvalidPluginConfigurationException, PluginContainerException { + if (resourceUpgradeDelegate.hasUpgradeFailed(resource)) { + if (log.isTraceEnabled()) { + log.trace("Skipping activation of " + resource + " - it has failed to upgrade."); + } + return; + } + ResourceComponent component = container.getResourceComponent();
// if the component already exists and is started, and the resource's plugin config has not changed, there is @@ -1762,7 +1777,7 @@ public class InventoryManager extends AgentService implements ContainerService, * Shutdown the ResourceComponents from the bottom up. * @param resource The resource to deactivate */ - private void deactivateResource(Resource resource) { + public void deactivateResource(Resource resource) { this.inventoryLock.writeLock().lock(); try { ResourceContainer container = getResourceContainer(resource); @@ -1841,7 +1856,7 @@ public class InventoryManager extends AgentService implements ContainerService, Set<DiscoveredResourceDetails> discoveredResources = null;
try { - discoveredResources = invokeDiscoveryComponent(component, context); + discoveredResources = invokeDiscoveryComponent(null, component, context); } catch (Throwable e) { log.warn("Platform plugin discovery failed - skipping", e); } @@ -2043,6 +2058,13 @@ public class InventoryManager extends AgentService implements ContainerService, } }
+ /** + * @return true if the inventory manager failed to merge the upgrade requests with the server during startup. + */ + public boolean hasUpgradeMergeFailed() { + return resourceUpgradeDelegate.hasUpgradeMergeFailed(); + } + /** * Always use this before accessing the event listeners because this ensures * thread safety. @@ -2171,7 +2193,7 @@ public class InventoryManager extends AgentService implements ContainerService, parentResourceContext, SystemInfoFactory.createSystemInfo(), processScanResults, Collections.EMPTY_LIST, this.configuration.getContainerName(), this.configuration .getPluginContainerDeployment()); - Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(discoveryComponent, context); + Set<DiscoveredResourceDetails> discoveredResources = invokeDiscoveryComponent(parentContainer, discoveryComponent, context); newResources = new HashSet<Resource>(); if ((discoveredResources != null) && (!discoveredResources.isEmpty())) { IdentityHashMap<Configuration, DiscoveredResourceDetails> pluginConfigObjects = new IdentityHashMap<Configuration, DiscoveredResourceDetails>(); @@ -2613,6 +2635,12 @@ public class InventoryManager extends AgentService implements ContainerService,
private void upgradeResources() { try { + + if (!configuration.isInsideAgent()) { + log.debug("Skipping resource upgrade in embedded mode."); + return; + } + log.debug("Executing resource upgrade.");
boolean syncResult = handleReport(new InventoryReport(getAgent()), true); @@ -2622,7 +2650,7 @@ public class InventoryManager extends AgentService implements ContainerService, }
upgradeResource(getPlatform()); - + log.debug("Sending the upgrade requests to the server."); resourceUpgradeDelegate.sendRequests();
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java index 025ba3a..98a897e 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java @@ -19,15 +19,17 @@
package org.rhq.core.pc.upgrade;
+import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.inventory.InventoryManager; @@ -56,7 +58,10 @@ public class ResourceUpgradeDelegate {
private Set<ResourceUpgradeRequest> requests = new HashSet<ResourceUpgradeRequest>(); private InventoryManager inventoryManager; - + private Set<Resource> failedResources = new HashSet<Resource>(); + private Map<Resource, Set<ResourceType>> failedResourceTypesPerParent = new HashMap<Resource, Set<ResourceType>>(); + private boolean mergeFailed; + public ResourceUpgradeDelegate(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; } @@ -88,11 +93,56 @@ public class ResourceUpgradeDelegate { } }
- public void sendRequests() { - if (enabled) { - if (requests.size() > 0) { - inventoryManager.mergeResourceFromUpgrade(requests); - requests.clear(); + /** + * @return true if {@link #sendRequests()} threw an exception, false otherwise + */ + public boolean hasUpgradeMergeFailed() { + return mergeFailed; + } + + /** + * Tells whether given resource had a upgrade failure during the {@link #processAndQueue(ResourceContainer)} invocation. + * + * @param resource the resource to test + * @return true if there was an error upgrading this resource, false otherwise + */ + public boolean hasUpgradeFailed(Resource resource) { + return mergeFailed || failedResources.contains(resource); + } + + /** + * Tells whether at least one of the children with given resource type of the given parent resource + * had an upgrade failure during {@link #processAndQueue(ResourceContainer)} invocation. + * + * @return true if at least one of the children of given type failed to upgrade, false otherwise + */ + public boolean hasUpgradeFailedInChildren(Resource parentResource, ResourceType childrenResourceType) { + if (mergeFailed) { + return true; + } + + Set<ResourceType> failedTypes = failedResourceTypesPerParent.get(parentResource); + + return failedTypes != null && failedTypes.contains(childrenResourceType); + } + + public void sendRequests() throws Throwable { + if (enabled && requests.size() > 0) { + try { + inventoryManager.mergeResourcesFromUpgrade(requests); + } catch (Throwable t) { + mergeFailed = true; + + //deactivate all the resources to be upgraded. We might have a problem + //because they have not been upgraded because the merge failed. + for(ResourceUpgradeRequest request : requests) { + ResourceContainer container = inventoryManager.getResourceContainer(request.getResourceId()); + if (container != null) { + inventoryManager.deactivateResource(container.getResource()); + } + } + + throw t; } } } @@ -157,6 +207,20 @@ public class ResourceUpgradeDelegate { if (request.hasSomethingToUpgrade()) { requests.add(request); } + + if (request.getUpgradeErrorMessage() != null) { + failedResources.add(resource); + + Set<ResourceType> failedResourceTypesInParent = failedResourceTypesPerParent.get(parentResource); + if (failedResourceTypesInParent == null) { + failedResourceTypesInParent = new HashSet<ResourceType>(); + failedResourceTypesPerParent.put(parentResource, failedResourceTypesInParent); + } + + failedResourceTypesInParent.add(resource.getResourceType()); + + inventoryManager.deactivateResource(resource); + } }
private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 244d2f2..1479345 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -237,6 +237,14 @@ public class ResourceUpgradeTest { TestPayload test = new TestPayload() { public void test(Resource resourceUpgradeTestResource) { assertTrue(resourceUpgradeTestResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side."); + + //the discovery of the failed resource mustn't have run + ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(resourceUpgradeTestResource); + File dataDir = container.getResourceContext().getDataDirectory(); + + File marker = new File(dataDir, "failing-discovery-ran"); + + assertFalse(marker.exists(), "The discovery of the resource type with a failed upgraded resource must not be executed but it was."); }
@SuppressWarnings("unchecked") diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java index 54153e6..75bfbd7 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java @@ -19,6 +19,8 @@
package org.rhq.core.pc.upgrade.plugins.failing;
+import java.io.File; +import java.io.IOException; import java.util.Collections; import java.util.Set;
@@ -44,6 +46,20 @@ public class DiscComponent implements ResourceDiscoveryComponent<ResourceCompone
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent> context) throws InvalidPluginConfigurationException, Exception { + + //create a marker file so that the testing code knows this method has run + File dataDir = context.getParentResourceContext().getDataDirectory(); + if (dataDir != null) { + if (!(dataDir.exists())) { + dataDir.mkdir(); + } + File marker = new File(dataDir, "failing-discovery-ran"); + try { + marker.createNewFile(); + } catch (IOException e) { + } + } + return Collections.singleton(new DiscoveredResourceDetails(context.getResourceType(), RESOURCE_KEY, RESOURCE_NAME, null, RESOURCE_DESCRIPTION, context.getDefaultPluginConfiguration(), null)); } diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java index d1894cb..43c2ba5 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java @@ -91,6 +91,7 @@ import org.rhq.core.domain.cloud.composite.FailoverListComposite.ServerEntry; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.PluginContainerConfiguration; import org.rhq.core.pc.ServerServices; +import org.rhq.core.pc.inventory.InventoryManager; import org.rhq.core.pc.plugin.FileSystemPluginFinder; import org.rhq.core.system.SystemInfoFactory; import org.rhq.core.util.ObjectNameFactory; @@ -1591,6 +1592,7 @@ public class AgentMain { * <ul> * <li>Registering with the server (if the agent needs to do so at startup)</li> * <li>Updating the plugins with the latest versions that are found on the server</li> + * <li>Setup a conditional restart of the plugin container, see {@link PluginContainerConditionalRestartListener}</li> * </ul> * * @return <code>true</code> if the agent is not registered or the agent was asked to re-register with the server; @@ -1623,6 +1625,10 @@ public class AgentMain { updatePlugins(); }
+ //the next thing is to setup the conditional restart of the PC if it fails to merge + //the upgrade results with the server due to some network glitch + m_clientSender.addStateListener(new PluginContainerConditionalRestartListener(), false); + return register; }
@@ -3390,6 +3396,42 @@ public class AgentMain { }
/** + * This listener restarts the plugin container upon establishing the connection with the server + * if the following conditions are met: + * <ol> + * <li> The plugin container is started + * <li> It performed the resource upgrade but failed to merge the changes to the server + * </ol> + * By restarting the plugin container in such conditions, we essentially re-run the resource upgrade + * and let the plugin container try to re-merge with the server that we know has just connected. + * + * @author Lukas Krejci + */ + private class PluginContainerConditionalRestartListener implements ClientCommandSenderStateListener { + public boolean startedSending(ClientCommandSender sender) { + try { + InventoryManager inventoryManager = PluginContainer.getInstance().getInventoryManager(); + if (inventoryManager != null && inventoryManager.hasUpgradeMergeFailed()) { + m_output.println(MSG.getMsg(AgentI18NResourceKeys.RESTARTING_PLUGIN_CONTAINER_AFTER_UPGRADE_MERGE_FAILURE)); + LOG.info(AgentI18NResourceKeys.RESTARTING_PLUGIN_CONTAINER_AFTER_UPGRADE_MERGE_FAILURE); + + PluginContainerPromptCommand pcCommand = new PluginContainerPromptCommand(); + pcCommand.execute(AgentMain.this, new String[] { "stop" }); + pcCommand.execute(AgentMain.this, new String[] { "start" }); + } + } catch (Exception e) { + LOG.error("Failed to restart the plugin container when server connection established."); + } + return true; + } + + public boolean stoppedSending(ClientCommandSender sender) { + //do nothing but keep listening + return true; + } + } + + /** * When the agent starts up, it needs to create the communications servers before starting the plugin container; * however, the agent must not process any incoming commands until after the plugin container fully starts. This * command listener will actually block indefinitely all commands from being processed until its told to open the diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java index eb1df86..c28349c 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java @@ -2050,4 +2050,7 @@ public interface AgentI18NResourceKeys {
@I18NMessage("Done.") String AVAILABILITY_REPORT_SENT = "PromptCommand.availability.sent"; + + @I18NMessage("Restarting the plugin container due to previous failure to merge the upgrade results with the server.") + String RESTARTING_PLUGIN_CONTAINER_AFTER_UPGRADE_MERGE_FAILURE = "AgentMain.pc-conditional-restart"; } \ No newline at end of file diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java index 8736f05..1de2dfb 100644 --- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java +++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java @@ -359,7 +359,7 @@ public class DiscoveryPromptCommand implements AgentPromptCommand { PluginContainerDeployment.AGENT);
Set<DiscoveredResourceDetails> discoveredResources; - discoveredResources = inventoryManager.invokeDiscoveryComponent(discoveryComponent, context); + discoveredResources = inventoryManager.invokeDiscoveryComponent(platformContainer, discoveryComponent, context); if (discoveredResources != null) { for (DiscoveredResourceDetails discoveredResource : discoveredResources) { out.println(MSG.getMsg(AgentI18NResourceKeys.DISCOVERY_COMPONENT_RESULT, discoveredResource diff --git a/modules/enterprise/agent/src/test/java/org/rhq/enterprise/agent/PluginContainerConditionalRestart.java b/modules/enterprise/agent/src/test/java/org/rhq/enterprise/agent/PluginContainerConditionalRestart.java new file mode 100644 index 0000000..b88d097 --- /dev/null +++ b/modules/enterprise/agent/src/test/java/org/rhq/enterprise/agent/PluginContainerConditionalRestart.java @@ -0,0 +1,31 @@ +/* + * 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.agent; + +import org.testng.annotations.Test; + +/** + * + * @author Lukas Krejci + */ +@Test +public class PluginContainerConditionalRestart { + //TODO implement +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index 29815cc..95bec5f 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@ -23,7 +23,11 @@ import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+import com.smartgwt.client.data.DSCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.GroupStartOpen; import com.smartgwt.client.widgets.HTMLPane; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Window; @@ -41,43 +45,37 @@ import com.smartgwt.client.widgets.grid.events.CellClickHandler; public class OverviewView extends LocatableVLayout {
private ResourceComposite resourceComposite; - + private OverviewForm form; + private Table errorsGrid; + public OverviewView(String locatorId, ResourceComposite resourceComposite) { super(locatorId); this.resourceComposite = resourceComposite; - } - - @Override - protected void onDraw() { - super.onDraw(); - - setLeft("10%"); - setWidth("80%"); - - if (this.resourceComposite != null) { - onResourceSelected(this.resourceComposite); - } - } - - public void onResourceSelected(ResourceComposite resourceComposite) { - addMember(new OverviewForm(extendLocatorId("form"), resourceComposite)); - buildErrorListGrid(resourceComposite); - } + form = new OverviewForm(extendLocatorId("form"), resourceComposite); + errorsGrid = new Table(extendLocatorId("errors"), "Detected errors", null, null, new String[] { ResourceErrorsDataSource.DETAIL_ID });
- private void buildErrorListGrid(ResourceComposite resourceComposite) { - final Resource resource = resourceComposite.getResource(); - final Table errorsGrid = new Table(extendLocatorId("errors")); + Resource resource = resourceComposite.getResource(); + ResourceErrorsDataSource errors = new ResourceErrorsDataSource(resource.getId());
errorsGrid.setShowFooter(false); -// errorsGrid.getListGrid().setGroupByField(ResourceErrorsDataSource.ERROR_TYPE_ID); -// errorsGrid.getListGrid().setGroupStartOpen(GroupStartOpen.ALL); -// errorsGrid.getListGrid().setShowGroupSummary(true); - - errorsGrid.setDataSource(new ResourceErrorsDataSource(resource.getId())); + errorsGrid.setDataSource(errors);
- //hide only works after we set the datasource - errorsGrid.getListGrid().hideField(ResourceErrorsDataSource.DETAIL_ID); + form.setHeight("*"); + errorsGrid.setHeight("10%");
+ addMember(form); + addMember(errorsGrid); + + } + + @Override + public void onInit() { + super.onInit(); + initErrorsGrid(); + } + + private void initErrorsGrid() { + errorsGrid.setTooltip("Click on the rows to see the error details."); errorsGrid.getListGrid().addCellClickHandler(new CellClickHandler() { public void onCellClick(CellClickEvent event) { ListGridRecord record = event.getRecord(); @@ -113,7 +111,5 @@ public class OverviewView extends LocatableVLayout { w.show(); } }); - - addMember(errorsGrid); } }
commit 34483f9ca83545ab317caf12545531ab5d9b31e9 Merge: b9e1f2c... 24ba997... Author: Lukas Krejci lkrejci@redhat.com Date: Mon Sep 20 16:58:46 2010 +0200
Merge branch 'master' into resource-upgrade
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java index 074b3c9,0000000..2479c87 mode 100644,000000..100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java @@@ -1,298 -1,0 +1,299 @@@ +/* + * 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.inventory.resource.detail.summary; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.List; + +import org.rhq.core.domain.measurement.DataType; +import org.rhq.core.domain.measurement.DisplayType; +import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; +import org.rhq.enterprise.gui.coregui.client.components.form.TogglableTextItem; +import org.rhq.enterprise.gui.coregui.client.components.form.ValueUpdatedHandler; +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.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.util.SC; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.HeaderItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; + +/** + * The Resource Summary>Overview tab, the form with resource data. + * + * @author Greg Hinkle + * @author Ian Springer + */ +public class OverviewForm extends EnhancedDynamicForm { + + private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); + private ResourceComposite resourceComposite; + - public OverviewForm(ResourceComposite resourceComposite) { ++ public OverviewForm(String locatorId, ResourceComposite resourceComposite) { ++ super(locatorId); + this.resourceComposite = resourceComposite; + } + + @Override + protected void onDraw() { + super.onDraw(); + + setLeft("10%"); + setWidth("80%"); + + if (this.resourceComposite != null) { + setResource(this.resourceComposite); + } + } + + public void setResource(ResourceComposite resourceComposite) { + + this.resourceComposite = resourceComposite; + Resource resource = resourceComposite.getResource(); + + // Load metric defs. + ResourceTypeRepository.Cache.getInstance().getResourceTypes(resource.getResourceType().getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.measurements), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + try { + buildForm(type); + loadTraitValues(); + } catch (Exception e) { + SC.say("Form load failure"); + e.printStackTrace(); + } + } + }); + } + + private void loadTraitValues() { + final Resource resource = resourceComposite.getResource(); + GWTServiceLookup.getMeasurementDataService().findCurrentTraitsForResource( + resource.getId(), + DisplayType.SUMMARY, + new AsyncCallback<List<MeasurementDataTrait>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load traits for " + resource + ".", + caught); + } + + public void onSuccess(List<MeasurementDataTrait> result) { + // TODO: Implement this method. + for (MeasurementDataTrait trait : result) { + String formId = trait.getName().replaceAll("\.", "_").replaceAll(" ", "__"); + FormItem item = getItem(formId); + + if (item != null) { + setValue(formId, trait.getValue()); + } + } + markForRedraw(); + } + } + ); + + } + + private void buildForm(ResourceType type) { + List<MeasurementDefinition> traits = new ArrayList<MeasurementDefinition>(); + + for (MeasurementDefinition measurement : type.getMetricDefinitions()) { + if (measurement.getDataType() == DataType.TRAIT && measurement.getDisplayType() == DisplayType.SUMMARY) { + traits.add(measurement); + } + } + + Collections.sort(traits, new Comparator<MeasurementDefinition>() { + public int compare(MeasurementDefinition o1, MeasurementDefinition o2) { + return new Integer(o1.getDisplayOrder()).compareTo(o2.getDisplayOrder()); + } + }); + + List<FormItem> formItems = new ArrayList<FormItem>(); + + HeaderItem headerItem = new HeaderItem("header", "Summary"); + headerItem.setValue("Summary"); + formItems.add(headerItem); + + StaticTextItem typeItem = new StaticTextItem("type", "Type"); + typeItem.setTooltip("Plugin: " + type.getPlugin() + "\n<br>" + "Type: " + type.getName()); + typeItem.setValue(type.getName() + " (" + type.getPlugin() + ")"); + formItems.add(typeItem); + + final Resource resource = this.resourceComposite.getResource(); + boolean modifiable = this.resourceComposite.getResourcePermission().isInventory(); + + final FormItem nameItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + nameItem.setName("name"); + nameItem.setTitle("Name"); + nameItem.setValue(resource.getName()); + if (nameItem instanceof TogglableTextItem) { + TogglableTextItem togglableNameItem = (TogglableTextItem) nameItem; + togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newName) { + final String oldName = resource.getName(); + if (newName.equals(oldName)) { + return; + } + resource.setName(newName); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change name of Resource with id " + + resource.getId() + + " from "" + oldName + "" to "" + newName + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setName(oldName); + nameItem.setValue(oldName); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Name of Resource with id " + + resource.getId() + " was changed from "" + + oldName + "" to "" + newName + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(nameItem); + + final FormItem descriptionItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + descriptionItem.setName("description"); + descriptionItem.setTitle("Description"); + descriptionItem.setValue(resource.getDescription()); + if (descriptionItem instanceof TogglableTextItem) { + TogglableTextItem togglableDescriptionItem = (TogglableTextItem) descriptionItem; + togglableDescriptionItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newDescription) { + final String oldDescription = resource.getDescription(); + if (newDescription.equals(oldDescription)) { + return; + } + resource.setDescription(newDescription); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change description of Resource with id " + + resource.getId() + + " from "" + oldDescription + "" to "" + newDescription + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setDescription(oldDescription); + descriptionItem.setValue(oldDescription); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Description of Resource with id " + + resource.getId() + " was changed from "" + + oldDescription + "" to "" + newDescription + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(descriptionItem); + + final FormItem locationItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + locationItem.setName("location"); + locationItem.setTitle("Location"); + locationItem.setValue(resource.getLocation()); + if (locationItem instanceof TogglableTextItem) { + TogglableTextItem togglableNameItem = (TogglableTextItem) locationItem; + togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newLocation) { + final String oldLocation = resource.getLocation(); + if (newLocation.equals(oldLocation)) { + return; + } + resource.setLocation(newLocation); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change location of Resource with id " + + resource.getId() + + " from "" + oldLocation + "" to "" + newLocation + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setLocation(oldLocation); + locationItem.setValue(oldLocation); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Location of Resource with id " + + resource.getId() + " was changed from "" + + oldLocation + "" to "" + newLocation + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(locationItem); + + + StaticTextItem versionItem = new StaticTextItem("version", "Version"); + formItems.add(versionItem); + + StaticTextItem parentItem = new StaticTextItem("parent", "Parent"); + formItems.add(parentItem); + + for (MeasurementDefinition trait : traits) { + String id = trait.getDisplayName().replaceAll("\.", "_").replaceAll(" ", "__"); + + StaticTextItem item = new StaticTextItem(id, trait.getDisplayName()); + item.setTooltip(trait.getDescription()); + formItems.add(item); +// item.setValue("?"); + } + +// SectionItem section = new SectionItem("Summary", "Summary"); +// section.setTitle("Summary"); +// section.setDefaultValue("Summary"); +// section.setCanCollapse(true); +// section.setCellStyle("HidablePlainSectionHeader"); +// section.setItemIds(itemIds.toArray(new String[itemIds.size()])); +// formItems.add(0, section); + + formItems.add(new SpacerItem()); + setItems(formItems.toArray(new FormItem[formItems.size()])); + + setValue("type", type.getName() + " (" + type.getPlugin() + ")"); + setValue("name", resource.getName()); + setValue("description", resource.getDescription()); + setValue("location", resource.getLocation()); + setValue("version", (resource.getVersion() != null) ? resource.getVersion() : "<i>none</i>"); + Resource parentResource = resource.getParentResource(); + setValue("parent", parentResource != null ? + ("<a href="#Resource/" + parentResource.getId() + "">" + + parentResource.getName() + "</a>") : "<i>none</i>"); + } +} diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index 10bde5b,4cf2119..29815cc --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@@ -18,31 -18,49 +18,32 @@@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary;
-import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.List; - -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.util.SC; -import com.smartgwt.client.widgets.form.fields.FormItem; -import com.smartgwt.client.widgets.form.fields.HeaderItem; -import com.smartgwt.client.widgets.form.fields.SpacerItem; -import com.smartgwt.client.widgets.form.fields.StaticTextItem; - -import org.rhq.core.domain.measurement.DataType; -import org.rhq.core.domain.measurement.DisplayType; -import org.rhq.core.domain.measurement.MeasurementDataTrait; -import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.composite.ResourceComposite; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; -import org.rhq.enterprise.gui.coregui.client.components.form.TogglableTextItem; -import org.rhq.enterprise.gui.coregui.client.components.form.ValueUpdatedHandler; -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.ResourceSelectListener; -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.components.table.Table; ++import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout; + +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.widgets.HTMLPane; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.grid.ListGridRecord; +import com.smartgwt.client.widgets.grid.events.CellClickEvent; +import com.smartgwt.client.widgets.grid.events.CellClickHandler; - import com.smartgwt.client.widgets.layout.VLayout;
/** * The Resource Summary>Overview tab. * - * @author Greg Hinkle - * @author Ian Springer + * @author Lukas Krejci */ - public class OverviewView extends VLayout { -public class OverviewView extends EnhancedDynamicForm implements ResourceSelectListener { ++public class OverviewView extends LocatableVLayout {
- private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); private ResourceComposite resourceComposite;
- public OverviewView(ResourceComposite resourceComposite) { + public OverviewView(String locatorId, ResourceComposite resourceComposite) { + super(locatorId); this.resourceComposite = resourceComposite; }
@@@ -59,60 -77,218 +60,60 @@@ }
public void onResourceSelected(ResourceComposite resourceComposite) { - addMember(new OverviewForm(resourceComposite)); - - this.resourceComposite = resourceComposite; - Resource resource = resourceComposite.getResource(); - - // Load metric defs. - ResourceTypeRepository.Cache.getInstance().getResourceTypes(resource.getResourceType().getId(), - EnumSet.of(ResourceTypeRepository.MetadataType.measurements), - new ResourceTypeRepository.TypeLoadedCallback() { - public void onTypesLoaded(ResourceType type) { - try { - buildForm(type); - loadTraitValues(); - } catch (Exception e) { - SC.say("Form load failure"); - e.printStackTrace(); - } - } - }); ++ addMember(new OverviewForm(extendLocatorId("form"), resourceComposite)); + buildErrorListGrid(resourceComposite); }
- private void loadTraitValues() { + private void buildErrorListGrid(ResourceComposite resourceComposite) { final Resource resource = resourceComposite.getResource(); - Table errorsGrid = new Table("Errors"); - GWTServiceLookup.getMeasurementDataService().findCurrentTraitsForResource(resource.getId(), - DisplayType.SUMMARY, new AsyncCallback<List<MeasurementDataTrait>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load traits for " + resource + ".", caught); - } - - public void onSuccess(List<MeasurementDataTrait> result) { - // TODO: Implement this method. - for (MeasurementDataTrait trait : result) { - String formId = trait.getName().replaceAll("\.", "_").replaceAll(" ", "__"); - FormItem item = getItem(formId); - - if (item != null) { - setValue(formId, trait.getValue()); - } ++ final Table errorsGrid = new Table(extendLocatorId("errors")); + + errorsGrid.setShowFooter(false); +// errorsGrid.getListGrid().setGroupByField(ResourceErrorsDataSource.ERROR_TYPE_ID); +// errorsGrid.getListGrid().setGroupStartOpen(GroupStartOpen.ALL); +// errorsGrid.getListGrid().setShowGroupSummary(true); + + errorsGrid.setDataSource(new ResourceErrorsDataSource(resource.getId())); + + //hide only works after we set the datasource + errorsGrid.getListGrid().hideField(ResourceErrorsDataSource.DETAIL_ID); + + errorsGrid.getListGrid().addCellClickHandler(new CellClickHandler() { + public void onCellClick(CellClickEvent event) { + ListGridRecord record = event.getRecord(); + final Window w = new Window(); + w.setTitle("Error Details"); + w.setIsModal(true); + w.setShowMinimizeButton(false); + w.setShowModalMask(true); + w.setWidth(640); + w.setHeight(480); + w.centerInPage(); + w.setCanDragResize(true); + - VLayout layout = new VLayout(10); ++ LocatableVLayout layout = new LocatableVLayout(errorsGrid.extendLocatorId("dialogLayout"), 10); + layout.setDefaultLayoutAlign(Alignment.CENTER); + layout.setLayoutMargin(10); + + w.addItem(layout); + + HTMLPane details = new HTMLPane(); + details.setContents("<pre>" + record.getAttribute(ResourceErrorsDataSource.DETAIL_ID) + "</pre>"); + layout.addMember(details); + + IButton ok = new IButton("Ok"); + ok.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent event) { + w.destroy(); } - markForRedraw(); - } - }); - - } - - private void buildForm(ResourceType type) { - List<MeasurementDefinition> traits = new ArrayList<MeasurementDefinition>(); - - for (MeasurementDefinition measurement : type.getMetricDefinitions()) { - if (measurement.getDataType() == DataType.TRAIT && measurement.getDisplayType() == DisplayType.SUMMARY) { - traits.add(measurement); - } - } - - Collections.sort(traits, new Comparator<MeasurementDefinition>() { - public int compare(MeasurementDefinition o1, MeasurementDefinition o2) { - return new Integer(o1.getDisplayOrder()).compareTo(o2.getDisplayOrder()); + }); + + layout.addMember(ok); + + w.show(); } }); - - List<FormItem> formItems = new ArrayList<FormItem>(); - - HeaderItem headerItem = new HeaderItem("header", "Summary"); - headerItem.setValue("Summary"); - formItems.add(headerItem); - - StaticTextItem typeItem = new StaticTextItem("type", "Type"); - typeItem.setTooltip("Plugin: " + type.getPlugin() + "\n<br>" + "Type: " + type.getName()); - typeItem.setValue(type.getName() + " (" + type.getPlugin() + ")"); - formItems.add(typeItem); - - final Resource resource = this.resourceComposite.getResource(); - boolean modifiable = this.resourceComposite.getResourcePermission().isInventory(); - - final FormItem nameItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - nameItem.setName("name"); - nameItem.setTitle("Name"); - nameItem.setValue(resource.getName()); - if (nameItem instanceof TogglableTextItem) { - TogglableTextItem togglableNameItem = (TogglableTextItem) nameItem; - togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newName) { - final String oldName = resource.getName(); - if (newName.equals(oldName)) { - return; - } - resource.setName(newName); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - "Failed to change name of Resource with id " + resource.getId() + " from "" + oldName - + "" to "" + newName + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setName(oldName); - nameItem.setValue(oldName); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Name of Resource with id " + resource.getId() + " was changed from "" - + oldName + "" to "" + newName + "".", Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(nameItem); - - final FormItem descriptionItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - descriptionItem.setName("description"); - descriptionItem.setTitle("Description"); - descriptionItem.setValue(resource.getDescription()); - if (descriptionItem instanceof TogglableTextItem) { - TogglableTextItem togglableDescriptionItem = (TogglableTextItem) descriptionItem; - togglableDescriptionItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newDescription) { - final String oldDescription = resource.getDescription(); - if (newDescription.equals(oldDescription)) { - return; - } - resource.setDescription(newDescription); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - "Failed to change description of Resource with id " + resource.getId() + " from "" - + oldDescription + "" to "" + newDescription + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setDescription(oldDescription); - descriptionItem.setValue(oldDescription); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Description of Resource with id " + resource.getId() - + " was changed from "" + oldDescription + "" to "" + newDescription + "".", - Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(descriptionItem); - - final FormItem locationItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - locationItem.setName("location"); - locationItem.setTitle("Location"); - locationItem.setValue(resource.getLocation()); - if (locationItem instanceof TogglableTextItem) { - TogglableTextItem togglableNameItem = (TogglableTextItem) locationItem; - togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newLocation) { - final String oldLocation = resource.getLocation(); - if (newLocation.equals(oldLocation)) { - return; - } - resource.setLocation(newLocation); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError( - "Failed to change location of Resource with id " + resource.getId() + " from "" - + oldLocation + "" to "" + newLocation + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setLocation(oldLocation); - locationItem.setValue(oldLocation); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify( - new Message("Location of Resource with id " + resource.getId() + " was changed from "" - + oldLocation + "" to "" + newLocation + "".", Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(locationItem); - - StaticTextItem versionItem = new StaticTextItem("version", "Version"); - formItems.add(versionItem); - - StaticTextItem parentItem = new StaticTextItem("parent", "Parent"); - formItems.add(parentItem); - - for (MeasurementDefinition trait : traits) { - String id = trait.getDisplayName().replaceAll("\.", "_").replaceAll(" ", "__"); - - StaticTextItem item = new StaticTextItem(id, trait.getDisplayName()); - item.setTooltip(trait.getDescription()); - formItems.add(item); - // item.setValue("?"); - } - - // SectionItem section = new SectionItem("Summary", "Summary"); - // section.setTitle("Summary"); - // section.setDefaultValue("Summary"); - // section.setCanCollapse(true); - // section.setCellStyle("HidablePlainSectionHeader"); - // section.setItemIds(itemIds.toArray(new String[itemIds.size()])); - // formItems.add(0, section); - - formItems.add(new SpacerItem()); - setItems(formItems.toArray(new FormItem[formItems.size()])); - - setValue("type", type.getName() + " (" + type.getPlugin() + ")"); - setValue("name", resource.getName()); - setValue("description", resource.getDescription()); - setValue("location", resource.getLocation()); - setValue("version", (resource.getVersion() != null) ? resource.getVersion() : "<i>none</i>"); - Resource parentResource = resource.getParentResource(); - setValue("parent", parentResource != null ? ("<a href="#Resource/" + parentResource.getId() + "">" - + parentResource.getName() + "</a>") : "<i>none</i>"); + + addMember(errorsGrid); } } diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java index 267b0f1,dd5e77b..4ac0f61 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java @@@ -225,8 -226,18 +227,22 @@@ public abstract class RPCDataSource<T> addField(field); } } + + public void addFields(DataSourceField... fields) { + addFields(Arrays.asList(fields)); + } + + public ListGridRecord getEditedRecord(DSRequest request) { + // Retrieving values before edit + JavaScriptObject oldValues = request.getAttributeAsJavaScriptObject("oldValues"); + // Creating new record for combining old values with changes + ListGridRecord newRecord = new ListGridRecord(); + // Copying properties from old record + JSOHelper.apply(oldValues, newRecord.getJsObj()); + // Retrieving changed values + JavaScriptObject data = request.getData(); + // Apply changes + JSOHelper.apply(data, newRecord.getJsObj()); + return newRecord; + } }
commit b9e1f2c995a66a147793c72dbeb13df7c162128e Merge: 0cd6acd... e5fac0a... Author: Lukas Krejci lkrejci@redhat.com Date: Tue Sep 14 18:33:01 2010 +0200
Merge branch 'master' into resource-upgrade
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index c06d0c2,b282e41..5990b60 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@@ -28,7 -28,8 +28,9 @@@ import org.rhq.core.domain.configuratio import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceError; + import org.rhq.core.domain.resource.composite.DisambiguationReport; + import org.rhq.core.domain.resource.composite.ProblemResourceComposite; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.util.PageControl; @@@ -65,7 -68,5 +69,7 @@@ public interface ResourceGWTService ext void ignoreResources(Integer[] resourceIds);
void unignoreResources(Integer[] resourceIds); + + List<ResourceError> findResourceErrors(int resourceId);
--} ++} diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index e63978a,ac2abc2..10bde5b --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@@ -18,33 -18,50 +18,31 @@@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary;
-import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.List; - -import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.util.SC; -import com.smartgwt.client.widgets.form.fields.FormItem; -import com.smartgwt.client.widgets.form.fields.HeaderItem; -import com.smartgwt.client.widgets.form.fields.SpacerItem; -import com.smartgwt.client.widgets.form.fields.StaticTextItem; - -import org.rhq.core.domain.measurement.DataType; -import org.rhq.core.domain.measurement.DisplayType; -import org.rhq.core.domain.measurement.MeasurementDataTrait; -import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.composite.ResourceComposite; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; -import org.rhq.enterprise.gui.coregui.client.components.form.TogglableTextItem; -import org.rhq.enterprise.gui.coregui.client.components.form.ValueUpdatedHandler; -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.ResourceSelectListener; -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.components.table.Table; - import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener; + +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.widgets.HTMLPane; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; +import com.smartgwt.client.widgets.grid.ListGridRecord; +import com.smartgwt.client.widgets.grid.events.CellClickEvent; +import com.smartgwt.client.widgets.grid.events.CellClickHandler; +import com.smartgwt.client.widgets.layout.VLayout;
/** * The Resource Summary>Overview tab. * - * @author Greg Hinkle - * @author Ian Springer + * @author Lukas Krejci */ - public class OverviewView extends VLayout implements ResourceSelectListener { -public class OverviewView extends EnhancedDynamicForm implements ResourceSelectListener { ++public class OverviewView extends VLayout {
- private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); private ResourceComposite resourceComposite;
- public OverviewView(ResourceComposite resourceComposite) { -- super(); this.resourceComposite = resourceComposite; }
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java index 4f3f3ce,cb2768f..267b0f1 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java @@@ -18,9 -18,10 +18,11 @@@ */ package org.rhq.enterprise.gui.coregui.client.util;
+import java.util.Arrays; + import java.util.ArrayList; import java.util.Collection; import java.util.List; + import java.util.Map;
import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@@ -183,11 -221,7 +222,11 @@@ public abstract class RPCDataSource<T> */ public void addFields(List<DataSourceField> fields) { for (DataSourceField field : fields) { - addField(field); + addField(field); } } + + public void addFields(DataSourceField... fields) { + addFields(Arrays.asList(fields)); + } } diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index b933248,25b19b0..6db01f8 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@@ -35,7 -35,8 +35,9 @@@ import org.rhq.core.domain.configuratio import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceError; + import org.rhq.core.domain.resource.composite.DisambiguationReport; + import org.rhq.core.domain.resource.composite.ProblemResourceComposite; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.util.PageControl; @@@ -215,9 -239,5 +240,9 @@@ public class ResourceGWTServiceImpl ext public void unignoreResources(Integer[] resourceIds) { discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); } - -} + + public List<ResourceError> findResourceErrors(int resourceId) { + return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), + "ResourceService.getResourceErrors"); + } - } ++}
commit 0cd6acd2fe93a35a9b2cdbde0828c416ac49f67d Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 24 17:48:01 2010 +0200
Make tests work with the changed test plugin jars location, added tests for upgrade failure reporting.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java index 19c1d95..adb3989 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -43,6 +43,8 @@ import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.discovery.ResourceSyncInfo; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceError; +import org.rhq.core.domain.resource.ResourceErrorType; import org.rhq.core.domain.resource.ResourceType;
/** @@ -137,6 +139,11 @@ public class FakeServerInventory { resource.setResourceKey(request.getNewResourceKey()); }
+ if (request.getUpgradeErrorMessage() != null) { + ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, request.getUpgradeErrorMessage(), request.getUpgradeErrorStackTrace(), request.getTimestamp()); + resource.getResourceErrors().add(error); + } + ResourceUpgradeResponse resp = new ResourceUpgradeResponse(); resp.setResourceId(resource.getId()); resp.setUpgradedResourceName(resource.getName()); diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 202e0c0..244d2f2 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -69,8 +69,9 @@ import org.rhq.core.pc.plugin.FileSystemPluginFinder; @Test(sequential = true, invocationCount = 1) public class ResourceUpgradeTest {
- private static final String PLUGIN_V1_FILENAME = "resource-upgrade-test-plugin-1.0.0.jar"; - private static final String PLUGIN_V2_FILENAME = "resource-upgrade-test-plugin-2.0.0.jar"; + private static final String PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-1.0.0.jar"; + private static final String PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-2.0.0.jar"; + private static final String FAILING_PLUGIN_FILE_NAME = "/resource-upgrade-test-plugin-3.0.0.jar";
private static final String PLUGINS_DIR_NAME = "plugins"; private static final String DATA_DIR_NAME = "data"; @@ -101,6 +102,7 @@ public class ResourceUpgradeTest { public void sanityCheck() { verifyPluginExists(PLUGIN_V1_FILENAME); verifyPluginExists(PLUGIN_V2_FILENAME); + verifyPluginExists(FAILING_PLUGIN_FILE_NAME); }
@BeforeClass(dependsOnMethods = "sanityCheck") @@ -227,6 +229,35 @@ public class ResourceUpgradeTest { executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, test); }
+ @Test + public void testUpgradeFailureHandling() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + initialSyncAndDiscovery(InventoryStatus.COMMITTED); + + TestPayload test = new TestPayload() { + public void test(Resource resourceUpgradeTestResource) { + assertTrue(resourceUpgradeTestResource.getResourceErrors().size() > 0, "There should be upgrade errors persisted on the server side."); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + will(currentServerSideInventory.upgradeResources()); + } + }; + } + }; + + executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), false, test); + } + private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { cleanDataDir(); executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), true, new TestPayload() {
commit 90b602f22c280ee63deb7e51470db1fcda9b79a1 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 24 17:46:58 2010 +0200
Final touches on the Server side error reporting.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index cc63040..e63978a 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@ -24,7 +24,6 @@ import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener;
import com.smartgwt.client.types.Alignment; -import com.smartgwt.client.types.GroupStartOpen; import com.smartgwt.client.widgets.HTMLPane; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Window; @@ -33,7 +32,6 @@ import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.grid.events.CellClickEvent; import com.smartgwt.client.widgets.grid.events.CellClickHandler; -import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
/** @@ -92,9 +90,10 @@ public class OverviewView extends VLayout implements ResourceSelectListener { w.setWidth(640); w.setHeight(480); w.centerInPage(); + w.setCanDragResize(true);
VLayout layout = new VLayout(10); - layout.setLayoutAlign(Alignment.CENTER); + layout.setDefaultLayoutAlign(Alignment.CENTER); layout.setLayoutMargin(10);
w.addItem(layout); @@ -109,7 +108,6 @@ public class OverviewView extends VLayout implements ResourceSelectListener { w.destroy(); } }); - ok.setAlign(Alignment.CENTER);
layout.addMember(ok);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java index 4957fc7..1843f2b 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java @@ -90,7 +90,7 @@ public class ResourceErrorsDataSource extends RPCDataSource<ResourceError> { ListGridRecord record = new ListGridRecord();
record.setAttribute(DETAIL_ID, from.getDetail()); - record.setAttribute(ERROR_TYPE_ID, from.getErrorType()); + record.setAttribute(ERROR_TYPE_ID, from.getErrorType().toString()); record.setAttribute(SUMMARY_ID, from.getSummary()); record.setAttribute(TIME_OCCURED_ID, new Date(from.getTimeOccurred()));
commit f0b6cda14af2bce898dd6af66b4bb2627a836d72 Merge: d689f70... 66234db... Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 24 13:25:05 2010 +0200
Merge branch 'master' into resource-upgrade
diff --cc modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java index 1ea9630,950d28c..4f3f3ce --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java @@@ -18,8 -18,8 +18,9 @@@ */ package org.rhq.enterprise.gui.coregui.client.util;
+import java.util.Arrays; import java.util.Collection; + import java.util.List;
import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; @@@ -172,13 -173,16 +174,20 @@@ public abstract class RPCDataSource<T> return response; }
- public void addFields(Collection<DataSourceField> fields) { + /** + * Add the specified fields to this data source. When the data source is associated with a + * {@link com.smartgwt.client.widgets.grid.ListGrid}, the fields will be displayed in the order they are specified + * here. + * + * @param fields the fields to be added + */ + public void addFields(List<DataSourceField> fields) { for (DataSourceField field : fields) { - addField(field); + addField(field); } } + + public void addFields(DataSourceField... fields) { + addFields(Arrays.asList(fields)); + } }
commit d689f70de060cdb776cea923f759f0e5de226955 Author: Lukas Krejci lkrejci@redhat.com Date: Tue Aug 24 13:17:24 2010 +0200
Upgrade errors (and other resource errors) shown in the summary tab. Not everything seems to work yet.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java index 9532920..aca9c90 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java @@ -41,7 +41,7 @@ public class ResourceUpgradeRequest extends ResourceUpgradeReport { private String upgradeErrorMessage; private String upgradeErrorStackTrace; private long timestamp; - + public ResourceUpgradeRequest(int resourceId) { this.resourceId = resourceId; } @@ -74,14 +74,37 @@ public class ResourceUpgradeRequest extends ResourceUpgradeReport { public long getTimestamp() { return timestamp; } - + public void setTimestamp(long timestamp) { this.timestamp = timestamp; } - + public void setErrorProperties(Throwable t) { - upgradeErrorMessage = t.getMessage(); + upgradeErrorMessage = null; + upgradeErrorStackTrace = null; + + //first try to extract an error message from the exception + //or some of its parents + Throwable p = t; + while (upgradeErrorMessage == null && p != null) { + upgradeErrorMessage = p.getMessage(); + if (upgradeErrorMessage == null) { + upgradeErrorMessage = p.getLocalizedMessage(); + } + p = p.getCause(); + } + + //ok, we have no error messages. But we have to supply something + //as the message, so let's use the class name as a last resort. + if (upgradeErrorMessage == null) { + if (t.getClass().getCanonicalName() != null) { + upgradeErrorMessage = t.getClass().getCanonicalName(); + } else if (t.getClass().getName() != null) { + upgradeErrorMessage = t.getClass().getName(); + } + }
+ //print the stack trace into a string StringWriter string = new StringWriter(); PrintWriter w = new PrintWriter(string); t.printStackTrace(w); diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java index 8fdc2f7..6630d4b 100644 --- a/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java +++ b/modules/core/domain/src/test/java/org/rhq/core/domain/resource/test/ResourceErrorTest.java @@ -92,7 +92,7 @@ public class ResourceErrorTest extends AbstractEJB3Test { q.setParameter("resourceId", newResource.getId()); assert q.getResultList().size() == 2;
- q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE); + q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPES); q.setParameter("resourceId", newResource.getId()); q.setParameter("errorType", ResourceErrorType.INVALID_PLUGIN_CONFIGURATION); assert q.getResultList().size() == 2; @@ -129,7 +129,7 @@ public class ResourceErrorTest extends AbstractEJB3Test { assert errors.get(0).getDetail().equals("test detail"); assert errors.get(0).getTimeOccurred() == 12345;
- q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPE); + q = em.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID_AND_ERROR_TYPES); q.setParameter("resourceId", newResource.getId()); q.setParameter("errorType", ResourceErrorType.INVALID_PLUGIN_CONFIGURATION); errors = q.getResultList(); diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index a4ca249..4b09ef8 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -163,26 +163,39 @@ <id>process-test-classes</id> <phase>process-test-classes</phase> <configuration> - <tasks> - <echo>Assembling the two resource upgrade test plugins</echo> - <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v1/META-INF"> + <tasks unless="maven.test.skip"> + <echo>Assembling the resource upgrade test plugins</echo> + <copy toDir="${project.build.testOutputDirectory}/tmp/v1/META-INF"> <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml" /> </copy> - <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar"> - <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v1" includes="*.class,**/rhq-plugin.xml" /> + <copy toDir="${project.build.testOutputDirectory}/tmp/v1/org/rhq/core/pc/upgrade/plugins/v1"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v1/*.class" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/v1" includes="**/*.class,**/rhq-plugin.xml" /> </jar> - <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2/META-INF"> + + <copy toDir="${project.build.testOutputDirectory}/tmp/v2/META-INF"> <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml" /> </copy> - <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar"> - <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2" includes="*.class,**/rhq-plugin.xml" /> + <copy toDir="${project.build.testOutputDirectory}/tmp/v2/org/rhq/core/pc/upgrade/plugins/v2"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2/*.class" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/v2" includes="**/*.class,**/rhq-plugin.xml" /> </jar> - <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/failing/META-INF"> + + <copy toDir="${project.build.testOutputDirectory}/tmp/failing/META-INF"> <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml" /> </copy> - <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-3.0.0.jar"> - <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/failing" includes="*.class,**/rhq-plugin.xml" /> + <copy toDir="${project.build.testOutputDirectory}/tmp/failing/org/rhq/core/pc/upgrade/plugins/failing"> + <fileset file="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/failing/*.class" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/resource-upgrade-test-plugin-3.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/tmp/failing" includes="**/*.class,**/rhq-plugin.xml" /> </jar> + + <delete dir="${project.build.testOutputDirectory}/tmp"/> </tasks> </configuration> <goals> diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java index f92e7d5..c06d0c2 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/gwt/ResourceGWTService.java @@ -28,6 +28,7 @@ import org.rhq.core.domain.configuration.Configuration; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.util.PageControl; @@ -64,5 +65,7 @@ public interface ResourceGWTService extends RemoteService { void ignoreResources(Integer[] resourceIds);
void unignoreResources(Integer[] resourceIds); + + List<ResourceError> findResourceErrors(int resourceId);
} \ No newline at end of file diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index 2fff538..cc63040 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@ -18,20 +18,22 @@ */ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary;
-import java.util.ArrayList; -import java.util.List; - import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.components.table.Table; import org.rhq.enterprise.gui.coregui.client.inventory.resource.ResourceSelectListener;
-import com.smartgwt.client.util.SC; -import com.smartgwt.client.widgets.grid.ListGrid; -import com.smartgwt.client.widgets.grid.ListGridField; +import com.smartgwt.client.types.Alignment; +import com.smartgwt.client.types.GroupStartOpen; +import com.smartgwt.client.widgets.HTMLPane; +import com.smartgwt.client.widgets.IButton; +import com.smartgwt.client.widgets.Window; +import com.smartgwt.client.widgets.events.ClickEvent; +import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.grid.ListGridRecord; -import com.smartgwt.client.widgets.grid.events.RecordClickEvent; -import com.smartgwt.client.widgets.grid.events.RecordClickHandler; +import com.smartgwt.client.widgets.grid.events.CellClickEvent; +import com.smartgwt.client.widgets.grid.events.CellClickHandler; +import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.VLayout;
/** @@ -62,41 +64,59 @@ public class OverviewView extends VLayout implements ResourceSelectListener {
public void onResourceSelected(ResourceComposite resourceComposite) { addMember(new OverviewForm(resourceComposite)); - ListGrid errorsGrid = buildErrorListGrid(resourceComposite); - if (errorsGrid != null) { - addMember(errorsGrid); - } + buildErrorListGrid(resourceComposite); }
- private static ListGrid buildErrorListGrid(ResourceComposite resourceComposite) { + private void buildErrorListGrid(ResourceComposite resourceComposite) { final Resource resource = resourceComposite.getResource(); - ListGrid errorsGrid = null; - if (resource.getResourceErrors() != null && resource.getResourceErrors().size() > 0) { - errorsGrid = new ListGrid(); - - ListGridField summaryField = new ListGridField("summary", "Errors"); - summaryField.addRecordClickHandler(new RecordClickHandler() { - - @Override - public void onRecordClick(RecordClickEvent event) { - String detail = event.getRecord().getAttribute("detail"); - SC.say("Error details", detail); - } - }); - - errorsGrid.setFields(summaryField); - - List<ListGridRecord> errorList = new ArrayList<ListGridRecord>(); - for (ResourceError error : resource.getResourceErrors()) { - ListGridRecord record = new ListGridRecord(); - record.setAttribute("summary", error.getSummary()); - record.setAttribute("detail", error.getDetail()); - errorList.add(record); + Table errorsGrid = new Table("Errors"); + + errorsGrid.setShowFooter(false); +// errorsGrid.getListGrid().setGroupByField(ResourceErrorsDataSource.ERROR_TYPE_ID); +// errorsGrid.getListGrid().setGroupStartOpen(GroupStartOpen.ALL); +// errorsGrid.getListGrid().setShowGroupSummary(true); + + errorsGrid.setDataSource(new ResourceErrorsDataSource(resource.getId())); + + //hide only works after we set the datasource + errorsGrid.getListGrid().hideField(ResourceErrorsDataSource.DETAIL_ID); + + errorsGrid.getListGrid().addCellClickHandler(new CellClickHandler() { + public void onCellClick(CellClickEvent event) { + ListGridRecord record = event.getRecord(); + final Window w = new Window(); + w.setTitle("Error Details"); + w.setIsModal(true); + w.setShowMinimizeButton(false); + w.setShowModalMask(true); + w.setWidth(640); + w.setHeight(480); + w.centerInPage(); + + VLayout layout = new VLayout(10); + layout.setLayoutAlign(Alignment.CENTER); + layout.setLayoutMargin(10); + + w.addItem(layout); + + HTMLPane details = new HTMLPane(); + details.setContents("<pre>" + record.getAttribute(ResourceErrorsDataSource.DETAIL_ID) + "</pre>"); + layout.addMember(details); + + IButton ok = new IButton("Ok"); + ok.addClickHandler(new ClickHandler() { + public void onClick(ClickEvent event) { + w.destroy(); + } + }); + ok.setAlign(Alignment.CENTER); + + layout.addMember(ok); + + w.show(); } - - errorsGrid.setRecords(errorList.toArray(new ListGridRecord[errorList.size()])); - } - - return errorsGrid; + }); + + addMember(errorsGrid); } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java new file mode 100644 index 0000000..4957fc7 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/ResourceErrorsDataSource.java @@ -0,0 +1,100 @@ +/* + * 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.inventory.resource.detail.summary; + +import java.util.Date; +import java.util.List; + +import org.rhq.core.domain.resource.ResourceError; +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; +import org.rhq.enterprise.gui.coregui.client.util.RPCDataSource; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.data.DSRequest; +import com.smartgwt.client.data.DSResponse; +import com.smartgwt.client.data.fields.DataSourceDateField; +import com.smartgwt.client.data.fields.DataSourceDateTimeField; +import com.smartgwt.client.data.fields.DataSourceEnumField; +import com.smartgwt.client.data.fields.DataSourceTextField; +import com.smartgwt.client.rpc.RPCResponse; +import com.smartgwt.client.widgets.grid.ListGridRecord; + +/** + * + * @author Lukas Krejci + */ +public class ResourceErrorsDataSource extends RPCDataSource<ResourceError> { + + public static final String SUMMARY_ID = "summary"; + public static final String DETAIL_ID = "detail"; + public static final String ERROR_TYPE_ID = "errorType"; + public static final String TIME_OCCURED_ID = "timeOccured"; + + ResourceGWTServiceAsync resourceService; + int resourceId; + + public ResourceErrorsDataSource(int resourceId) { + resourceService = GWTServiceLookup.getResourceService(); + this.resourceId = resourceId; + + addFields(new DataSourceTextField(SUMMARY_ID, "Summary"), + new DataSourceTextField(DETAIL_ID, "Detailed Message"), + new DataSourceEnumField(ERROR_TYPE_ID, "Error Type"), new DataSourceDateTimeField(TIME_OCCURED_ID, "Time")); + } + + /* (non-Javadoc) + * @see org.rhq.enterprise.gui.coregui.client.util.RPCDataSource#executeFetch(com.smartgwt.client.data.DSRequest, com.smartgwt.client.data.DSResponse) + */ + @Override + protected void executeFetch(final DSRequest request, final DSResponse response) { + resourceService.findResourceErrors(resourceId, new AsyncCallback<List<ResourceError>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError( + "Failed to find resource errors for resource with id: " + resourceId, caught); + response.setStatus(RPCResponse.STATUS_FAILURE); + processResponse(request.getRequestId(), response); + } + + public void onSuccess(List<ResourceError> result) { + response.setData(buildRecords(result)); + processResponse(request.getRequestId(), response); + }; + }); + } + + public ResourceError copyValues(ListGridRecord from) { + //This is read-only datasource, so no need to implement this. + return null; + } + + public ListGridRecord copyValues(ResourceError from) { + ListGridRecord record = new ListGridRecord(); + + record.setAttribute(DETAIL_ID, from.getDetail()); + record.setAttribute(ERROR_TYPE_ID, from.getErrorType()); + record.setAttribute(SUMMARY_ID, from.getSummary()); + record.setAttribute(TIME_OCCURED_ID, new Date(from.getTimeOccurred())); + + return record; + } + +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java index 1b6f6cd..1ea9630 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/RPCDataSource.java @@ -18,6 +18,7 @@ */ package org.rhq.enterprise.gui.coregui.client.util;
+import java.util.Arrays; import java.util.Collection;
import com.smartgwt.client.data.DSRequest; @@ -176,4 +177,8 @@ public abstract class RPCDataSource<T> extends DataSource { addField(field); } } + + public void addFields(DataSourceField... fields) { + addFields(Arrays.asList(fields)); + } } diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java index c10254e..b933248 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/server/gwt/ResourceGWTServiceImpl.java @@ -35,6 +35,7 @@ import org.rhq.core.domain.configuration.definition.ConfigurationTemplate; import org.rhq.core.domain.criteria.ResourceCriteria; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.composite.RecentlyAddedResourceComposite; import org.rhq.core.domain.resource.composite.ResourceComposite; import org.rhq.core.domain.util.PageControl; @@ -215,4 +216,8 @@ public class ResourceGWTServiceImpl extends AbstractGWTServiceImpl implements Re discoveryBoss.unignoreResources(getSessionSubject(), resourceIds); }
+ public List<ResourceError> findResourceErrors(int resourceId) { + return SerialUtility.prepare(resourceManager.findResourceErrors(getSessionSubject(), resourceId), + "ResourceService.getResourceErrors"); + } } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index b773384..a480fb7 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -486,7 +486,7 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeRequest upgradeRequest, boolean allowGenericPropertiesUpgrade) { if (upgradeRequest.getUpgradeErrorMessage() != null) { ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, upgradeRequest.getUpgradeErrorMessage(), upgradeRequest.getUpgradeErrorStackTrace(), upgradeRequest.getTimestamp()); - entityManager.persist(error); + resourceManager.addResourceError(error); return null; }
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 5a4cf92..29672cc 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 @@ -1708,6 +1708,21 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage return query.getResultList(); }
+ @NotNull + @SuppressWarnings("unchecked") + public List<ResourceError> findResourceErrors(Subject user, int resourceId) { + // do authz check + if (!authorizationManager.canViewResource(user, resourceId)) { + throw new PermissionException("User [" + user + "] does not have permission to view resource [" + + resourceId + "]"); + } + + // we passed authz check, now get the errors + Query query = entityManager.createNamedQuery(ResourceError.QUERY_FIND_BY_RESOURCE_ID); + query.setParameter("resourceId", resourceId); + return query.getResultList(); + } + public void addResourceError(ResourceError resourceError) { Subject overlord = subjectManager.getOverlord(); Resource resource; @@ -1718,9 +1733,10 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage }
if (resourceError.getErrorType() == ResourceErrorType.INVALID_PLUGIN_CONFIGURATION - || resourceError.getErrorType() == ResourceErrorType.AVAILABILITY_CHECK) { - // there should be at most one invalid plugin configuration error and one availability check error per - // resource, so delete any currently existing ones before we add this new one + || resourceError.getErrorType() == ResourceErrorType.AVAILABILITY_CHECK + || resourceError.getErrorType() == ResourceErrorType.UPGRADE) { + // there should be at most one invalid plugin configuration error, availability check + // or upgrade error per resource, so delete any currently existing ones before we add this new one List<ResourceError> doomedErrors = resource.getResourceErrors(resourceError.getErrorType());
// there should only ever be at most 1, but loop through the list just in case something got screwed up diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java index a2f26ff..b84a104 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java @@ -319,6 +319,17 @@ public interface ResourceManagerLocal { List<ResourceError> findResourceErrors(Subject user, int resourceId, ResourceErrorType errorType);
/** + * Returns all the errors that have occurred for the given resource. + * + * @param user the user asking to see the errors + * @param resourceId the resource whose errors are to be returned + * + * @return the list of resource errors + */ + @NotNull + List<ResourceError> findResourceErrors(Subject user, int resourceId); + + /** * Indicates an error occurred on a resource. The given error will be associated with the resource found in the * error. *
commit 4e8ae3349ff28b025741a1c3bb0d1a827c0feff8 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 20 15:14:27 2010 +0200
first stab at the errors display GUI.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java new file mode 100644 index 0000000..074b3c9 --- /dev/null +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewForm.java @@ -0,0 +1,298 @@ +/* + * 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.inventory.resource.detail.summary; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.List; + +import org.rhq.core.domain.measurement.DataType; +import org.rhq.core.domain.measurement.DisplayType; +import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.measurement.MeasurementDefinition; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.composite.ResourceComposite; +import org.rhq.enterprise.gui.coregui.client.CoreGUI; +import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; +import org.rhq.enterprise.gui.coregui.client.components.form.TogglableTextItem; +import org.rhq.enterprise.gui.coregui.client.components.form.ValueUpdatedHandler; +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.type.ResourceTypeRepository; +import org.rhq.enterprise.gui.coregui.client.util.message.Message; + +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.smartgwt.client.util.SC; +import com.smartgwt.client.widgets.form.fields.FormItem; +import com.smartgwt.client.widgets.form.fields.HeaderItem; +import com.smartgwt.client.widgets.form.fields.SpacerItem; +import com.smartgwt.client.widgets.form.fields.StaticTextItem; + +/** + * The Resource Summary>Overview tab, the form with resource data. + * + * @author Greg Hinkle + * @author Ian Springer + */ +public class OverviewForm extends EnhancedDynamicForm { + + private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); + private ResourceComposite resourceComposite; + + public OverviewForm(ResourceComposite resourceComposite) { + this.resourceComposite = resourceComposite; + } + + @Override + protected void onDraw() { + super.onDraw(); + + setLeft("10%"); + setWidth("80%"); + + if (this.resourceComposite != null) { + setResource(this.resourceComposite); + } + } + + public void setResource(ResourceComposite resourceComposite) { + + this.resourceComposite = resourceComposite; + Resource resource = resourceComposite.getResource(); + + // Load metric defs. + ResourceTypeRepository.Cache.getInstance().getResourceTypes(resource.getResourceType().getId(), + EnumSet.of(ResourceTypeRepository.MetadataType.measurements), + new ResourceTypeRepository.TypeLoadedCallback() { + public void onTypesLoaded(ResourceType type) { + try { + buildForm(type); + loadTraitValues(); + } catch (Exception e) { + SC.say("Form load failure"); + e.printStackTrace(); + } + } + }); + } + + private void loadTraitValues() { + final Resource resource = resourceComposite.getResource(); + GWTServiceLookup.getMeasurementDataService().findCurrentTraitsForResource( + resource.getId(), + DisplayType.SUMMARY, + new AsyncCallback<List<MeasurementDataTrait>>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to load traits for " + resource + ".", + caught); + } + + public void onSuccess(List<MeasurementDataTrait> result) { + // TODO: Implement this method. + for (MeasurementDataTrait trait : result) { + String formId = trait.getName().replaceAll("\.", "_").replaceAll(" ", "__"); + FormItem item = getItem(formId); + + if (item != null) { + setValue(formId, trait.getValue()); + } + } + markForRedraw(); + } + } + ); + + } + + private void buildForm(ResourceType type) { + List<MeasurementDefinition> traits = new ArrayList<MeasurementDefinition>(); + + for (MeasurementDefinition measurement : type.getMetricDefinitions()) { + if (measurement.getDataType() == DataType.TRAIT && measurement.getDisplayType() == DisplayType.SUMMARY) { + traits.add(measurement); + } + } + + Collections.sort(traits, new Comparator<MeasurementDefinition>() { + public int compare(MeasurementDefinition o1, MeasurementDefinition o2) { + return new Integer(o1.getDisplayOrder()).compareTo(o2.getDisplayOrder()); + } + }); + + List<FormItem> formItems = new ArrayList<FormItem>(); + + HeaderItem headerItem = new HeaderItem("header", "Summary"); + headerItem.setValue("Summary"); + formItems.add(headerItem); + + StaticTextItem typeItem = new StaticTextItem("type", "Type"); + typeItem.setTooltip("Plugin: " + type.getPlugin() + "\n<br>" + "Type: " + type.getName()); + typeItem.setValue(type.getName() + " (" + type.getPlugin() + ")"); + formItems.add(typeItem); + + final Resource resource = this.resourceComposite.getResource(); + boolean modifiable = this.resourceComposite.getResourcePermission().isInventory(); + + final FormItem nameItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + nameItem.setName("name"); + nameItem.setTitle("Name"); + nameItem.setValue(resource.getName()); + if (nameItem instanceof TogglableTextItem) { + TogglableTextItem togglableNameItem = (TogglableTextItem) nameItem; + togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newName) { + final String oldName = resource.getName(); + if (newName.equals(oldName)) { + return; + } + resource.setName(newName); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change name of Resource with id " + + resource.getId() + + " from "" + oldName + "" to "" + newName + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setName(oldName); + nameItem.setValue(oldName); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Name of Resource with id " + + resource.getId() + " was changed from "" + + oldName + "" to "" + newName + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(nameItem); + + final FormItem descriptionItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + descriptionItem.setName("description"); + descriptionItem.setTitle("Description"); + descriptionItem.setValue(resource.getDescription()); + if (descriptionItem instanceof TogglableTextItem) { + TogglableTextItem togglableDescriptionItem = (TogglableTextItem) descriptionItem; + togglableDescriptionItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newDescription) { + final String oldDescription = resource.getDescription(); + if (newDescription.equals(oldDescription)) { + return; + } + resource.setDescription(newDescription); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change description of Resource with id " + + resource.getId() + + " from "" + oldDescription + "" to "" + newDescription + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setDescription(oldDescription); + descriptionItem.setValue(oldDescription); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Description of Resource with id " + + resource.getId() + " was changed from "" + + oldDescription + "" to "" + newDescription + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(descriptionItem); + + final FormItem locationItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); + locationItem.setName("location"); + locationItem.setTitle("Location"); + locationItem.setValue(resource.getLocation()); + if (locationItem instanceof TogglableTextItem) { + TogglableTextItem togglableNameItem = (TogglableTextItem) locationItem; + togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { + public void onValueUpdated(final String newLocation) { + final String oldLocation = resource.getLocation(); + if (newLocation.equals(oldLocation)) { + return; + } + resource.setLocation(newLocation); + OverviewForm.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { + public void onFailure(Throwable caught) { + CoreGUI.getErrorHandler().handleError("Failed to change location of Resource with id " + + resource.getId() + + " from "" + oldLocation + "" to "" + newLocation + "".", caught); + // We failed to update it on the Server, so change back the Resource and the form item to + // the original value. + resource.setLocation(oldLocation); + locationItem.setValue(oldLocation); + } + + public void onSuccess(Void result) { + CoreGUI.getMessageCenter().notify(new Message("Location of Resource with id " + + resource.getId() + " was changed from "" + + oldLocation + "" to "" + newLocation + "".", Message.Severity.Info)); + } + }); + } + }); + } + formItems.add(locationItem); + + + StaticTextItem versionItem = new StaticTextItem("version", "Version"); + formItems.add(versionItem); + + StaticTextItem parentItem = new StaticTextItem("parent", "Parent"); + formItems.add(parentItem); + + for (MeasurementDefinition trait : traits) { + String id = trait.getDisplayName().replaceAll("\.", "_").replaceAll(" ", "__"); + + StaticTextItem item = new StaticTextItem(id, trait.getDisplayName()); + item.setTooltip(trait.getDescription()); + formItems.add(item); +// item.setValue("?"); + } + +// SectionItem section = new SectionItem("Summary", "Summary"); +// section.setTitle("Summary"); +// section.setDefaultValue("Summary"); +// section.setCanCollapse(true); +// section.setCellStyle("HidablePlainSectionHeader"); +// section.setItemIds(itemIds.toArray(new String[itemIds.size()])); +// formItems.add(0, section); + + formItems.add(new SpacerItem()); + setItems(formItems.toArray(new FormItem[formItems.size()])); + + setValue("type", type.getName() + " (" + type.getPlugin() + ")"); + setValue("name", resource.getName()); + setValue("description", resource.getDescription()); + setValue("location", resource.getLocation()); + setValue("version", (resource.getVersion() != null) ? resource.getVersion() : "<i>none</i>"); + Resource parentResource = resource.getParentResource(); + setValue("parent", parentResource != null ? + ("<a href="#Resource/" + parentResource.getId() + "">" + + parentResource.getName() + "</a>") : "<i>none</i>"); + } +} diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java index ac2abc2..2fff538 100644 --- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java +++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/summary/OverviewView.java @@ -19,53 +19,35 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.summary;
import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumSet; import java.util.List;
-import com.google.gwt.user.client.rpc.AsyncCallback; -import com.smartgwt.client.util.SC; -import com.smartgwt.client.widgets.form.fields.FormItem; -import com.smartgwt.client.widgets.form.fields.HeaderItem; -import com.smartgwt.client.widgets.form.fields.SpacerItem; -import com.smartgwt.client.widgets.form.fields.StaticTextItem; - -import org.rhq.core.domain.measurement.DataType; -import org.rhq.core.domain.measurement.DisplayType; -import org.rhq.core.domain.measurement.MeasurementDataTrait; -import org.rhq.core.domain.measurement.MeasurementDefinition; import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.composite.ResourceComposite; -import org.rhq.enterprise.gui.coregui.client.CoreGUI; -import org.rhq.enterprise.gui.coregui.client.components.form.EnhancedDynamicForm; -import org.rhq.enterprise.gui.coregui.client.components.form.TogglableTextItem; -import org.rhq.enterprise.gui.coregui.client.components.form.ValueUpdatedHandler; -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.ResourceSelectListener; -import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository; -import org.rhq.enterprise.gui.coregui.client.util.message.Message; + +import com.smartgwt.client.util.SC; +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.grid.events.RecordClickEvent; +import com.smartgwt.client.widgets.grid.events.RecordClickHandler; +import com.smartgwt.client.widgets.layout.VLayout;
/** * The Resource Summary>Overview tab. * - * @author Greg Hinkle - * @author Ian Springer + * @author Lukas Krejci */ -public class OverviewView extends EnhancedDynamicForm implements ResourceSelectListener { +public class OverviewView extends VLayout implements ResourceSelectListener {
- private ResourceGWTServiceAsync resourceService = GWTServiceLookup.getResourceService(); private ResourceComposite resourceComposite;
- public OverviewView(ResourceComposite resourceComposite) { super(); this.resourceComposite = resourceComposite; }
- @Override protected void onDraw() { super.onDraw(); @@ -78,225 +60,43 @@ public class OverviewView extends EnhancedDynamicForm implements ResourceSelectL } }
- public void onResourceSelected(ResourceComposite resourceComposite) { - - this.resourceComposite = resourceComposite; - Resource resource = resourceComposite.getResource(); - - // Load metric defs. - ResourceTypeRepository.Cache.getInstance().getResourceTypes(resource.getResourceType().getId(), - EnumSet.of(ResourceTypeRepository.MetadataType.measurements), - new ResourceTypeRepository.TypeLoadedCallback() { - public void onTypesLoaded(ResourceType type) { - try { - buildForm(type); - loadTraitValues(); - } catch (Exception e) { - SC.say("Form load failure"); - e.printStackTrace(); - } - } - }); + addMember(new OverviewForm(resourceComposite)); + ListGrid errorsGrid = buildErrorListGrid(resourceComposite); + if (errorsGrid != null) { + addMember(errorsGrid); + } }
- private void loadTraitValues() { + private static ListGrid buildErrorListGrid(ResourceComposite resourceComposite) { final Resource resource = resourceComposite.getResource(); - GWTServiceLookup.getMeasurementDataService().findCurrentTraitsForResource( - resource.getId(), - DisplayType.SUMMARY, - new AsyncCallback<List<MeasurementDataTrait>>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to load traits for " + resource + ".", - caught); - } - - public void onSuccess(List<MeasurementDataTrait> result) { - // TODO: Implement this method. - for (MeasurementDataTrait trait : result) { - String formId = trait.getName().replaceAll("\.", "_").replaceAll(" ", "__"); - FormItem item = getItem(formId); - - if (item != null) { - setValue(formId, trait.getValue()); - } - } - markForRedraw(); - } - } - ); - - } - - private void buildForm(ResourceType type) { - List<MeasurementDefinition> traits = new ArrayList<MeasurementDefinition>(); - - for (MeasurementDefinition measurement : type.getMetricDefinitions()) { - if (measurement.getDataType() == DataType.TRAIT && measurement.getDisplayType() == DisplayType.SUMMARY) { - traits.add(measurement); - } - } - - Collections.sort(traits, new Comparator<MeasurementDefinition>() { - public int compare(MeasurementDefinition o1, MeasurementDefinition o2) { - return new Integer(o1.getDisplayOrder()).compareTo(o2.getDisplayOrder()); - } - }); - - List<FormItem> formItems = new ArrayList<FormItem>(); - - HeaderItem headerItem = new HeaderItem("header", "Summary"); - headerItem.setValue("Summary"); - formItems.add(headerItem); + ListGrid errorsGrid = null; + if (resource.getResourceErrors() != null && resource.getResourceErrors().size() > 0) { + errorsGrid = new ListGrid();
- StaticTextItem typeItem = new StaticTextItem("type", "Type"); - typeItem.setTooltip("Plugin: " + type.getPlugin() + "\n<br>" + "Type: " + type.getName()); - typeItem.setValue(type.getName() + " (" + type.getPlugin() + ")"); - formItems.add(typeItem); + ListGridField summaryField = new ListGridField("summary", "Errors"); + summaryField.addRecordClickHandler(new RecordClickHandler() {
- final Resource resource = this.resourceComposite.getResource(); - boolean modifiable = this.resourceComposite.getResourcePermission().isInventory(); - - final FormItem nameItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - nameItem.setName("name"); - nameItem.setTitle("Name"); - nameItem.setValue(resource.getName()); - if (nameItem instanceof TogglableTextItem) { - TogglableTextItem togglableNameItem = (TogglableTextItem) nameItem; - togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newName) { - final String oldName = resource.getName(); - if (newName.equals(oldName)) { - return; - } - resource.setName(newName); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to change name of Resource with id " - + resource.getId() - + " from "" + oldName + "" to "" + newName + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setName(oldName); - nameItem.setValue(oldName); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Name of Resource with id " - + resource.getId() + " was changed from "" - + oldName + "" to "" + newName + "".", Message.Severity.Info)); - } - }); + @Override + public void onRecordClick(RecordClickEvent event) { + String detail = event.getRecord().getAttribute("detail"); + SC.say("Error details", detail); } }); - } - formItems.add(nameItem); - - final FormItem descriptionItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - descriptionItem.setName("description"); - descriptionItem.setTitle("Description"); - descriptionItem.setValue(resource.getDescription()); - if (descriptionItem instanceof TogglableTextItem) { - TogglableTextItem togglableDescriptionItem = (TogglableTextItem) descriptionItem; - togglableDescriptionItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newDescription) { - final String oldDescription = resource.getDescription(); - if (newDescription.equals(oldDescription)) { - return; - } - resource.setDescription(newDescription); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to change description of Resource with id " - + resource.getId() - + " from "" + oldDescription + "" to "" + newDescription + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setDescription(oldDescription); - descriptionItem.setValue(oldDescription); - } - - public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Description of Resource with id " - + resource.getId() + " was changed from "" - + oldDescription + "" to "" + newDescription + "".", Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(descriptionItem);
- final FormItem locationItem = (modifiable) ? new TogglableTextItem() : new StaticTextItem(); - locationItem.setName("location"); - locationItem.setTitle("Location"); - locationItem.setValue(resource.getLocation()); - if (locationItem instanceof TogglableTextItem) { - TogglableTextItem togglableNameItem = (TogglableTextItem) locationItem; - togglableNameItem.addValueUpdatedHandler(new ValueUpdatedHandler() { - public void onValueUpdated(final String newLocation) { - final String oldLocation = resource.getLocation(); - if (newLocation.equals(oldLocation)) { - return; - } - resource.setLocation(newLocation); - OverviewView.this.resourceService.updateResource(resource, new AsyncCallback<Void>() { - public void onFailure(Throwable caught) { - CoreGUI.getErrorHandler().handleError("Failed to change location of Resource with id " - + resource.getId() - + " from "" + oldLocation + "" to "" + newLocation + "".", caught); - // We failed to update it on the Server, so change back the Resource and the form item to - // the original value. - resource.setLocation(oldLocation); - locationItem.setValue(oldLocation); - } + errorsGrid.setFields(summaryField);
- public void onSuccess(Void result) { - CoreGUI.getMessageCenter().notify(new Message("Location of Resource with id " - + resource.getId() + " was changed from "" - + oldLocation + "" to "" + newLocation + "".", Message.Severity.Info)); - } - }); - } - }); - } - formItems.add(locationItem); - - - StaticTextItem versionItem = new StaticTextItem("version", "Version"); - formItems.add(versionItem); - - StaticTextItem parentItem = new StaticTextItem("parent", "Parent"); - formItems.add(parentItem); - - for (MeasurementDefinition trait : traits) { - String id = trait.getDisplayName().replaceAll("\.", "_").replaceAll(" ", "__"); + List<ListGridRecord> errorList = new ArrayList<ListGridRecord>(); + for (ResourceError error : resource.getResourceErrors()) { + ListGridRecord record = new ListGridRecord(); + record.setAttribute("summary", error.getSummary()); + record.setAttribute("detail", error.getDetail()); + errorList.add(record); + }
- StaticTextItem item = new StaticTextItem(id, trait.getDisplayName()); - item.setTooltip(trait.getDescription()); - formItems.add(item); -// item.setValue("?"); + errorsGrid.setRecords(errorList.toArray(new ListGridRecord[errorList.size()])); }
-// SectionItem section = new SectionItem("Summary", "Summary"); -// section.setTitle("Summary"); -// section.setDefaultValue("Summary"); -// section.setCanCollapse(true); -// section.setCellStyle("HidablePlainSectionHeader"); -// section.setItemIds(itemIds.toArray(new String[itemIds.size()])); -// formItems.add(0, section); - - formItems.add(new SpacerItem()); - setItems(formItems.toArray(new FormItem[formItems.size()])); - - setValue("type", type.getName() + " (" + type.getPlugin() + ")"); - setValue("name", resource.getName()); - setValue("description", resource.getDescription()); - setValue("location", resource.getLocation()); - setValue("version", (resource.getVersion() != null) ? resource.getVersion() : "<i>none</i>"); - Resource parentResource = resource.getParentResource(); - setValue("parent", parentResource != null ? - ("<a href="#Resource/" + parentResource.getId() + "">" + - parentResource.getName() + "</a>") : "<i>none</i>"); + return errorsGrid; } }
commit d266142e299215832de65b40be45e40862f56128 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 20 15:14:04 2010 +0200
adding a test plugin that fails the upgrade so that we can add the tests for handling that scenario
diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index 4b4524a..a4ca249 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -177,6 +177,12 @@ <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar"> <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2" includes="*.class,**/rhq-plugin.xml" /> </jar> + <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/failing/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-3.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/failing" includes="*.class,**/rhq-plugin.xml" /> + </jar> </tasks> </configuration> <goals> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java new file mode 100644 index 0000000..54153e6 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/DiscComponent.java @@ -0,0 +1,54 @@ +/* + * 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.core.pc.upgrade.plugins.failing; + +import java.util.Collections; +import java.util.Set; + +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + +/** + * + * @author Lukas Krejci + */ +public class DiscComponent implements ResourceDiscoveryComponent<ResourceComponent>, + ResourceUpgradeFacet<ResourceComponent> { + + private static final String RESOURCE_KEY = "resource-key-failing"; + private static final String RESOURCE_NAME = "resource-name-failing"; + private static final String RESOURCE_DESCRIPTION = "resource-description-failing"; + + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent> context) + throws InvalidPluginConfigurationException, Exception { + return Collections.singleton(new DiscoveredResourceDetails(context.getResourceType(), RESOURCE_KEY, + RESOURCE_NAME, null, RESOURCE_DESCRIPTION, context.getDefaultPluginConfiguration(), null)); + } + + public ResourceUpgradeReport upgrade(ResourceUpgradeContext<ResourceComponent> inventoriedResource) { + throw new RuntimeException("Failing the upgrade purposefully."); + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/ResComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/ResComponent.java new file mode 100644 index 0000000..4c33adc --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/ResComponent.java @@ -0,0 +1,46 @@ +/* + * 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.core.pc.upgrade.plugins.failing; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; + +/** + * + * @author Lukas Krejci + */ +public class ResComponent implements ResourceComponent<ResourceComponent> { + private static final Log log = LogFactory.getLog(ResComponent.class); + + public AvailabilityType getAvailability() { + return AvailabilityType.UP; + } + + public void start(ResourceContext<ResourceComponent> context) throws InvalidPluginConfigurationException, Exception { + log.info("~~~ starting the resource upgrade test failing component with resource key: " + context.getResourceKey()); + } + + public void stop() { + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml new file mode 100644 index 0000000..9e750d1 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/failing/rhq-plugin.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeTest" + displayName="Resource Upgrade Test" + description="Resource Upgrade Test" + package="org.rhq.core.pc.upgrade.plugins.failing" + version="3.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="Resource" + discovery="DiscComponent" + class="ResComponent" + singleton="true" /> + +</plugin> +
commit 6dde2f7be37f23a5e8a9b25ccf66e99541fd3bc7 Merge: d58520e... 462e15f... Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 20 12:50:39 2010 +0200
Merge branch 'master' into resource-upgrade
commit d58520e4a31ab38e03151e827488776d4dcca93f Author: Lukas Krejci lkrejci@redhat.com Date: Fri Aug 20 12:46:29 2010 +0200
Added agent and server side support for upgrade error reporting.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java index f055e8c..9532920 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java @@ -23,6 +23,9 @@
package org.rhq.core.clientapi.agent.upgrade;
+import java.io.PrintWriter; +import java.io.StringWriter; + import org.rhq.core.domain.resource.ResourceUpgradeReport;
/** @@ -34,44 +37,95 @@ public class ResourceUpgradeRequest extends ResourceUpgradeReport {
private static final long serialVersionUID = 1L;
- private int resourceId; + private final int resourceId; + private String upgradeErrorMessage; + private String upgradeErrorStackTrace; + private long timestamp;
- public ResourceUpgradeRequest() { - + public ResourceUpgradeRequest(int resourceId) { + this.resourceId = resourceId; }
public ResourceUpgradeRequest(int resourceId, ResourceUpgradeReport report) { - setResourceId(resourceId); - setNewDescription(report.getNewDescription()); - setNewName(report.getNewName()); - setNewResourceKey(report.getNewResourceKey()); + this.resourceId = resourceId; + fillInFromReport(report); } - + public int getResourceId() { return resourceId; }
- public void setResourceId(int resourceId) { - this.resourceId = resourceId; + public String getUpgradeErrorMessage() { + return upgradeErrorMessage; + } + + public void setUpgradeErrorMessage(String upgradeErrorMessage) { + this.upgradeErrorMessage = upgradeErrorMessage; + } + + public String getUpgradeErrorStackTrace() { + return upgradeErrorStackTrace; + } + + public void setUpgradeErrorStackTrace(String upgradeErrorStackTrace) { + this.upgradeErrorStackTrace = upgradeErrorStackTrace; + } + + public long getTimestamp() { + return timestamp; }
+ public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public void setErrorProperties(Throwable t) { + upgradeErrorMessage = t.getMessage(); + + StringWriter string = new StringWriter(); + PrintWriter w = new PrintWriter(string); + t.printStackTrace(w); + w.close(); + + upgradeErrorStackTrace = string.toString(); + } + + public void fillInFromReport(ResourceUpgradeReport report) { + setNewDescription(report.getNewDescription()); + setNewName(report.getNewName()); + setNewResourceKey(report.getNewResourceKey()); + } + + @Override + public boolean hasSomethingToUpgrade() { + return super.hasSomethingToUpgrade() || upgradeErrorMessage != null || upgradeErrorStackTrace != null; + } + @Override public int hashCode() { return 31 * resourceId; } - + @Override public boolean equals(Object other) { if (other == this) { return true; } - + if (!(other instanceof ResourceUpgradeRequest)) { return false; } - + ResourceUpgradeRequest r = (ResourceUpgradeRequest) other; - + return r.getResourceId() == resourceId; } + + @Override + public String toString() { + return "ResourceUpgradeRequest[resourceId = '" + resourceId + "', newResourceKey = '" + getNewResourceKey() + + "', newName = '" + getNewName() + "', newDescription = '" + getNewDescription() + + "', upgradeErrorMessage = '" + upgradeErrorMessage + "', upgradeErrorStackTrace = '" + + upgradeErrorStackTrace + "']"; + } } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceErrorType.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceErrorType.java index 1435cc3..8fcedb7 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceErrorType.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceErrorType.java @@ -36,5 +36,10 @@ public enum ResourceErrorType { /** * An exception was thrown by the Resource component's getAvailablity() method the last time it was called. */ - AVAILABILITY_CHECK + AVAILABILITY_CHECK, + + /** + * There was an attempt to upgrade the resource on the agent but it failed. + */ + UPGRADE } \ No newline at end of file diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 728b2e3..3af9b84 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1202,14 +1202,14 @@ public class InventoryManager extends AgentService implements ContainerService, return resourceContainer.updateAvailability(availabilityType); }
- public void mergeResourceFromUpgrade(Set<ResourceUpgradeRequest> upgradeReports) { + public void mergeResourceFromUpgrade(Set<ResourceUpgradeRequest> upgradeRequests) { Set<ResourceUpgradeResponse> serverUpdates = null; try { ServerServices serverServices = this.configuration.getServerServices(); if (serverServices != null) { DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService();
- serverUpdates = discoveryServerService.upgradeResources(upgradeReports); + serverUpdates = discoveryServerService.upgradeResources(upgradeRequests); } } catch (Exception e) { log.error("Failed to process resource upgrades on the server.", e); diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java index 5b33fe1..025ba3a 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java @@ -82,12 +82,10 @@ public class ResourceUpgradeDelegate { * @return true if the resource was queued for upgrade, false otherwise * @throws PluginContainerException on error */ - public boolean processAndQueue(ResourceContainer resourceContainer) throws PluginContainerException { + public void processAndQueue(ResourceContainer resourceContainer) throws PluginContainerException { if (enabled) { - return executeResourceUpgradeFacetAndStoreRequest(resourceContainer); + executeResourceUpgradeFacetAndStoreRequest(resourceContainer); } - - return false; }
public void sendRequests() { @@ -100,7 +98,7 @@ public class ResourceUpgradeDelegate { }
@SuppressWarnings("unchecked") - private <T extends ResourceComponent> boolean executeResourceUpgradeFacetAndStoreRequest( + private <T extends ResourceComponent> void executeResourceUpgradeFacetAndStoreRequest( ResourceContainer resourceContainer) throws PluginContainerException {
ResourceComponent<T> parentResourceComponent = resourceContainer.getResourceContext() @@ -118,36 +116,47 @@ public class ResourceUpgradeDelegate {
if (!(discoveryComponent instanceof ResourceUpgradeFacet)) { //well, there's no point in continuing if the resource doesn't support the facet - return false; + return; }
ResourceUpgradeContext<ResourceComponent<T>> upgradeContext = inventoryManager.createResourceUpgradeContext( resource, parentResourceComponent, discoveryComponent);
- ResourceUpgradeReport upgradeReport; + ResourceUpgradeRequest request = new ResourceUpgradeRequest(resource.getId()); + + request.setTimestamp(System.currentTimeMillis()); + + ResourceUpgradeReport upgradeReport = null; try { upgradeReport = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resource.getResourceType(), discoveryComponent, upgradeContext); } catch (Throwable t) { log.error("ResourceUpgradeFacet threw an exception while upgrading resource [" + resource + "]", t); - return false; + request.setErrorProperties(t); }
- if (upgradeReport == null || !upgradeReport.hasSomethingToUpgrade()) { - return false; - } + if (upgradeReport != null && upgradeReport.hasSomethingToUpgrade()) { + String upgradeErrors = null; + if ((upgradeErrors = checkUpgradeValid(resource, upgradeReport)) != null) { + String errorString = "Upgrading the resource [" + resource + "] using these updates [" + upgradeReport + + "] would render the inventory invalid because of the following reasons: " + upgradeErrors; + + log.error(errorString); + + IllegalStateException ex = new IllegalStateException(errorString); + ex.fillInStackTrace(); + + request.setErrorProperties(ex); + } else { + request.fillInFromReport(upgradeReport); + }
- String upgradeErrors = null; - if ((upgradeErrors = checkUpgradeValid(resource, upgradeReport)) != null) { - log.error("Upgrading the resource [" + resource + "] using these updates [" + upgradeReport - + "] would render the inventory invalid because of the following reasons: " + upgradeErrors); - return false; }
//everything went ok, let's queue a upgrade request that will be sent to the server - requests.add(new ResourceUpgradeRequest(resource.getId(), upgradeReport)); - - return true; + if (request.hasSomethingToUpgrade()) { + requests.add(request); + } }
private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 304cbad..b773384 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -58,6 +58,8 @@ import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.ProductVersion; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceCategory; +import org.rhq.core.domain.resource.ResourceError; +import org.rhq.core.domain.resource.ResourceErrorType; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.domain.util.PageControl; @@ -422,7 +424,9 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot Resource existingResource = this.entityManager.find(Resource.class, request.getResourceId()); if (existingResource != null) { ResourceUpgradeResponse upgradedData = upgradeResource(existingResource, request, allowGenericPropertiesUpgrade); - result.add(upgradedData); + if (upgradedData != null) { + result.add(upgradedData); + } } } return result; @@ -475,18 +479,24 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot
/** * @param existingResource - * @param upgradeReport + * @param upgradeRequest * @param allowGenericPropertiesUpgrade name and description are only upgraded if this is true * @return true if the resource was changed, false otherwise */ - private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeReport upgradeReport, boolean allowGenericPropertiesUpgrade) { + private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeRequest upgradeRequest, boolean allowGenericPropertiesUpgrade) { + if (upgradeRequest.getUpgradeErrorMessage() != null) { + ResourceError error = new ResourceError(resource, ResourceErrorType.UPGRADE, upgradeRequest.getUpgradeErrorMessage(), upgradeRequest.getUpgradeErrorStackTrace(), upgradeRequest.getTimestamp()); + entityManager.persist(error); + return null; + } + ResourceUpgradeResponse ret = new ResourceUpgradeResponse(); ret.setResourceId(resource.getId());
- String resourceKey = upgradeReport.getNewResourceKey(); - String name = upgradeReport.getNewName(); + String resourceKey = upgradeRequest.getNewResourceKey(); + String name = upgradeRequest.getNewName(); // String version = upgradeReport.getNewVersion(); - String description = upgradeReport.getNewDescription(); + String description = upgradeRequest.getNewDescription(); // Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); // Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
commit 5b093893923a739ed2634c73e05392e917b8e7fb Merge: 63d04ea... a13c17d... Author: Lukas Krejci lkrejci@redhat.com Date: Wed Aug 11 16:43:07 2010 +0200
Merge branch 'master' into resource-upgrade
diff --cc modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp index 136c37c,45526f7..0000000 deleted file mode 100644,100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp +++ /dev/null diff --cc modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index add8168,2773b4c..304cbad --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@@ -659,22 -559,10 +659,22 @@@ public class DiscoveryBossBean implemen */ ResourceType resourceType = resource.getResourceType(); Resource parent = resource; + Subject overlord = subjectManager.getOverlord(); while (parent != null && existingResource == null) { parent = parent.getParentResource(); - existingResource = resourceManager.getResourceByParentAndKey(subjectManager.getOverlord(), parent, + //check if the parent itself is inventoried. This might not be the case + //during initial sync-up for resource upgrade. + Resource existingParent = null; + if (parent != null) { + existingParent = entityManager.find(Resource.class, parent.getId()); + if (existingParent == null) { + //well, this parent is not known to the server, so there's no + //point in trying to find a child of it... + continue; + } + } + existingResource = resourceManager.getResourceByParentAndKey(overlord, existingParent, - resource.getResourceKey(), resourceType.getPlugin(), resourceType.getName()); + resource.getResourceKey(), resourceType.getPlugin(), resourceType.getName()); }
if (existingResource != null) { @@@ -905,8 -808,4 +920,8 @@@
updateInventoryStatus(subject, platforms, servers, target); } -} + + private static <T> boolean needsUpgrade(T oldValue, T newValue) { + return newValue != null && (oldValue == null || !newValue.equals(oldValue)); + } - } ++}
commit 63d04eaf7e697a241efe59832d7a4e127a084f92 Author: Lukas Krejci lkrejci@redhat.com Date: Mon Jul 12 18:39:22 2010 +0200
Adding tests for graceful handling of server-side exceptions and platform "disappearance" on the server-side.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index a5c3d1f..6fe7e96 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -940,8 +940,16 @@ public class InventoryManager extends AgentService implements ContainerService, //resource upgrade executor to sync up with the server side inventory *JUST AFTER* //this agent registered with the server for the very first time. In that case //the server hasn't received any info from us yet. + //Another (rare) scenario where this would happen would be when the platform resource type + //would change. + //In either case, let's sync up with the server - if it's got nothing, neither should the agent. if (syncInfo != null) { synchInventory(syncInfo); + } else { + purgeObsoleteResources(Collections.<String>emptySet()); + + //can't live without a platform, but we just deleted it. Let's rediscover it. + discoverPlatform(); }
return true; @@ -1077,8 +1085,10 @@ public class InventoryManager extends AgentService implements ContainerService, return; } boolean scan = removeResourceAndIndicateIfScanIsNeeded(resourceContainer.getResource()); - - if (scan) { + + //only actually schedule the scanning when we are finished with resource upgrade. The resource upgrade + //happens before any scanning infrastructure is established. + if (!resourceUpgradeDelegate.enabled() && scan) { log.info("Deleted resource #[" + resourceId + "] - this will trigger a server scan now"); inventoryThreadPoolExecutor.submit((Callable<InventoryReport>) this.serverScanExecutor); } @@ -2612,14 +2622,13 @@ public class InventoryManager extends AgentService implements ContainerService,
ResourceContainer container = getResourceContainer(resource); if (container != null) { - try { - container = getResourceContainer(resource); - resourceUpgradeDelegate.processAndQueue(container); - } catch (PluginContainerException e) { - log.error("Exception thrown while upgrading [" + resource + "]."); - } - if (container.getResourceComponentState() == ResourceComponentState.STARTED) { + try { + resourceUpgradeDelegate.processAndQueue(container); + } catch (PluginContainerException e) { + log.error("Exception thrown while upgrading [" + resource + "].", e); + } + for (Resource child : resource.getChildResources()) { upgradeResource(child); } diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java index c3bdbf4..19c1d95 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -56,7 +56,8 @@ public class FakeServerInventory { private Resource platform; private Map<String, Resource> resourceStore = new HashMap<String, Resource>(); private int counter; - + private boolean failing; + private static final Comparator<Resource> ID_COMPARATOR = new Comparator<Resource>() { public int compare(Resource o1, Resource o2) { return o1.getId() - o2.getId(); @@ -69,11 +70,21 @@ public class FakeServerInventory { } };
+ public FakeServerInventory() { + this(false); + } + + public FakeServerInventory(boolean failing) { + this.failing = failing; + } + //need to synchronize, because resource upgrade is async and can overlap with //resource discovery. public synchronized CustomAction mergeInventoryReport(final InventoryStatus requiredInventoryStatus) { return new CustomAction("updateServerSideInventory") { public Object invoke(Invocation invocation) throws Throwable { + throwIfFailing(); + InventoryReport inventoryReport = (InventoryReport) invocation.getParameter(0);
for(Resource res : inventoryReport.getAddedRoots()) { @@ -87,10 +98,24 @@ public class FakeServerInventory { }; }
+ public synchronized CustomAction clearPlatform() { + return new CustomAction("updateServerSideInventory - report platform deleted on the server") { + public Object invoke(Invocation invocation) throws Throwable { + throwIfFailing(); + + platform = null; + + return getSyncInfo(); + } + }; + } + public synchronized CustomAction upgradeResources() { return new CustomAction("upgradeServerSideInventory") { @SuppressWarnings({"serial", "unchecked"}) public Object invoke(Invocation invocation) throws Throwable { + throwIfFailing(); + Set<ResourceUpgradeRequest> requests = (Set<ResourceUpgradeRequest>) invocation.getParameter(0); Set<ResourceUpgradeResponse> responses = new HashSet<ResourceUpgradeResponse>();
@@ -129,6 +154,8 @@ public class FakeServerInventory { return new CustomAction("getResources") { @SuppressWarnings("unchecked") public Object invoke(Invocation invocation) throws Throwable { + throwIfFailing(); + Set<Integer> resourceIds = (Set<Integer>)invocation.getParameter(0); boolean includeDescendants = (Boolean) invocation.getParameter(1);
@@ -137,6 +164,14 @@ public class FakeServerInventory { }; }
+ public boolean isFailing() { + return failing; + } + + public void setFailing(boolean failing) { + this.failing = failing; + } + @SuppressWarnings("serial") public synchronized Set<Resource> findResourcesByType(final ResourceType type) { Set<Resource> result = new HashSet<Resource>(); @@ -218,6 +253,12 @@ public class FakeServerInventory { return platform != null ? convert(platform) : null; }
+ private void throwIfFailing() { + if (failing) { + throw new RuntimeException("Fake server inventory is in the failing mode."); + } + } + private static ResourceSyncInfo convert(Resource root) { try { ResourceSyncInfo ret = new ResourceSyncInfo(); diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index b5d571f..202e0c0 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -25,6 +25,7 @@ package org.rhq.core.pc.upgrade;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse;
import java.io.File; import java.io.IOException; @@ -151,11 +152,83 @@ public class ResourceUpgradeTest { }
@Test - public void testRecoveryWithServerUnavailable() throws Exception { - //TODO implement + public void testSkipUpgradeWhenServerUnavailable() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + initialSyncAndDiscovery(InventoryStatus.COMMITTED); + + currentServerSideInventory.setFailing(true); + + TestPayload test = new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); + assertEquals(discoveredResource.getName(), "resource-name-v1"); + assertEquals(discoveredResource.getDescription(), "resource-description-v1"); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + never(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + } + }; + } + }; + + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, test); + } + + @Test + public void testUpgradeWithPlatformDeletedOnServer() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + initialSyncAndDiscovery(InventoryStatus.COMMITTED); + + TestPayload test = new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); + assertEquals(discoveredResource.getName(), "resource-name-v2"); + assertEquals(discoveredResource.getDescription(), "resource-description-v2"); + + ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + File dataDir = container.getResourceContext().getDataDirectory(); + + File marker = new File(dataDir, "upgrade-succeeded"); + + assertFalse(marker.exists(), "The upgrade seems to have occured even though there shouldn't have been a resource to upgrade."); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + + //the first merge will be triggered from within the upgrade process and we are + //going to report null sync. + oneOf(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.clearPlatform()); + + //the rest of the inventory merges are executed by discoveries, so let's import the + //discovered stuff into the server-side inventory. + between(1, 3).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + never(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + } + }; + } + }; + + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, test); }
private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { + cleanDataDir(); executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), true, new TestPayload() { public void test(Resource discoveredResource) { assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); @@ -303,40 +376,43 @@ public class ResourceUpgradeTest { for(String pluginResourcePath : pluginResourcePaths) { copyPlugin(pluginResourcePath, pluginDir); } - + Mockery context = new Mockery(); - + PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context); - + if (clearInventoryDat) { File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); inventoryDat.delete(); } - + context.checking(test.getExpectations(context)); - + PluginContainer.getInstance().setConfiguration(pcConfig); PluginContainer.getInstance().initialize(); - - //give the pc the time to finish resource upgrade - Thread.sleep(1000); - - //execute full discovery - InventoryManager im = PluginContainer.getInstance().getInventoryManager(); - im.executeServerScanImmediately(); - im.executeServiceScanImmediately(); - - Set<Resource> resources = getTestingResources(); - - assertEquals(resources.size(), 1, "There should be only a single testing resource but " + resources + " were found."); - - Resource discoveredResource = resources.iterator().next(); - - test.test(discoveredResource); - - PluginContainer.getInstance().shutdown(); - - context.assertIsSatisfied(); + + try { + //give the pc the time to finish resource upgrade + Thread.sleep(1000); + + //execute full discovery + InventoryManager im = PluginContainer.getInstance().getInventoryManager(); + im.executeServerScanImmediately(); + im.executeServiceScanImmediately(); + + Set<Resource> resources = getTestingResources(); + + assertEquals(resources.size(), 1, "There should be only a single testing resource but " + resources + + " were found."); + + Resource discoveredResource = resources.iterator().next(); + + test.test(discoveredResource); + + context.assertIsSatisfied(); + } finally { + PluginContainer.getInstance().shutdown(); + } }
@SuppressWarnings("unchecked") @@ -356,4 +432,8 @@ public class ResourceUpgradeTest { expectations.allowing(currentDiscoveryServerService).getResources(expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); expectations.will(currentServerSideInventory.getResources()); } + + private void cleanDataDir() throws IOException { + FileUtils.cleanDirectory(new File(tmpDir, DATA_DIR_NAME)); + } }
commit 178d4de9fb18d7f9045e673e64c33a359436be81 Author: John Mazzitelli mazz@redhat.com Date: Tue Jul 6 19:12:26 2010 -0400
generate the two resource upgrade test plugins rather than have the .jar files committed directly to git this way we can see the source and change it if we ever need to. also allows us to have source to step through in a debugger
diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml index 2e58102..93f64cf 100644 --- a/modules/core/plugin-container/pom.xml +++ b/modules/core/plugin-container/pom.xml @@ -126,6 +126,7 @@ <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> + <id>process-test-resources</id> <phase>process-test-resources</phase> <configuration> <tasks> @@ -151,7 +152,31 @@ <include name="**/lib/*" /> </fileset> </move> - <delete dir="${project.build.directory}/jboss-sigar/hyperic-sigar-${sigar.version}" /> + <delete dir="${project.build.directory}/jboss-sigar/hyperic-sigar-${sigar.version}" /> + </tasks> + </configuration> + <goals> + <goal>run</goal> + </goals> + </execution> + <execution> + <id>process-test-classes</id> + <phase>process-test-classes</phase> + <configuration> + <tasks> + <echo>Assembling the two resource upgrade test plugins</echo> + <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v1/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v1" includes="*.class,**/rhq-plugin.xml" /> + </jar> + <copy toDir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2/META-INF"> + <fileset file="${project.build.testSourceDirectory}/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml" /> + </copy> + <jar destfile="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar"> + <fileset dir="${project.build.testOutputDirectory}/org/rhq/core/pc/upgrade/plugins/v2" includes="*.class,**/rhq-plugin.xml" /> + </jar> </tasks> </configuration> <goals> diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/DiscComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/DiscComponent.java new file mode 100644 index 0000000..5fbca32 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/DiscComponent.java @@ -0,0 +1,22 @@ +package org.rhq.core.pc.upgrade.plugins.v1; + +import java.util.Collections; +import java.util.Set; + +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; + +public class DiscComponent implements ResourceDiscoveryComponent<ResourceComponent> { + private static final String RESOURCE_KEY = "resource-key-v1"; + private static final String RESOURCE_NAME = "resource-name-v1"; + private static final String RESOURCE_DESCRIPTION = "resource-description-v1"; + + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent> context) + throws InvalidPluginConfigurationException, Exception { + return Collections.singleton(new DiscoveredResourceDetails(context.getResourceType(), RESOURCE_KEY, + RESOURCE_NAME, null, RESOURCE_DESCRIPTION, context.getDefaultPluginConfiguration(), null)); + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/ResComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/ResComponent.java new file mode 100644 index 0000000..cc21fc3 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/ResComponent.java @@ -0,0 +1,21 @@ +package org.rhq.core.pc.upgrade.plugins.v1; + +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; + +public class ResComponent implements ResourceComponent<ResourceComponent> { + public AvailabilityType getAvailability() { + return AvailabilityType.UP; + } + + public void start(ResourceContext<ResourceComponent> context) { + LogFactory.getLog(this.getClass()).info( + "~~~ Starting resource upgrade test plugin v1 component: key=" + context.getResourceKey()); + } + + public void stop() { + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml new file mode 100644 index 0000000..c658e0c --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v1/rhq-plugin.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeTest" + displayName="Resource Upgrade Test" + description="Resource Upgrade Test" + package="org.rhq.core.pc.upgrade.plugins.v1" + version="1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="Resource" + discovery="DiscComponent" + class="ResComponent" + singleton="true" /> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/DiscComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/DiscComponent.java new file mode 100644 index 0000000..d113d1c --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/DiscComponent.java @@ -0,0 +1,54 @@ +package org.rhq.core.pc.upgrade.plugins.v2; + +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.Set; + +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + +public class DiscComponent implements ResourceDiscoveryComponent<ResourceComponent>, + ResourceUpgradeFacet<ResourceComponent> { + private static final String V1_RESOURCE_KEY = "resource-key-v1"; + private static final String RESOURCE_KEY = "resource-key-v2"; + private static final String RESOURCE_NAME = "resource-name-v2"; + private static final String RESOURCE_DESCRIPTION = "resource-description-v2"; + + public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent> context) + throws InvalidPluginConfigurationException, Exception { + return Collections.singleton(new DiscoveredResourceDetails(context.getResourceType(), RESOURCE_KEY, + RESOURCE_NAME, null, RESOURCE_DESCRIPTION, context.getDefaultPluginConfiguration(), null)); + } + + public ResourceUpgradeReport upgrade(ResourceUpgradeContext<ResourceComponent> inventoriedResource) { + if (V1_RESOURCE_KEY.equals(inventoriedResource.getResourceKey())) { + ResourceUpgradeReport report = new ResourceUpgradeReport(); + report.setNewResourceKey(RESOURCE_KEY); + report.setNewName(RESOURCE_NAME); + report.setNewDescription(RESOURCE_DESCRIPTION); + + File dataDir = inventoriedResource.getDataDirectory(); + + if (dataDir != null) { + if (!(dataDir.exists())) { + dataDir.mkdir(); + } + File marker = new File(dataDir, "upgrade-succeeded"); + try { + marker.createNewFile(); + } catch (IOException localIOException) { + } + } + return report; + } + + return null; + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/ResComponent.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/ResComponent.java new file mode 100644 index 0000000..83144b2 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/ResComponent.java @@ -0,0 +1,21 @@ +package org.rhq.core.pc.upgrade.plugins.v2; + +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; + +public class ResComponent implements ResourceComponent<ResourceComponent> { + public AvailabilityType getAvailability() { + return AvailabilityType.UP; + } + + public void start(ResourceContext<ResourceComponent> context) { + LogFactory.getLog(this.getClass()).info( + "~~~ Starting resource upgrade test plugin v2 component: key=" + context.getResourceKey()); + } + + public void stop() { + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml new file mode 100644 index 0000000..9f63892 --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/plugins/v2/rhq-plugin.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<plugin name="ResourceUpgradeTest" + displayName="Resource Upgrade Test" + description="Resource Upgrade Test" + package="org.rhq.core.pc.upgrade.plugins.v2" + version="2.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="urn:xmlns:rhq-plugin" + xmlns:c="urn:xmlns:rhq-configuration"> + + <server name="Resource" + discovery="DiscComponent" + class="ResComponent" + singleton="true" /> + +</plugin> + diff --git a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar deleted file mode 100644 index 33a79c0..0000000 Binary files a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar and /dev/null differ diff --git a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar deleted file mode 100644 index 7ffc5bb..0000000 Binary files a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar and /dev/null differ
commit 9edde408d4dbabbc057e5e11fdfb6c3c16d2936e Author: John Mazzitelli mazz@redhat.com Date: Tue Jul 6 16:11:44 2010 -0400
trivial - reformat some things. no need to use isDebugEnabled if you are logging a simple string message with no string concatentation
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 5786702..a5c3d1f 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -72,8 +72,8 @@ import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceCreationDataType; import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.ResourceErrorType; -import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.pc.ContainerService; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.PluginContainerConfiguration; @@ -193,7 +193,7 @@ public class InventoryManager extends AgentService implements ContainerService, * Handles the resource upgrade during the initialization of the inventory manager. */ private ResourceUpgradeDelegate resourceUpgradeDelegate; - + public InventoryManager() { super(DiscoveryAgentService.class); } @@ -224,7 +224,7 @@ public class InventoryManager extends AgentService implements ContainerService, //discoveries. resourceUpgradeDelegate = new ResourceUpgradeDelegate(this); upgradeResources(); - + availabilityCollectors = new AvailabilityCollectorThreadPool(); availabilityCollectors.initialize();
@@ -300,7 +300,7 @@ public class InventoryManager extends AgentService implements ContainerService, return results; } catch (TimeoutException te) { log.warn("Discovery for Resources of [" + context.getResourceType() + "] has been running for more than " - + timeout + " milliseconds. This may be a plugin bug.", te); + + timeout + " milliseconds. This may be a plugin bug.", te); return null; } catch (BlacklistedException be) { // Discovery did not run, because the ResourceType was blacklisted during a prior discovery scan. @@ -333,8 +333,8 @@ public class InventoryManager extends AgentService implements ContainerService, return result; } catch (TimeoutException te) { log.warn("Manual add of Resource of type [" + context.getResourceType() + "] with plugin configuration [" - + pluginConfig.toString(true) + "] has been running for more than " - + timeout + " milliseconds. This may be a plugin bug.", te); + + pluginConfig.toString(true) + "] has been running for more than " + timeout + + " milliseconds. This may be a plugin bug.", te); return null; } catch (BlacklistedException be) { log.debug(ThrowableUtil.getAllMessages(be)); @@ -382,11 +382,12 @@ public class InventoryManager extends AgentService implements ContainerService, public <T extends ResourceComponent> ResourceUpgradeReport invokeDiscoveryComponentResourceUpgradeFacet( ResourceType resourceType, ResourceDiscoveryComponent<T> component, ResourceUpgradeContext<T> inventoriedResource) throws Throwable { - + long timeout = getDiscoveryComponentTimeout(resourceType); try { @SuppressWarnings("unchecked") - ResourceUpgradeFacet<T> proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(resourceType, component, timeout, ResourceUpgradeFacet.class); + ResourceUpgradeFacet<T> proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy( + resourceType, component, timeout, ResourceUpgradeFacet.class);
return proxy.upgrade(inventoriedResource); } catch (BlacklistedException e) { @@ -394,7 +395,7 @@ public class InventoryManager extends AgentService implements ContainerService, return null; } } - + public DiscoveryComponentProxyFactory getDiscoveryComponentProxyFactory() { return this.discoveryComponentProxyFactory; } @@ -892,7 +893,7 @@ public class InventoryManager extends AgentService implements ContainerService, public boolean handleReport(InventoryReport report) { return handleReport(report, false); } - + /** * Send an inventory report to the Server. * @@ -904,7 +905,7 @@ public class InventoryManager extends AgentService implements ContainerService, if (!configuration.isInsideAgent()) { return true; } - + if (report.getAddedRoots().isEmpty() && !forceServerRoundtrip) { return true; // nothing to do } @@ -981,7 +982,7 @@ public class InventoryManager extends AgentService implements ContainerService, log.debug(String.format("DONE syncing local inventory [%d] ms.", (System.currentTimeMillis() - startTime))); } - + // If we synced any Resources, one or more Resource components were probably started, // so run an avail check to report on their availabilities immediately. Also kick off // a service scan to scan those Resources for new child Resources. Kick both tasks off @@ -991,7 +992,8 @@ public class InventoryManager extends AgentService implements ContainerService, // inventory with the server side as well as to disallow any other server-agent traffic during // the upgrade phase. Not to mention the fact that no thread pools are initialized yet by the // time the upgrade kicks in.. - if (!resourceUpgradeDelegate.enabled() && (!syncedResources.isEmpty() || !unknownResourceIds.isEmpty() || !modifiedResourceIds.isEmpty())) { + if (!resourceUpgradeDelegate.enabled() + && (!syncedResources.isEmpty() || !unknownResourceIds.isEmpty() || !modifiedResourceIds.isEmpty())) { performAvailabilityChecks(true); this.inventoryThreadPoolExecutor.schedule((Callable<? extends Object>) this.serviceScanExecutor, 5, TimeUnit.SECONDS); @@ -1003,7 +1005,7 @@ public class InventoryManager extends AgentService implements ContainerService, throw new RuntimeException(t); } } - + private void getAllUuids(ResourceSyncInfo syncInfo, Set<String> allServerSideUuids) { allServerSideUuids.add(syncInfo.getUuid()); for (ResourceSyncInfo child : syncInfo.getChildSyncInfos()) { @@ -1181,13 +1183,13 @@ public class InventoryManager extends AgentService implements ContainerService, ServerServices serverServices = this.configuration.getServerServices(); if (serverServices != null) { DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService(); - + serverUpdates = discoveryServerService.upgradeResources(upgradeReports); } } catch (Exception e) { log.error("Failed to process resource upgrades on the server.", e); } - + if (serverUpdates != null) { for (ResourceUpgradeResponse upgradeResponse : serverUpdates) { String resourceKey = upgradeResponse.getUpgradedResourceKey(); @@ -1202,49 +1204,50 @@ public class InventoryManager extends AgentService implements ContainerService, ResourceContainer existingResourceContainer = getResourceContainer(upgradeResponse.getResourceId()); if (existingResourceContainer != null) { Resource existingResource = existingResourceContainer.getResource(); - - StringBuilder logMessage = new StringBuilder("Resource [") - .append(existingResource.toString()).append("] upgraded its "); - + + StringBuilder logMessage = new StringBuilder("Resource [").append(existingResource.toString()) + .append("] upgraded its "); + if (resourceKey != null) { existingResource.setResourceKey(resourceKey); logMessage.append("resourceKey, "); } - + if (name != null) { existingResource.setName(name); logMessage.append("name, "); } - -// if (version != null) { -// existingResource.setVersion(version); -// } - + + //if (version != null) { + // existingResource.setVersion(version); + //} + if (description != null) { existingResource.setDescription(description); logMessage.append("description, "); } - -// if (pluginConfiguration != null) { -// existingResource.setPluginConfiguration(pluginConfiguration); -// } -// -// if (resourceConfiguration != null) { -// existingResource.setResourceConfiguration(resourceConfiguration); -// } - - logMessage.replace(logMessage.length() - 1, logMessage.length(), - "to become [").append(existingResource.toString()).append("]"); - + + //if (pluginConfiguration != null) { + // existingResource.setPluginConfiguration(pluginConfiguration); + //} + // + //if (resourceConfiguration != null) { + // existingResource.setResourceConfiguration(resourceConfiguration); + //} + + logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [").append( + existingResource.toString()).append("]"); + log.info(logMessage.toString()); } else { - log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeResponse.getResourceId()); + log.error("Upgraded a resource that is not present on the agent. This should not happen. " + + "The id of the missing resource is: " + upgradeResponse.getResourceId()); } } } } } - + public Resource mergeResourceFromDiscovery(Resource resource, Resource parent) throws PluginContainerException { // If the Resource is already in inventory, make sure its version is up-to-date, then simply return the // existing Resource. @@ -1466,7 +1469,7 @@ public class InventoryManager extends AgentService implements ContainerService, }
ResourceContext context = createResourceContext(resource, parentComponent, discoveryComponent); - + container.setResourceContext(context);
// Wrap the component in a proxy that will provide locking and a timeout for the call to start(). @@ -1513,7 +1516,8 @@ public class InventoryManager extends AgentService implements ContainerService, } }
- private <T extends ResourceComponent> ResourceContext<T> createResourceContext(Resource resource, T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { + private <T extends ResourceComponent> ResourceContext<T> createResourceContext(Resource resource, + T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { File pluginDataDir = new File(this.configuration.getDataDirectory(), resource.getResourceType().getPlugin());
return new ResourceContext<T>(resource, // the resource itself @@ -1529,8 +1533,9 @@ public class InventoryManager extends AgentService implements ContainerService, this.availabilityCollectors, // for components that want to perform async avail checking this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do } - - public <T extends ResourceComponent> ResourceUpgradeContext<T> createResourceUpgradeContext(Resource resource, T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { + + public <T extends ResourceComponent> ResourceUpgradeContext<T> createResourceUpgradeContext(Resource resource, + T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { File pluginDataDir = new File(this.configuration.getDataDirectory(), resource.getResourceType().getPlugin());
return new ResourceUpgradeContext<T>(resource, // the resource itself @@ -1546,7 +1551,7 @@ public class InventoryManager extends AgentService implements ContainerService, this.availabilityCollectors, // for components that want to perform async avail checking this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do } - + /** * This will send a resource error to the server (if applicable) to indicate that the given resource could not be * connected to due to an invalid plugin configuration. @@ -1789,13 +1794,13 @@ public class InventoryManager extends AgentService implements ContainerService, Set<DiscoveredResourceDetails> allDiscoveredPlatforms = new HashSet<DiscoveredResourceDetails>(2);
if ((platformTypes != null) && (platformTypes.size() > 0)) { - + //check for fake testing type. If the test platform type is being used, it is always going to be //the sole platform type available. if (platformTypes.size() == 1 && platformTypes.contains(PluginMetadataManager.TEST_PLATFORM_TYPE)) { return getTestPlatform(); } - + // Go through all the platform types that are supported and see if they can detect our platform. for (ResourceType platformType : platformTypes) { try { @@ -2123,11 +2128,11 @@ public class InventoryManager extends AgentService implements ContainerService, @NotNull Set<Resource> executeComponentDiscovery(ResourceType resourceType, ResourceDiscoveryComponent discoveryComponent, ResourceContainer parentContainer, List<ProcessScanResult> processScanResults) { - + ResourceContext parentResourceContext = parentContainer.getResourceContext(); ResourceComponent parentComponent = parentContainer.getResourceComponent(); Resource parentResource = parentContainer.getResource(); - + long startTime = System.currentTimeMillis(); log.debug("Executing discovery for [" + resourceType.getName() + "] Resources..."); Set<Resource> newResources; @@ -2578,9 +2583,7 @@ public class InventoryManager extends AgentService implements ContainerService,
private void upgradeResources() { try { - if (log.isDebugEnabled()) { - log.debug("Executing resource upgrade."); - } + log.debug("Executing resource upgrade.");
boolean syncResult = handleReport(new InventoryReport(getAgent()), true); if (!syncResult) { @@ -2590,27 +2593,23 @@ public class InventoryManager extends AgentService implements ContainerService,
upgradeResource(getPlatform());
- if (log.isDebugEnabled()) { - log.debug("Sending the upgrade requests to the server."); - } + log.debug("Sending the upgrade requests to the server."); resourceUpgradeDelegate.sendRequests();
resourceUpgradeDelegate.disable();
- if (log.isDebugEnabled()) { - log.debug("Resource upgrade finished."); - } + log.debug("Resource upgrade finished."); } catch (Throwable t) { log.error("Resource upgrade failed with an exception.", t); } } - + private void upgradeResource(Resource resource) { //only process committed resources if (resource.getInventoryStatus() != InventoryStatus.COMMITTED) { return; } - + ResourceContainer container = getResourceContainer(resource); if (container != null) { try { @@ -2625,14 +2624,15 @@ public class InventoryManager extends AgentService implements ContainerService, upgradeResource(child); } } else { - log.error("The resource container for resource [" + resource + "] wasn't started during upgrade. This should not happen."); - } + log.error("The resource container for resource [" + resource + + "] wasn't started during upgrade. This should not happen."); + } } else { log.error("Resource container not initialized for resource [" + resource + "] during upgrade. This should not happen."); } } - + /** * That class implements a listener that gets called when the resource got activated * @author hrupp
commit 1e41a098af78a7d97e0a0415dba48bf0b98dba73 Author: John Mazzitelli mazz@redhat.com Date: Tue Jul 6 16:03:35 2010 -0400
trivial - add comment, small reformat
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java index cb466bd..5b33fe1 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java @@ -24,6 +24,7 @@ import java.util.Set;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; import org.rhq.core.domain.resource.Resource; @@ -40,6 +41,11 @@ import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; * This is a helper class to {@link InventoryManager} that takes care of resource upgrade. * Note that this class is not thread-safe in any manner. * + * This class must not call (explicitly or implicitly anywhere in its outgoing call chain) + * any other plugin container manager other than the InventoryManager. This is because + * this delegate is called within the Inventory Manager's initialize method and hence + * many other managers are not yet initialized themselves yet. + * * @author Lukas Krejci */ public class ResourceUpgradeDelegate { @@ -62,7 +68,7 @@ public class ResourceUpgradeDelegate { public boolean enabled() { return enabled; } - + /** * Disables all future operations of the delegate. */ @@ -93,10 +99,10 @@ public class ResourceUpgradeDelegate { } }
+ @SuppressWarnings("unchecked") private <T extends ResourceComponent> boolean executeResourceUpgradeFacetAndStoreRequest( ResourceContainer resourceContainer) throws PluginContainerException {
- @SuppressWarnings("unchecked") ResourceComponent<T> parentResourceComponent = resourceContainer.getResourceContext() .getParentResourceComponent();
@@ -107,7 +113,6 @@ public class ResourceUpgradeDelegate {
Resource resource = resourceContainer.getResource();
- @SuppressWarnings("unchecked") ResourceDiscoveryComponent<ResourceComponent<T>> discoveryComponent = PluginContainer.getInstance() .getPluginComponentFactory().getDiscoveryComponent(resource.getResourceType(), parentResourceContainer);
@@ -146,13 +151,13 @@ public class ResourceUpgradeDelegate { }
private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { - StringBuilder bld = new StringBuilder(); + StringBuilder s = new StringBuilder();
if (!checkResourceKeyUniqueAmongSiblings(resource, upgradeReport)) { - bld.append("\nAnother inventoried sibling resource of the same type already has the proposed resource key."); + s.append("\nAnother inventoried sibling resource of the same type already has the proposed resource key."); }
- return bld.length() > 0 ? bld.toString() : null; + return s.length() > 0 ? s.toString() : null; }
private boolean checkResourceKeyUniqueAmongSiblings(Resource resource, ResourceUpgradeReport upgradeReport) {
commit fb7c05447b2b4d0f3ebf30481942f12d176f759e Author: John Mazzitelli mazz@redhat.com Date: Tue Jul 6 16:02:39 2010 -0400
trivial - remove tabs
diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java index d122da4..915a9e7 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java @@ -35,12 +35,11 @@ import org.rhq.core.pluginapi.inventory.ResourceComponent; * @author Lukas Krejci */ public interface ResourceUpgradeFacet<T extends ResourceComponent> { - - /** - * Specifies what data should change on the provided resource to upgrade it to the current version. - * - * @param inventoriedResource a context representing the resource to be upgraded - * @return a report specifying what aspects of the resource should be changed or null if there is nothing to upgrade - */ - ResourceUpgradeReport upgrade(ResourceUpgradeContext<T> inventoriedResource); + /** + * Specifies what data should change on the provided resource to upgrade it to the current version. + * + * @param inventoriedResource a context representing the resource to be upgraded + * @return a report specifying what aspects of the resource should be changed or null if there is nothing to upgrade + */ + ResourceUpgradeReport upgrade(ResourceUpgradeContext<T> inventoriedResource); }
commit 18316510cafe27425cd1ac3cc1d08afe398d77ab Merge: 14db66f... fac71cd... Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jul 2 17:54:08 2010 +0200
Merge branch 'release-3.0.0' into resource-upgrade
commit 14db66fe1f2774bcead24daebee947e6b52851dd Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jul 2 17:52:12 2010 +0200
Refactoring the resource upgrade to upgrade before the discovery during InventoryManager.initialize(). That enables us to remove all the synchronization on the resources.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java index 825a616..f055e8c 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java @@ -32,6 +32,8 @@ import org.rhq.core.domain.resource.ResourceUpgradeReport; */ public class ResourceUpgradeRequest extends ResourceUpgradeReport {
+ private static final long serialVersionUID = 1L; + private int resourceId;
public ResourceUpgradeRequest() { @@ -52,4 +54,24 @@ public class ResourceUpgradeRequest extends ResourceUpgradeReport { public void setResourceId(int resourceId) { this.resourceId = resourceId; } + + @Override + public int hashCode() { + return 31 * resourceId; + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + + if (!(other instanceof ResourceUpgradeRequest)) { + return false; + } + + ResourceUpgradeRequest r = (ResourceUpgradeRequest) other; + + return r.getResourceId() == resourceId; + } } diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java index 0f9db04..c2bc392 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java @@ -108,4 +108,14 @@ public class ResourceUpgradeReport implements Serializable { public void setNewDescription(String newDescription) { this.newDescription = newDescription; } + + public boolean hasSomethingToUpgrade() { + return newResourceKey != null || + newName != null || + newDescription != null; + } + + public String toString() { + return "ResourceUpgradeReport[newResourceKey = '" + newResourceKey + "', newName = '" + newName + "', newDescription = '" + newDescription + "']"; + } } diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java index 914641c..d122da4 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java @@ -23,9 +23,6 @@
package org.rhq.core.pluginapi.upgrade;
-import java.util.Map; -import java.util.Set; - import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.pluginapi.inventory.ResourceComponent;
@@ -39,19 +36,11 @@ import org.rhq.core.pluginapi.inventory.ResourceComponent; */ public interface ResourceUpgradeFacet<T extends ResourceComponent> {
- /** - * This method is called on the discovery component straight after it has finished the discovery. - * The exact same discovery results are passed to this method along with the set of resources - * that already exist in the inventory. - * - * @param inventoriedSiblings the existing resources - * @param parentContext the parent of both the newly discovered and existing resources - * @param discoveryResults the discovered resources. The resources from this set that have - * the same resource key as one of the inventoried siblings (after upgrade using the results of this method) won't - * be reported. - * @return the mapping of old resources to the newly desired data. The keys are instances from the - * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the - * corresponding siblings should be upgraded to. - */ - Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext<T>> inventoriedSiblings, ResourceUpgradeContext<? extends ResourceComponent> parentContext, Set<ResourceUpgradeContext<T>> discoveryResults); + /** + * Specifies what data should change on the provided resource to upgrade it to the current version. + * + * @param inventoriedResource a context representing the resource to be upgraded + * @return a report specifying what aspects of the resource should be changed or null if there is nothing to upgrade + */ + ResourceUpgradeReport upgrade(ResourceUpgradeContext<T> inventoriedResource); } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java index 4d61e93..7561bf7 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java @@ -261,10 +261,6 @@ public class PluginContainer implements ContainerService { } finally { releaseLock(lock); } - - //fire off the resource upgrade as soon as possible. It will run only once per plugin container - //lifetime. - inventoryManager.fireResourceUpgrade();
return; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index ee42f7d..5786702 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -33,11 +33,9 @@ import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -93,8 +91,7 @@ import org.rhq.core.pc.plugin.BlacklistedException; import org.rhq.core.pc.plugin.CanonicalResourceKey; import org.rhq.core.pc.plugin.PluginComponentFactory; import org.rhq.core.pc.plugin.PluginManager; -import org.rhq.core.pc.upgrade.ResourceUpgradeExecutor; -import org.rhq.core.pc.upgrade.ResourceUpgradePendingRequest; +import org.rhq.core.pc.upgrade.ResourceUpgradeDelegate; import org.rhq.core.pc.util.DiscoveryComponentProxyFactory; import org.rhq.core.pc.util.FacetLockType; import org.rhq.core.pc.util.LoggingThreadFactory; @@ -195,7 +192,7 @@ public class InventoryManager extends AgentService implements ContainerService, /** * Handles the resource upgrade during the initialization of the inventory manager. */ - private ResourceUpgradeExecutor resourceUpgradeExecutor; + private ResourceUpgradeDelegate resourceUpgradeDelegate;
public InventoryManager() { super(DiscoveryAgentService.class); @@ -219,12 +216,18 @@ public class InventoryManager extends AgentService implements ContainerService, loadFromDisk(); }
- availabilityCollectors = new AvailabilityCollectorThreadPool(); - availabilityCollectors.initialize(); - // Discover the platform first thing. executePlatformScan();
+ //try the resource upgrade before we have any schedulers set up + //so that we don't get any interventions from concurrently running + //discoveries. + resourceUpgradeDelegate = new ResourceUpgradeDelegate(this); + upgradeResources(); + + availabilityCollectors = new AvailabilityCollectorThreadPool(); + availabilityCollectors.initialize(); + // Never run more than one avail check at a time. availabilityThreadPoolExecutor = new ScheduledThreadPoolExecutor(AVAIL_THREAD_POOL_CORE_POOL_SIZE, new LoggingThreadFactory(AVAIL_THREAD_POOL_NAME, true)); @@ -251,8 +254,6 @@ public class InventoryManager extends AgentService implements ContainerService, inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor, configuration .getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS); } - - resourceUpgradeExecutor = new ResourceUpgradeExecutor(this); } finally { inventoryLock.writeLock().unlock(); } @@ -378,20 +379,19 @@ public class InventoryManager extends AgentService implements ContainerService, return results; }
- public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> invokeDiscoveryComponentResourceUpgradeFacet( + public <T extends ResourceComponent> ResourceUpgradeReport invokeDiscoveryComponentResourceUpgradeFacet( ResourceType resourceType, ResourceDiscoveryComponent<T> component, - Set<ResourceUpgradeContext<T>> inventoriedSiblings, ResourceUpgradeContext<?> parent, - Set<ResourceUpgradeContext<T>> discoveredResources) throws Throwable { + ResourceUpgradeContext<T> inventoriedResource) throws Throwable {
long timeout = getDiscoveryComponentTimeout(resourceType); try { @SuppressWarnings("unchecked") ResourceUpgradeFacet<T> proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(resourceType, component, timeout, ResourceUpgradeFacet.class);
- return proxy.upgrade(inventoriedSiblings, parent, discoveredResources); + return proxy.upgrade(inventoriedResource); } catch (BlacklistedException e) { log.debug(e); - return Collections.emptyMap(); + return null; } }
@@ -518,15 +518,6 @@ public class InventoryManager extends AgentService implements ContainerService, } }
- /** - * Executes the resource upgrade asynchronously. - */ - public void fireResourceUpgrade() { - Thread resourceUpgradeThread = new Thread(resourceUpgradeExecutor, "Resource Upgrade Thread"); - resourceUpgradeThread.setDaemon(true); - resourceUpgradeThread.start(); - } - public InventoryReport executeServerScanImmediately() { try { return inventoryThreadPoolExecutor.submit((Callable<InventoryReport>) this.serverScanExecutor).get(); @@ -914,16 +905,6 @@ public class InventoryManager extends AgentService implements ContainerService, return true; }
- //finish the resource upgrade. - //by now all the resource upgrade requests have been processed - //by the executor, which means that the inventory report - //we got already only contains the "correct" new resources and - //that the executor has all the upgrade requests queued up - //to be sent to the server in a batch. - if (resourceUpgradeExecutor.isEnabled()) { - resourceUpgradeExecutor.sendRequests(); - } - if (report.getAddedRoots().isEmpty() && !forceServerRoundtrip) { return true; // nothing to do } @@ -1005,7 +986,12 @@ public class InventoryManager extends AgentService implements ContainerService, // so run an avail check to report on their availabilities immediately. Also kick off // a service scan to scan those Resources for new child Resources. Kick both tasks off // asynchronously. - if (!syncedResources.isEmpty() || !unknownResourceIds.isEmpty() || !modifiedResourceIds.isEmpty()) { + // Do this only if we are finished with resource upgrade because no availability checks + // or discoveries can happen during upgrade. This is to ensure maximum consistency of the + // inventory with the server side as well as to disallow any other server-agent traffic during + // the upgrade phase. Not to mention the fact that no thread pools are initialized yet by the + // time the upgrade kicks in.. + if (!resourceUpgradeDelegate.enabled() && (!syncedResources.isEmpty() || !unknownResourceIds.isEmpty() || !modifiedResourceIds.isEmpty())) { performAvailabilityChecks(true); this.inventoryThreadPoolExecutor.schedule((Callable<? extends Object>) this.serviceScanExecutor, 5, TimeUnit.SECONDS); @@ -2180,10 +2166,6 @@ public class InventoryManager extends AgentService implements ContainerService, newResources.add(newResource); } } - - if (resourceUpgradeExecutor.isEnabled()) { - resourceUpgradeExecutor.processAndQueue(new ResourceUpgradePendingRequest(newResources, context, parentResource.getId()), newResources); - } } catch (Throwable e) { // TODO GH: Add server/parent - up/down semantics so this won't happen just because a server is not up long elapsedTime = System.currentTimeMillis() - startTime; @@ -2594,6 +2576,63 @@ public class InventoryManager extends AgentService implements ContainerService, container.setSynchronizationState(ResourceContainer.SynchronizationState.SYNCHRONIZED); }
+ private void upgradeResources() { + try { + if (log.isDebugEnabled()) { + log.debug("Executing resource upgrade."); + } + + boolean syncResult = handleReport(new InventoryReport(getAgent()), true); + if (!syncResult) { + log.warn("Resource upgrade failed to sync up the inventory with the server."); + return; + } + + upgradeResource(getPlatform()); + + if (log.isDebugEnabled()) { + log.debug("Sending the upgrade requests to the server."); + } + resourceUpgradeDelegate.sendRequests(); + + resourceUpgradeDelegate.disable(); + + if (log.isDebugEnabled()) { + log.debug("Resource upgrade finished."); + } + } catch (Throwable t) { + log.error("Resource upgrade failed with an exception.", t); + } + } + + private void upgradeResource(Resource resource) { + //only process committed resources + if (resource.getInventoryStatus() != InventoryStatus.COMMITTED) { + return; + } + + ResourceContainer container = getResourceContainer(resource); + if (container != null) { + try { + container = getResourceContainer(resource); + resourceUpgradeDelegate.processAndQueue(container); + } catch (PluginContainerException e) { + log.error("Exception thrown while upgrading [" + resource + "]."); + } + + if (container.getResourceComponentState() == ResourceComponentState.STARTED) { + for (Resource child : resource.getChildResources()) { + upgradeResource(child); + } + } else { + log.error("The resource container for resource [" + resource + "] wasn't started during upgrade. This should not happen."); + } + } else { + log.error("Resource container not initialized for resource [" + resource + + "] during upgrade. This should not happen."); + } + } + /** * That class implements a listener that gets called when the resource got activated * @author hrupp diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java new file mode 100644 index 0000000..cb466bd --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeDelegate.java @@ -0,0 +1,180 @@ +/* + * 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.core.pc.upgrade; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.clientapi.agent.PluginContainerException; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.inventory.InventoryManager; +import org.rhq.core.pc.inventory.ResourceContainer; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + +/** + * This is a helper class to {@link InventoryManager} that takes care of resource upgrade. + * Note that this class is not thread-safe in any manner. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeDelegate { + + private static final Log log = LogFactory.getLog(ResourceUpgradeDelegate.class); + + private boolean enabled = true; + + private Set<ResourceUpgradeRequest> requests = new HashSet<ResourceUpgradeRequest>(); + private InventoryManager inventoryManager; + + public ResourceUpgradeDelegate(InventoryManager inventoryManager) { + this.inventoryManager = inventoryManager; + } + + /** + * Is the delegate enabled? In another words has the resource upgrade phase finished in the {@link IventoryManager#initialize()} + * method? + */ + public boolean enabled() { + return enabled; + } + + /** + * Disables all future operations of the delegate. + */ + public void disable() { + enabled = false; + } + + /** + * Asks the resource's discovery component to upgrade the resource. + * @param resourceContainer + * @return true if the resource was queued for upgrade, false otherwise + * @throws PluginContainerException on error + */ + public boolean processAndQueue(ResourceContainer resourceContainer) throws PluginContainerException { + if (enabled) { + return executeResourceUpgradeFacetAndStoreRequest(resourceContainer); + } + + return false; + } + + public void sendRequests() { + if (enabled) { + if (requests.size() > 0) { + inventoryManager.mergeResourceFromUpgrade(requests); + requests.clear(); + } + } + } + + private <T extends ResourceComponent> boolean executeResourceUpgradeFacetAndStoreRequest( + ResourceContainer resourceContainer) throws PluginContainerException { + + @SuppressWarnings("unchecked") + ResourceComponent<T> parentResourceComponent = resourceContainer.getResourceContext() + .getParentResourceComponent(); + + Resource parentResource = resourceContainer.getResource().getParentResource(); + + ResourceContainer parentResourceContainer = (parentResource != null) ? inventoryManager + .getResourceContainer(resourceContainer.getResource().getParentResource()) : null; + + Resource resource = resourceContainer.getResource(); + + @SuppressWarnings("unchecked") + ResourceDiscoveryComponent<ResourceComponent<T>> discoveryComponent = PluginContainer.getInstance() + .getPluginComponentFactory().getDiscoveryComponent(resource.getResourceType(), parentResourceContainer); + + if (!(discoveryComponent instanceof ResourceUpgradeFacet)) { + //well, there's no point in continuing if the resource doesn't support the facet + return false; + } + + ResourceUpgradeContext<ResourceComponent<T>> upgradeContext = inventoryManager.createResourceUpgradeContext( + resource, parentResourceComponent, discoveryComponent); + + ResourceUpgradeReport upgradeReport; + try { + upgradeReport = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resource.getResourceType(), + discoveryComponent, upgradeContext); + } catch (Throwable t) { + log.error("ResourceUpgradeFacet threw an exception while upgrading resource [" + resource + "]", t); + return false; + } + + if (upgradeReport == null || !upgradeReport.hasSomethingToUpgrade()) { + return false; + } + + String upgradeErrors = null; + if ((upgradeErrors = checkUpgradeValid(resource, upgradeReport)) != null) { + log.error("Upgrading the resource [" + resource + "] using these updates [" + upgradeReport + + "] would render the inventory invalid because of the following reasons: " + upgradeErrors); + return false; + } + + //everything went ok, let's queue a upgrade request that will be sent to the server + requests.add(new ResourceUpgradeRequest(resource.getId(), upgradeReport)); + + return true; + } + + private String checkUpgradeValid(Resource resource, ResourceUpgradeReport upgradeReport) { + StringBuilder bld = new StringBuilder(); + + if (!checkResourceKeyUniqueAmongSiblings(resource, upgradeReport)) { + bld.append("\nAnother inventoried sibling resource of the same type already has the proposed resource key."); + } + + return bld.length() > 0 ? bld.toString() : null; + } + + private boolean checkResourceKeyUniqueAmongSiblings(Resource resource, ResourceUpgradeReport upgradeReport) { + Resource parent = resource.getParentResource(); + if (parent == null) { + return true; + } + + for (Resource sibling : parent.getChildResources()) { + //we'd have a resource key conflict if there was a resource + //of the same type under the same parent that would have the same + //resource key. + if (upgradeReport.getNewResourceKey() != null + && sibling.getResourceType().equals(resource.getResourceType()) + && !sibling.getUuid().equals(resource.getUuid())) { + + if (sibling.getResourceKey().equals(upgradeReport.getNewResourceKey())) { + return false; + } + } + } + + return true; + } +} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java deleted file mode 100644 index f344900..0000000 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ /dev/null @@ -1,299 +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, 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.pc.upgrade; - -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.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.rhq.core.clientapi.agent.PluginContainerException; -import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; -import org.rhq.core.clientapi.server.discovery.InventoryReport; -import org.rhq.core.domain.resource.InventoryStatus; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.domain.resource.ResourceType; -import org.rhq.core.domain.resource.ResourceUpgradeReport; -import org.rhq.core.pc.PluginContainer; -import org.rhq.core.pc.inventory.InventoryManager; -import org.rhq.core.pc.inventory.ResourceContainer; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.inventory.ResourceContext; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; -import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; -import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; - -/** - * This class is responsible for performing the resource upgrade on behalf on of {@link InventoryManager}. - * Despite its name, it is not an {@link java.util.concurrent.Executor} implementation. - * - * @author Lukas Krejci - */ -public class ResourceUpgradeExecutor implements Runnable { - private static final Log log = LogFactory.getLog(ResourceUpgradeExecutor.class); - - /** - * The upgrade runs only once in its lifetime. - */ - private AtomicBoolean enabled = new AtomicBoolean(true); - private AtomicBoolean started = new AtomicBoolean(false); - - private InventoryManager inventoryManager; - - private ConcurrentLinkedQueue<ResourceUpgradeRequest> requests; - - public ResourceUpgradeExecutor(InventoryManager inventoryManager) { - this.inventoryManager = inventoryManager; - requests = new ConcurrentLinkedQueue<ResourceUpgradeRequest>(); - } - - /** - * This method is called from within the {@link InventoryManager} during the - * discovery process as individual upgrade requests are generated. - * <p> - * This method calls the appropriate discovery component to perform the upgrade and - * at the same time stores off the results so that they can be sent to the server - * at the end of the discovery in one big batch. - * <p> - * The provided set of discovery results is updated if this method detects that an existing - * resource upgrade would result in a resource key collision with some of the newly discovered - * resources. - * - * @param request the upgrade request - * @param discoveredResources the set of discovered resources that this method can optionally remove some elements from. - */ - public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> processAndQueue( - ResourceUpgradePendingRequest<T> request, Set<Resource> discoveredResources) { - - return enabled.get() ? executeResourceUpgradeAndStoreRequest(request, discoveredResources) : null; - } - - /** - * @return true if the executor is ready to perform the upgrade, false otherwise. - */ - public boolean isEnabled() { - return enabled.get(); - } - - /** - * This method is called from within the {@link InventoryManager} once it's collected - * all the upgrade requests. - */ - public void sendRequests() { - if (enabled.get() && requests.size() > 0) { - HashSet<ResourceUpgradeRequest> currentCopy = new HashSet<ResourceUpgradeRequest>(requests); - inventoryManager.mergeResourceFromUpgrade(currentCopy); - requests.removeAll(currentCopy); - } - } - - /** - * Performs the resource upgrade. First, a full inventory report is pulled down from the - * server to ensure we have an up-to-date picture of the inventory. - * After that a full discovery is performed and both the upgrade report and discovery report - * are sent to the server. - */ - public void run() { - if (!started.getAndSet(true)) { - if (log.isDebugEnabled()) { - log.debug("Starting resource upgrade."); - } - - try { - //pull the inventory down from the server. - //this will ensure that we have an up-to-date info on the - //server inventory before we try to upgrade. - boolean syncResult = inventoryManager.handleReport(new InventoryReport(inventoryManager.getAgent()), true); - if (!syncResult) { - log.warn("Resource upgrade failed to sync up the inventory with the server."); - return; - } - - //fire off the full discovery - inventoryManager.executeServerScanImmediately(); - inventoryManager.executeServiceScanImmediately(); - } catch (Throwable t) { - log.warn("Resource upgrade failed.", t); - } finally { - //make sure to switch off the upgrade... - this.enabled.set(false); - - //clear up so that we don't hold unnecessary instances. - requests.clear(); - - if (log.isDebugEnabled()) { - log.debug("Resource upgrade finished."); - } - } - - } else { - if (log.isDebugEnabled()) { - log.debug("ResourceUpgradeExecutor already ran before. Skipping the execution."); - } - } - } - - /** - * Executes the resource upgrade request on the agent (if the appropriate discovery component support {@link ResourceUpgradeFacet}). - * - * @param request the upgrade request to execute on the agent. - * @param discoveredResources the set of the discovered resources that this method can remove some elements from - * @return the resulting upgrade map as reported by the plugin from {@link ResourceUpgradeFacet#upgrade(Set, ResourceUpgradeContext, Set)} method. - * - * @throws PluginContainerException - */ - private <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> executeResourceUpgradeAndStoreRequest( - ResourceUpgradePendingRequest<T> request, Set<Resource> discoveredResources) { - - ResourceDiscoveryContext<T> discoveryContext = request.getDiscoveryContext(); - Set<Resource> newResources = request.getDiscoveredResources(); - Integer parentResourceId = request.getParentResourceId(); - - try { - ResourceType resourceType = discoveryContext.getResourceType(); - ResourceContainer parentResourceContainer = null; - Resource parentResource = null; - if (parentResourceId != null) { - parentResourceContainer = inventoryManager.getResourceContainer(parentResourceId); - if (parentResourceContainer != null) { - parentResource = parentResourceContainer.getResource(); - } - } - - @SuppressWarnings("unchecked") - ResourceDiscoveryComponent<T> discoveryComponent = PluginContainer.getInstance() - .getPluginComponentFactory().getDiscoveryComponent(resourceType, parentResourceContainer); - - ResourceContext<?> parentResourceContext = discoveryContext.getParentResourceContext(); - - T parentComponent = discoveryContext.getParentResourceComponent(); - - //check if the discovery component supports resource upgrade - //if it does, perform the resource upgrade straight away here during the discovery process. - if (discoveryComponent instanceof ResourceUpgradeFacet) { - //the siblings are the resources of the type that is currently being discovered that are already - //present in the inventory. These are the candidate resources for the upgrade. - Set<Resource> siblings = parentResource == null ? Collections.singleton(inventoryManager.getPlatform()) - : inventoryManager.getResourcesWithType(resourceType, parentResource.getChildResources()); - - //filter out not committed resources - //XXX what about uninventoried or ignored ones? is it correct to not upgrade those? - Iterator<Resource> siblingsIterator = siblings.iterator(); - while (siblingsIterator.hasNext()) { - if (siblingsIterator.next().getInventoryStatus() != InventoryStatus.COMMITTED) { - siblingsIterator.remove(); - } - } - - //get the upgrade context of the parent resource so that it can be passed to the upgrade method - //of the discovery component. - ResourceUpgradeContext<?> parentUpgradeContext = null; - - if (parentResource != null) { - Resource grandParent = parentResource.getParentResource(); - ResourceContainer grandParentContainer = grandParent == null ? null : inventoryManager - .getResourceContainer(grandParent); - - @SuppressWarnings("unchecked") - ResourceDiscoveryComponent<ResourceComponent> parentDiscoveryComponent = PluginContainer - .getInstance().getPluginComponentFactory().getDiscoveryComponent( - parentResource.getResourceType(), grandParentContainer); - - ResourceComponent<?> grandParentResourceComponent = grandParentContainer == null ? null - : grandParentContainer.getResourceComponent(); - - parentUpgradeContext = inventoryManager.createResourceUpgradeContext(parentResource, - grandParentResourceComponent, parentDiscoveryComponent); - } - - //convert the sibling resources into upgrade context objects so that the plugin methods don't access the - //domain objects directly. - Set<ResourceUpgradeContext<T>> siblingContexts = new HashSet<ResourceUpgradeContext<T>>(siblings.size()); - - //but we are going to need to update the resources in the end, so map the contexts with the resources. - Map<ResourceUpgradeContext<T>, Resource> siblingContextToResource = new HashMap<ResourceUpgradeContext<T>, Resource>(); - - for (Resource sibling : siblings) { - ResourceUpgradeContext<T> siblingContext = inventoryManager.createResourceUpgradeContext(sibling, - parentComponent, discoveryComponent); - siblingContexts.add(siblingContext); - siblingContextToResource.put(siblingContext, sibling); - } - - //convert the new resources into contexts. - //map the resources by resource key so that we can later check for uniqueness of the reported results. - Set<ResourceUpgradeContext<T>> newResourceContexts = new HashSet<ResourceUpgradeContext<T>>(); - Map<String, Resource> newResourceKeyToResource = new HashMap<String, Resource>(); - - for (Resource newResource : newResources) { - ResourceUpgradeContext<T> newUpgradeContext = inventoryManager.createResourceUpgradeContext( - newResource, parentComponent, discoveryComponent); - newResourceContexts.add(newUpgradeContext); - newResourceKeyToResource.put(newResource.getResourceKey(), newResource); - } - - //ask the discovery component to upgrade the siblings. - Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> results; - try { - results = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resourceType, - discoveryComponent, siblingContexts, parentUpgradeContext, newResourceContexts); - - //now go through the results and create the upgrade requests. - for (Map.Entry<ResourceUpgradeContext<T>, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { - Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); - ResourceUpgradeRequest newData = new ResourceUpgradeRequest(siblingToUpgrade.getId(), upgradeEntry.getValue()); - - requests.add(newData); - - //if there was a resource key upgrade, remove a resource with the same resource key - //from the discovery results. Otherwise we'd end up with 2 sibling resources with - //the same resource key, which is illegal. - if (newData.getNewResourceKey() != null) { - Resource newResourceToRemove = newResourceKeyToResource.get(newData.getNewResourceKey()); - if (newResourceToRemove != null) { - discoveredResources.remove(newResourceToRemove); - } - } - } - - return results; - } catch (Throwable t) { - log.warn("Exception in discovery component " + discoveryComponent.getClass() + " upgrade method.", - t); - } - } - } catch (PluginContainerException e) { - log.warn("Failed resource upgrade of children of resource id " + parentResourceId, e); - } - return null; - } -} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java deleted file mode 100644 index 1099643..0000000 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.rhq.core.pc.upgrade; - -import java.util.Set; - -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; - -/** - * This class is used to store the requests for resource upgrade that originate in - * the discovery workflow, but can only be executed after an inventory sync. - */ -public class ResourceUpgradePendingRequest<T extends ResourceComponent> { - private Set<Resource> discoveredResources; - private ResourceDiscoveryContext<T> discoveryContext; - private Integer parentResourceId; - - public ResourceUpgradePendingRequest(Set<Resource> discoveredResources, ResourceDiscoveryContext<T> discoveryContext, Integer parentResourceId) { - this.discoveredResources = discoveredResources; - this.discoveryContext = discoveryContext; - this.parentResourceId = parentResourceId; - } - - public Set<Resource> getDiscoveredResources() { - return discoveredResources; - } - - public ResourceDiscoveryContext<T> getDiscoveryContext() { - return discoveryContext; - } - - public Integer getParentResourceId() { - return parentResourceId; - } -} \ No newline at end of file diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 087b46f..b5d571f 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -151,34 +151,8 @@ public class ResourceUpgradeTest { }
@Test - public void testResourceUpgradeRunsOnlyOnce() throws Exception { - currentServerSideInventory = new FakeServerInventory(); - initialSyncAndDiscovery(InventoryStatus.COMMITTED); - - executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, new TestPayload() { - public void test(Resource discoveredResource) { - for(int i = 0; i < 100; i++) { - PluginContainer.getInstance().getInventoryManager().fireResourceUpgrade(); - } - } - - @SuppressWarnings("unchecked") - public Expectations getExpectations(Mockery context) throws Exception { - return new Expectations() { - { - defineDefaultExpectations(this); - - between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); - will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); - - //even though we fire the resource upgrade 100 times above, - //only 1 upgrade should actually occur and go up to the server. - oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); - will(currentServerSideInventory.upgradeResources()); - } - }; - } - }); + public void testRecoveryWithServerUnavailable() throws Exception { + //TODO implement }
private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { diff --git a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar index 412ae00..7ffc5bb 100644 Binary files a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar and b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar differ diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 329f476..add8168 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -20,7 +20,6 @@ package org.rhq.enterprise.server.discovery;
import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; 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 7fe7a5e..de265eb 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 @@ -1715,8 +1715,16 @@ public class ResourceManagerBean implements ResourceManagerLocal, ResourceManage Query query = entityManager.createNamedQuery(Resource.QUERY_FIND_PLATFORM_BY_AGENT); query.setParameter("category", ResourceCategory.PLATFORM); query.setParameter("agent", agent); - Resource platform = (Resource) query.getSingleResult(); - return platform; + + try { + Resource platform = (Resource) query.getSingleResult(); + return platform; + } catch (NoResultException e) { + //this means that the agent didn't send any info to us yet. + //this can happen during the inital resource upgrade sync between + //the agent and server. + return null; + } }
@SuppressWarnings("unchecked") diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java index 327c439..faf0b11 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/ResourceManagerLocal.java @@ -376,7 +376,7 @@ public interface ResourceManagerLocal { * * @param agent an Agent * - * @return the platform Resource associated with the specified Agent + * @return the platform Resource associated with the specified Agent or null if the platform for the agent is not known yet. */ Resource getPlatform(Agent agent);
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index 362a1df..c31d153 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -170,45 +170,40 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return discoveredResources; }
- public Map<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext<PlatformComponent>> inventoriedSiblings, - ResourceUpgradeContext<?> parentContext, Set<ResourceUpgradeContext<PlatformComponent>> discoveryResults) { - - Map<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport> ret = new HashMap<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport>(); - - for (ResourceUpgradeContext context : inventoriedSiblings) { - String inventoriedResourceKey = context.getResourceKey(); - File inventoriedResourceKeyAsPath = new File(inventoriedResourceKey); - - //the resource key we use now is a full path to the httpdconf. - //in the old version, it was the server root. - //so if the inventoried resource key is a path to a file, - //we know it's a new style resource key. - if (inventoriedResourceKeyAsPath.isFile()) { - continue; - } - - Configuration pluginConfiguration = context.getPluginConfiguration(); - - String serverRoot = pluginConfiguration.getSimpleValue("serverRoot", null); - String httpdConf = pluginConfiguration.getSimpleValue("configFile", null); - - String resourceKey = null; - - if (httpdConf != null) { - File httpdConfFile = new File(httpdConf); - if (!httpdConfFile.isAbsolute()) { - httpdConfFile = new File(serverRoot, httpdConf); - } - - resourceKey = httpdConfFile.getPath(); - - ResourceUpgradeReport rep = new ResourceUpgradeReport(); - rep.setNewResourceKey(resourceKey); - - ret.put(context, rep); + public ResourceUpgradeReport upgrade(ResourceUpgradeContext<PlatformComponent> context) { + String inventoriedResourceKey = context.getResourceKey(); + File inventoriedResourceKeyAsPath = new File(inventoriedResourceKey); + + //the resource key we use now is a full path to the httpd.conf. + //in the old version, it was the server root. + //so if the inventoried resource key is a path to a file, + //we know it's a new style resource key. + if (inventoriedResourceKeyAsPath.isFile()) { + return null; + } + + Configuration pluginConfiguration = context.getPluginConfiguration(); + + String serverRoot = pluginConfiguration.getSimpleValue("serverRoot", null); + String httpdConf = pluginConfiguration.getSimpleValue("configFile", null); + + String resourceKey = null; + + if (httpdConf != null) { + File httpdConfFile = new File(httpdConf); + if (!httpdConfFile.isAbsolute()) { + httpdConfFile = new File(serverRoot, httpdConf); } + + resourceKey = httpdConfFile.getPath(); + + ResourceUpgradeReport rep = new ResourceUpgradeReport(); + rep.setNewResourceKey(resourceKey); + + return rep; } - return ret; + + return null; }
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig,
commit 00b2aae2f27dd64092eee3c2d09df33e48736e10 Merge: 90ca72b... ed06919... Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jul 2 14:25:47 2010 +0200
Merge branch 'release-3.0.0' into resource-upgrade
diff --cc modules/core/dbutils/pom.xml index 2013b3d,d536ce6..96685db --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@@ -22,7 -22,7 +22,7 @@@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> -- <db.schema.version>2.88</db.schema.version> ++ <db.schema.version>2.89</db.schema.version> </properties>
<dependencies> diff --cc modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml index 3ee8217,7f8f9da..20e9d2f --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@@ -2994,15 -3000,17 +3000,27 @@@ </statement> </schema-directSQL> </schemaSpec> - - <schemaSpec version="2.88"> + + <schemaSpec version="2.88"> + <schema-directSQL> + <statement desc="Add end time index on call time data to speed up purges"> + CREATE INDEX RHQ_CT_DA_VA_END_TIM_IDX ON RHQ_CALLTIME_DATA_VALUE (end_time) + </statement> + <statement desc="Add index on measurement definition numeric type"> + CREATE INDEX RHQ_METRIC_DEF_NT_IDX ON RHQ_MEASUREMENT_DEF (numeric_type) + </statement> + </schema-directSQL> + </schemaSpec> ++ ++ <schemaSpec version="2.89"> + <schema-directSQL> + <statement desc="Adding 'Allow Agent Plugins To Upgrade Generic Resource Properties' system configuration setting"> + INSERT INTO rhq_system_config (id, property_key, property_value, default_property_value) + VALUES (56, 'RESOURCE_GENERIC_PROPERTIES_UPGRADE', 'false', 'false') + </statement> + </schema-directSQL> + </schemaSpec> ++ </dbupgrade> </target> </project>
commit 90ca72b3aa73f41165ab2d616f53f12d642bef7d Merge: 5449040... b9ca90d... Author: Lukas Krejci lkrejci@redhat.com Date: Wed Jun 23 19:01:34 2010 +0200
Merge branch 'release-3.0.0' into resource-upgrade
commit 54490406d19753524b052beeab418af68bf68c2c Author: Lukas Krejci lkrejci@redhat.com Date: Wed Jun 23 15:41:36 2010 +0200
Restructuring the tests a bit, adding a test for correct reinitialization of the agent inventory from the server inventory during the resource upgrade.
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java index 46d069c..087b46f 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -49,6 +49,7 @@ import org.rhq.core.clientapi.server.event.EventServerService; import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService; import org.rhq.core.clientapi.server.measurement.MeasurementServerService; import org.rhq.core.clientapi.server.operation.OperationServerService; +import org.rhq.core.domain.discovery.AvailabilityReport; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; @@ -64,6 +65,7 @@ import org.rhq.core.pc.plugin.FileSystemPluginFinder; * * @author Lukas Krejci */ +@Test(sequential = true, invocationCount = 1) public class ResourceUpgradeTest {
private static final String PLUGIN_V1_FILENAME = "resource-upgrade-test-plugin-1.0.0.jar"; @@ -100,7 +102,7 @@ public class ResourceUpgradeTest { verifyPluginExists(PLUGIN_V2_FILENAME); }
- @BeforeClass + @BeforeClass(dependsOnMethods = "sanityCheck") public void init() { tmpDir = getTmpDirectory(); pluginDir = new File(tmpDir, PLUGINS_DIR_NAME); @@ -110,12 +112,10 @@ public class ResourceUpgradeTest { }
@Test - public void testInitialSyncAndDiscoveryWithoutCommit() throws Exception { - testInitialSyncAndDiscovery(InventoryStatus.NEW); - } - - @Test(dependsOnMethods = "testInitialSyncAndDiscoveryWithoutCommit") public void testIgnoreUncommittedResources() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + initialSyncAndDiscovery(InventoryStatus.NEW); + TestPayload testNoChange = new TestPayload() { public void test(Resource discoveredResource) { assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); @@ -123,17 +123,13 @@ public class ResourceUpgradeTest { assertEquals(discoveredResource.getDescription(), "resource-description-v1"); }
- @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { - defineIgnoredExpectations(this); + defineDefaultExpectations(this);
between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); - - allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); - will(currentServerSideInventory.getResources()); } }; } @@ -142,52 +138,50 @@ public class ResourceUpgradeTest { executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, testNoChange); }
- //make the tests run serially, so that they don't overwrite the currentServerSideInventory - //variable concurrently - @Test(dependsOnMethods = "testIgnoreUncommittedResources") - public void testInitialSyncAndDiscoveryWithCommit() throws Exception { - testInitialSyncAndDiscovery(InventoryStatus.COMMITTED); - } - - @Test(dependsOnMethods = "testInitialSyncAndDiscoveryWithCommit") + @Test public void testUpgradeData() throws Exception { - //we are keeping the currentServerSideInventory from the previous test + currentServerSideInventory = new FakeServerInventory(); + upgradeTest(false); + } + + @Test + public void testInventoryReinitializationFromServerDuringUpgrade() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + upgradeTest(true); + } + + @Test + public void testResourceUpgradeRunsOnlyOnce() throws Exception { + currentServerSideInventory = new FakeServerInventory(); + initialSyncAndDiscovery(InventoryStatus.COMMITTED); + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, new TestPayload() { public void test(Resource discoveredResource) { - assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); - assertEquals(discoveredResource.getName(), "resource-name-v2"); - assertEquals(discoveredResource.getDescription(), "resource-description-v2"); - - ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); - File dataDir = container.getResourceContext().getDataDirectory(); - - File marker = new File(dataDir, "upgrade-succeeded"); - - assertTrue(marker.exists(), "The upgrade success marker file wasn't found. This means the upgrade didn't actually run."); + for(int i = 0; i < 100; i++) { + PluginContainer.getInstance().getInventoryManager().fireResourceUpgrade(); + } }
@SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { - defineIgnoredExpectations(this); + defineDefaultExpectations(this);
between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED));
+ //even though we fire the resource upgrade 100 times above, + //only 1 upgrade should actually occur and go up to the server. oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); will(currentServerSideInventory.upgradeResources()); - - allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); - will(currentServerSideInventory.getResources()); } }; } }); }
- private void testInitialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { - currentServerSideInventory = new FakeServerInventory(); + private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), true, new TestPayload() { public void test(Resource discoveredResource) { assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); @@ -195,17 +189,13 @@ public class ResourceUpgradeTest { assertEquals(discoveredResource.getDescription(), "resource-description-v1"); }
- @SuppressWarnings("unchecked") public Expectations getExpectations(Mockery context) throws Exception { return new Expectations() { { - defineIgnoredExpectations(this); + defineDefaultExpectations(this);
between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); will(currentServerSideInventory.mergeInventoryReport(requiredInventoryStatus)); - - allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); - will(currentServerSideInventory.getResources()); } }; } @@ -213,6 +203,40 @@ public class ResourceUpgradeTest {
}
+ private void upgradeTest(boolean clearInventoryDat) throws Exception { + initialSyncAndDiscovery(InventoryStatus.COMMITTED); + + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), clearInventoryDat, new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); + assertEquals(discoveredResource.getName(), "resource-name-v2"); + assertEquals(discoveredResource.getDescription(), "resource-description-v2"); + + ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + File dataDir = container.getResourceContext().getDataDirectory(); + + File marker = new File(dataDir, "upgrade-succeeded"); + + assertTrue(marker.exists(), "The upgrade success marker file wasn't found. This means the upgrade didn't actually run."); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineDefaultExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + will(currentServerSideInventory.upgradeResources()); + } + }; + } + }); + } + private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception { PluginContainerConfiguration conf = new PluginContainerConfiguration();
@@ -223,6 +247,15 @@ public class ResourceUpgradeTest { conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory())); conf.setCreateResourceClassloaders(false);
+ //we're not interested in any scans happening out of our control + conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE); + conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setEventSenderInitialDelay(Long.MAX_VALUE); + conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE); + conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE); + conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE); + currentBundleServerService = context.mock(BundleServerService.class); currentConfigurationServerService = context.mock(ConfigurationServerService.class); currentContentServerService = context.mock(ContentServerService.class); @@ -332,7 +365,8 @@ public class ResourceUpgradeTest { context.assertIsSatisfied(); }
- private void defineIgnoredExpectations(Expectations expectations) { + @SuppressWarnings("unchecked") + private void defineDefaultExpectations(Expectations expectations) { expectations.ignoring(currentBundleServerService); expectations.ignoring(currentConfigurationServerService); expectations.ignoring(currentContentServerService); @@ -341,5 +375,11 @@ public class ResourceUpgradeTest { expectations.ignoring(currentMeasurementServerService); expectations.ignoring(currentOperationServerService); expectations.ignoring(currentResourceFactoryServerService); + + //just ignore these invocations if we get a availability scan in the PC... + expectations.allowing(currentDiscoveryServerService).mergeAvailabilityReport(expectations.with(Expectations.any(AvailabilityReport.class))); + + expectations.allowing(currentDiscoveryServerService).getResources(expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class))); + expectations.will(currentServerSideInventory.getResources()); } }
commit 0d5d63e1ed0825ddc0ea256b695a66c980b69e6e Author: Lukas Krejci lkrejci@redhat.com Date: Wed Jun 23 15:40:16 2010 +0200
Forgot to bump the db version.
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml index 92ae1d2..2013b3d 100644 --- a/modules/core/dbutils/pom.xml +++ b/modules/core/dbutils/pom.xml @@ -22,7 +22,7 @@
<properties> <scm.module.path>modules/core/dbutils/</scm.module.path> - <db.schema.version>2.87</db.schema.version> + <db.schema.version>2.88</db.schema.version> </properties>
<dependencies>
commit 7f8310f4d3648ba3386fda883563bdcc8c5d1492 Author: Lukas Krejci lkrejci@redhat.com Date: Wed Jun 23 15:39:54 2010 +0200
Adding the server side system config property for controlling whether to allow resource name and description upgrades.
diff --git a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/config/SystemConfigForm.java b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/config/SystemConfigForm.java index 237858d..508a4ac 100644 --- a/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/config/SystemConfigForm.java +++ b/modules/enterprise/gui/portal-war/src/main/java/org/rhq/enterprise/gui/admin/config/SystemConfigForm.java @@ -66,7 +66,8 @@ public class SystemConfigForm extends BaseValidatorForm { private String ldapPassword = ""; private Boolean ldapEnabled = null; private boolean reindex = false; - + private boolean allowResourceGenericPropertiesUpgrade; + @Override public String toString() { StringBuffer buf = new StringBuffer(super.toString()); @@ -230,6 +231,8 @@ public class SystemConfigForm extends BaseValidatorForm { String jaasProvider = prop.getProperty(RHQConstants.JAASProvider); ldapEnabled = RHQConstants.LDAPJAASProvider.equals(jaasProvider) ? Boolean.TRUE : null;
+ String resourceGenericPropertiesUpgradeAllowed = prop.getProperty(RHQConstants.AllowResourceGenericPropertiesUpgrade); + allowResourceGenericPropertiesUpgrade = Boolean.parseBoolean(resourceGenericPropertiesUpgradeAllowed); }
/** @@ -332,6 +335,8 @@ public class SystemConfigForm extends BaseValidatorForm { prop.setProperty(RHQConstants.JAASProvider, RHQConstants.JDBCJAASProvider); }
+ prop.setProperty(RHQConstants.AllowResourceGenericPropertiesUpgrade, String.valueOf(allowResourceGenericPropertiesUpgrade)); + return prop; }
@@ -608,6 +613,14 @@ public class SystemConfigForm extends BaseValidatorForm { public void setReindex(boolean reindex) { this.reindex = reindex; } + + public boolean isAllowResourceGenericPropertiesUpgrade() { + return allowResourceGenericPropertiesUpgrade; + } + + public void setAllowResourceGenericPropertiesUpgrade(boolean allowResourceGenericPropertiesUpgrade) { + this.allowResourceGenericPropertiesUpgrade = allowResourceGenericPropertiesUpgrade; + }
/* (non-Javadoc) * @see org.apache.struts.action.ActionForm#validate(org.apache.struts.action.ActionMapping, diff --git a/modules/enterprise/gui/portal-war/src/main/webapp-filtered/WEB-INF/classes/ApplicationResources.properties b/modules/enterprise/gui/portal-war/src/main/webapp-filtered/WEB-INF/classes/ApplicationResources.properties index f02efb5..83f42f0 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp-filtered/WEB-INF/classes/ApplicationResources.properties +++ b/modules/enterprise/gui/portal-war/src/main/webapp-filtered/WEB-INF/classes/ApplicationResources.properties @@ -667,6 +667,8 @@ admin.settings.ServerPluginsConfigPropTab=Server Plugins Configuration Propertie admin.settings.UseCAMAuth=Use ${product.shortName} Internal Authentication admin.settings.UseLDAPAuth=Use LDAP Authentication
+admin.settings.AllowResourceGenericPropertiesUpgrade=Allow Agent Plugins To Upgrade Generic Resource Properties + admin.settings.error.DeleteUnitsField=Value must be between 1 and 7 days. admin.settings.error.InvalidSNMPTrapOID=SNMP Trap OID invalid, please enter OID in form of 1.2.3.4. admin.settings.error.InvalidSNMPEngineID=SNMP Engine ID is invalid, must be a valid number. diff --git a/modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp b/modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp index 30df9ef..136c37c 100644 --- a/modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp +++ b/modules/enterprise/gui/portal-war/src/main/webapp/admin/config/GeneralPropertiesConfigForm.jsp @@ -86,6 +86,17 @@ </table> </td> </tr> + <tr> + <td class="BlockLabel"><fmt:message key="admin.settings.AllowResourceGenericPropertiesUpgrade"/></td> + <td class="BlockContent"> + <table cellpadding="0" cellspacing="4" border="0"> + <tr> + <td align="left"><html:radio property="allowResourceGenericPropertiesUpgrade" value="true"/><fmt:message key="yesno.true"/></td> + <td align="left"><html:radio property="allowResourceGenericPropertiesUpgrade" value="false"/><fmt:message key="yesno.false"/></td> + </tr> + </table> + </td> + </tr>
<hq:authorization permission="superuser"> <tr>
commit 6c2472739d2df4b5a99f1e4fae22b945440dd5fd Author: Lukas Krejci lkrejci@redhat.com Date: Wed Jun 23 15:29:15 2010 +0200
Adding the ability of the server to alter/ignore some upgrade data.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java new file mode 100644 index 0000000..825a616 --- /dev/null +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeRequest.java @@ -0,0 +1,55 @@ +/* + * 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, 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.clientapi.agent.upgrade; + +import org.rhq.core.domain.resource.ResourceUpgradeReport; + +/** + * Represents a request to upgrade a resource. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeRequest extends ResourceUpgradeReport { + + private int resourceId; + + public ResourceUpgradeRequest() { + + } + + public ResourceUpgradeRequest(int resourceId, ResourceUpgradeReport report) { + setResourceId(resourceId); + setNewDescription(report.getNewDescription()); + setNewName(report.getNewName()); + setNewResourceKey(report.getNewResourceKey()); + } + + public int getResourceId() { + return resourceId; + } + + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } +} diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeResponse.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeResponse.java new file mode 100644 index 0000000..3faa9ef --- /dev/null +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/upgrade/ResourceUpgradeResponse.java @@ -0,0 +1,80 @@ +/* + * 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, 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.clientapi.agent.upgrade; + +import java.io.Serializable; + +/** + * Represents a response to a resource upgrade request. + * The upgraded* properties contain the values of the corresponding resource properties + * as they were stored on the server. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeResponse implements Serializable { + + private static final long serialVersionUID = 1L; + + private int resourceId; + + private String upgradedResourceName; + private String upgradedResourceKey; + private String upgradedResourceDescription; + + public ResourceUpgradeResponse() { + + } + + public int getResourceId() { + return resourceId; + } + + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } + + public String getUpgradedResourceName() { + return upgradedResourceName; + } + + public void setUpgradedResourceName(String upgradedResourceName) { + this.upgradedResourceName = upgradedResourceName; + } + + public String getUpgradedResourceKey() { + return upgradedResourceKey; + } + + public void setUpgradedResourceKey(String upgradedResourceKey) { + this.upgradedResourceKey = upgradedResourceKey; + } + + public String getUpgradedResourceDescription() { + return upgradedResourceDescription; + } + + public void setUpgradedResourceDescription(String upgradedResourceDescription) { + this.upgradedResourceDescription = upgradedResourceDescription; + } +} diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java index 61e5084..0622fc5 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java @@ -29,6 +29,8 @@ import org.rhq.core.communications.command.annotation.Asynchronous; import org.rhq.core.communications.command.annotation.LimitedConcurrency; import org.rhq.core.communications.command.annotation.Timeout; import org.rhq.core.domain.discovery.AvailabilityReport; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.discovery.MergeResourceResponse; import org.rhq.core.domain.discovery.ResourceSyncInfo; @@ -37,7 +39,6 @@ import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.ResourceErrorType; -import org.rhq.core.domain.resource.ResourceUpgradeReport;
/** * The interface to a JON server's resource discovery subsystem. @@ -139,11 +140,13 @@ public interface DiscoveryServerService {
/** * Upgrades the data of the resources according to the provided reports. + * The server is free to ignore or modify the requests and will provide the + * true changes made to the resources on the server-side in the result of this method. * - * @param upgradeReports contains the information about the upgrade of individual resources. - * @return true if the upgrade succeeded, false otherwise. + * @param upgradeRequests contains the information about the upgrade of individual resources. + * @return details on what resources have been upgraded with what data. */ - boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports); + Set<ResourceUpgradeResponse> upgradeResources(Set<ResourceUpgradeRequest> upgradeRequests);
/** * Gives the server a chance to apply any necessary post-processing that's needed for newly committed resources 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 26d648e..121e971 100644 --- a/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml +++ b/modules/core/dbutils/src/main/scripts/dbsetup/sysconfig-data.xml @@ -121,6 +121,9 @@ <!-- How old does availability have to be in order to get purged --> <data ID="55" PROPERTY_KEY="AVAILABILITY_PURGE" PROPERTY_VALUE="31536000000" DEFAULT_PROPERTY_VALUE="31536000000" FREAD_ONLY="FALSE"/> + + <data ID="56" PROPERTY_KEY="RESOURCE_GENERIC_PROPERTIES_UPGRADE" PROPERTY_VALUE="false" + DEFAULT_PROPERTY_VALUE="false" 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 71aa297..ad53803 100644 --- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml +++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml @@ -2994,6 +2994,14 @@ </schema-directSQL> </schemaSpec>
+ <schemaSpec version="2.88"> + <schema-directSQL> + <statement desc="Adding 'Allow Agent Plugins To Upgrade Generic Resource Properties' system configuration setting"> + INSERT INTO rhq_system_config (id, property_key, property_value, default_property_value) + VALUES (56, 'RESOURCE_GENERIC_PROPERTIES_UPGRADE', 'false', 'false') + </statement> + </schema-directSQL> + </schemaSpec> </dbupgrade> </target> </project> diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java index 979c456..0f9db04 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java @@ -41,7 +41,6 @@ public class ResourceUpgradeReport implements Serializable {
private static final long serialVersionUID = 1L;
- private int resourceId; private String newResourceKey; private String newName;
@@ -62,22 +61,6 @@ public class ResourceUpgradeReport implements Serializable {
}
- /** - * The server-side id of the resource being upgraded. - * The discovery components don't need to assign this value. - */ - public int getResourceId() { - return resourceId; - } - - /** - * The server-side id of the resource being upgraded. - * The discovery components don't need to assign this value. - */ - public void setResourceId(int resourceId) { - this.resourceId = resourceId; - } - public String getNewResourceKey() { return newResourceKey; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 6c3d26a..b5f5f00 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -55,6 +55,8 @@ import org.rhq.core.clientapi.agent.configuration.ConfigurationUtility; import org.rhq.core.clientapi.agent.discovery.DiscoveryAgentService; import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException; import org.rhq.core.clientapi.agent.metadata.PluginMetadataManager; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.DiscoveryServerService; import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; @@ -92,7 +94,7 @@ import org.rhq.core.pc.plugin.CanonicalResourceKey; import org.rhq.core.pc.plugin.PluginComponentFactory; import org.rhq.core.pc.plugin.PluginManager; import org.rhq.core.pc.upgrade.ResourceUpgradeExecutor; -import org.rhq.core.pc.upgrade.ResourceUpgradeRequest; +import org.rhq.core.pc.upgrade.ResourceUpgradePendingRequest; import org.rhq.core.pc.util.DiscoveryComponentProxyFactory; import org.rhq.core.pc.util.FacetLockType; import org.rhq.core.pc.util.LoggingThreadFactory; @@ -1178,31 +1180,31 @@ public class InventoryManager extends AgentService implements ContainerService, return resourceContainer.updateAvailability(availabilityType); }
- public boolean mergeResourceFromUpgrade(Set<ResourceUpgradeReport> upgradeReports) { - boolean serverUpdated = false; + public void mergeResourceFromUpgrade(Set<ResourceUpgradeRequest> upgradeReports) { + Set<ResourceUpgradeResponse> serverUpdates = null; try { ServerServices serverServices = this.configuration.getServerServices(); if (serverServices != null) { DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService();
- serverUpdated = discoveryServerService.upgradeResources(upgradeReports); + serverUpdates = discoveryServerService.upgradeResources(upgradeReports); } } catch (Exception e) { log.error("Failed to process resource upgrades on the server.", e); }
- if (serverUpdated) { - for (ResourceUpgradeReport upgradeReport : upgradeReports) { - String resourceKey = upgradeReport.getNewResourceKey(); - String name = upgradeReport.getNewName(); + if (serverUpdates != null) { + for (ResourceUpgradeResponse upgradeResponse : serverUpdates) { + String resourceKey = upgradeResponse.getUpgradedResourceKey(); + String name = upgradeResponse.getUpgradedResourceName(); //String version = upgradeReport.getNewVersion(); - String description = upgradeReport.getNewDescription(); + String description = upgradeResponse.getUpgradedResourceDescription(); //Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); //Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
//only bother if there's something to upgrade at all on this resource. if (resourceKey != null || name != null || description != null) { - ResourceContainer existingResourceContainer = getResourceContainer(upgradeReport.getResourceId()); + ResourceContainer existingResourceContainer = getResourceContainer(upgradeResponse.getResourceId()); if (existingResourceContainer != null) { Resource existingResource = existingResourceContainer.getResource();
@@ -1241,13 +1243,11 @@ public class InventoryManager extends AgentService implements ContainerService,
log.info(logMessage.toString()); } else { - log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeReport.getResourceId()); + log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeResponse.getResourceId()); } } } } - - return serverUpdated; }
public Resource mergeResourceFromDiscovery(Resource resource, Resource parent) throws PluginContainerException { @@ -2173,7 +2173,7 @@ public class InventoryManager extends AgentService implements ContainerService, }
if (resourceUpgradeExecutor.isEnabled()) { - resourceUpgradeExecutor.processAndQueue(new ResourceUpgradeRequest(newResources, context, parentResource.getId()), newResources); + resourceUpgradeExecutor.processAndQueue(new ResourceUpgradePendingRequest(newResources, context, parentResource.getId()), newResources); } } catch (Throwable e) { // TODO GH: Add server/parent - up/down semantics so this won't happen just because a server is not up diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index bb20054..f344900 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -29,7 +29,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean;
@@ -37,6 +36,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.agent.PluginContainerException; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; @@ -69,11 +69,11 @@ public class ResourceUpgradeExecutor implements Runnable {
private InventoryManager inventoryManager;
- private ConcurrentLinkedQueue<ResourceUpgradeReport> reports; + private ConcurrentLinkedQueue<ResourceUpgradeRequest> requests;
public ResourceUpgradeExecutor(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; - reports = new ConcurrentLinkedQueue<ResourceUpgradeReport>(); + requests = new ConcurrentLinkedQueue<ResourceUpgradeRequest>(); }
/** @@ -92,9 +92,9 @@ public class ResourceUpgradeExecutor implements Runnable { * @param discoveredResources the set of discovered resources that this method can optionally remove some elements from. */ public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> processAndQueue( - ResourceUpgradeRequest<T> request, Set<Resource> discoveredResources) { + ResourceUpgradePendingRequest<T> request, Set<Resource> discoveredResources) {
- return enabled.get() ? executeResourceUpgradeAndStoreReport(request, discoveredResources) : null; + return enabled.get() ? executeResourceUpgradeAndStoreRequest(request, discoveredResources) : null; }
/** @@ -109,10 +109,10 @@ public class ResourceUpgradeExecutor implements Runnable { * all the upgrade requests. */ public void sendRequests() { - if (enabled.get() && reports.size() > 0) { - HashSet<ResourceUpgradeReport> currentCopy = new HashSet<ResourceUpgradeReport>(reports); + if (enabled.get() && requests.size() > 0) { + HashSet<ResourceUpgradeRequest> currentCopy = new HashSet<ResourceUpgradeRequest>(requests); inventoryManager.mergeResourceFromUpgrade(currentCopy); - reports.removeAll(currentCopy); + requests.removeAll(currentCopy); } }
@@ -148,7 +148,7 @@ public class ResourceUpgradeExecutor implements Runnable { this.enabled.set(false);
//clear up so that we don't hold unnecessary instances. - reports.clear(); + requests.clear();
if (log.isDebugEnabled()) { log.debug("Resource upgrade finished."); @@ -171,8 +171,8 @@ public class ResourceUpgradeExecutor implements Runnable { * * @throws PluginContainerException */ - private <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> executeResourceUpgradeAndStoreReport( - ResourceUpgradeRequest<T> request, Set<Resource> discoveredResources) { + private <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> executeResourceUpgradeAndStoreRequest( + ResourceUpgradePendingRequest<T> request, Set<Resource> discoveredResources) {
ResourceDiscoveryContext<T> discoveryContext = request.getDiscoveryContext(); Set<Resource> newResources = request.getDiscoveredResources(); @@ -267,14 +267,12 @@ public class ResourceUpgradeExecutor implements Runnable { results = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resourceType, discoveryComponent, siblingContexts, parentUpgradeContext, newResourceContexts);
- //now go through the results and upgrade the resources as needed. + //now go through the results and create the upgrade requests. for (Map.Entry<ResourceUpgradeContext<T>, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); - ResourceUpgradeReport newData = upgradeEntry.getValue(); + ResourceUpgradeRequest newData = new ResourceUpgradeRequest(siblingToUpgrade.getId(), upgradeEntry.getValue());
- //upgrade the data on the server first - newData.setResourceId(siblingToUpgrade.getId()); - reports.add(newData); + requests.add(newData);
//if there was a resource key upgrade, remove a resource with the same resource key //from the discovery results. Otherwise we'd end up with 2 sibling resources with diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java new file mode 100644 index 0000000..1099643 --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradePendingRequest.java @@ -0,0 +1,35 @@ +package org.rhq.core.pc.upgrade; + +import java.util.Set; + +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; + +/** + * This class is used to store the requests for resource upgrade that originate in + * the discovery workflow, but can only be executed after an inventory sync. + */ +public class ResourceUpgradePendingRequest<T extends ResourceComponent> { + private Set<Resource> discoveredResources; + private ResourceDiscoveryContext<T> discoveryContext; + private Integer parentResourceId; + + public ResourceUpgradePendingRequest(Set<Resource> discoveredResources, ResourceDiscoveryContext<T> discoveryContext, Integer parentResourceId) { + this.discoveredResources = discoveredResources; + this.discoveryContext = discoveryContext; + this.parentResourceId = parentResourceId; + } + + public Set<Resource> getDiscoveredResources() { + return discoveredResources; + } + + public ResourceDiscoveryContext<T> getDiscoveryContext() { + return discoveryContext; + } + + public Integer getParentResourceId() { + return parentResourceId; + } +} \ No newline at end of file diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java deleted file mode 100644 index 25178ee..0000000 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.rhq.core.pc.upgrade; - -import java.util.Set; - -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; - -/** - * This class is used to store the requests for resource upgrade that originate in - * the discovery workflow, but can only be executed after an inventory sync. - */ -public class ResourceUpgradeRequest<T extends ResourceComponent> { - private Set<Resource> discoveredResources; - private ResourceDiscoveryContext<T> discoveryContext; - private Integer parentResourceId; - - public ResourceUpgradeRequest(Set<Resource> discoveredResources, ResourceDiscoveryContext<T> discoveryContext, Integer parentResourceId) { - this.discoveredResources = discoveredResources; - this.discoveryContext = discoveryContext; - this.parentResourceId = parentResourceId; - } - - public Set<Resource> getDiscoveredResources() { - return discoveredResources; - } - - public ResourceDiscoveryContext<T> getDiscoveryContext() { - return discoveryContext; - } - - public Integer getParentResourceId() { - return parentResourceId; - } -} \ No newline at end of file diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java index 4341e3a..c3bdbf4 100644 --- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -37,15 +37,17 @@ import java.util.Set; import org.jmock.api.Invocation; import org.jmock.lib.action.CustomAction;
+import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.discovery.ResourceSyncInfo; import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; -import org.rhq.core.domain.resource.ResourceUpgradeReport;
/** - * + * This class represents a server side database store of the inventory for the purposes + * of the ResourceUpgradeTest unit test. * * @author Lukas Krejci */ @@ -89,28 +91,36 @@ public class FakeServerInventory { return new CustomAction("upgradeServerSideInventory") { @SuppressWarnings({"serial", "unchecked"}) public Object invoke(Invocation invocation) throws Throwable { - Set<ResourceUpgradeReport> reports = (Set<ResourceUpgradeReport>) invocation.getParameter(0); - - for (final ResourceUpgradeReport report : reports) { + Set<ResourceUpgradeRequest> requests = (Set<ResourceUpgradeRequest>) invocation.getParameter(0); + Set<ResourceUpgradeResponse> responses = new HashSet<ResourceUpgradeResponse>(); + + for (final ResourceUpgradeRequest request : requests) { Resource resource = findResource(platform, new Resource() { public int getId() { - return report.getResourceId(); + return request.getResourceId(); } }, ID_COMPARATOR); if (resource != null) { - if (report.getNewDescription() != null) { - resource.setDescription(report.getNewDescription()); + if (request.getNewDescription() != null) { + resource.setDescription(request.getNewDescription()); } - if (report.getNewName() != null) { - resource.setName(report.getNewName()); + if (request.getNewName() != null) { + resource.setName(request.getNewName()); }
- if (report.getNewResourceKey() != null) { - resource.setResourceKey(report.getNewResourceKey()); + if (request.getNewResourceKey() != null) { + resource.setResourceKey(request.getNewResourceKey()); } + + ResourceUpgradeResponse resp = new ResourceUpgradeResponse(); + resp.setResourceId(resource.getId()); + resp.setUpgradedResourceName(resource.getName()); + resp.setUpgradedResourceKey(resource.getResourceKey()); + resp.setUpgradedResourceDescription(resource.getDescription()); + responses.add(resp); } } - return true; + return responses; } }; } 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 7bb1d72..fff7872 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 @@ -110,5 +110,8 @@ public class RHQConstants {
// Syslog Actions enabled public static final String SyslogActionsEnabled = "CAM_SYSLOG_ACTIONS_ENABLED"; + + //allow plugin initiated resource name & description upgrades (resource key is always upgradable) + public static final String AllowResourceGenericPropertiesUpgrade = "RESOURCE_GENERIC_PROPERTIES_UPGRADE";
} \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index fd59590..329f476 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -20,8 +20,10 @@ package org.rhq.enterprise.server.discovery;
import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -43,6 +45,8 @@ import org.jetbrains.annotations.Nullable;
import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.auth.Subject; @@ -75,6 +79,7 @@ import org.rhq.enterprise.server.resource.ResourceAvailabilityManagerLocal; import org.rhq.enterprise.server.resource.ResourceManagerLocal; import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal; import org.rhq.enterprise.server.resource.group.ResourceGroupManagerLocal; +import org.rhq.enterprise.server.system.SystemManagerLocal;
/** * SLSB that provides the interface point to the discovery subsystem for the UI layer and the discovery server service. @@ -107,6 +112,8 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot private SubjectManagerLocal subjectManager; @EJB private ProductVersionManagerLocal productVersionManager; + @EJB + private SystemManagerLocal systemManager;
public ResourceSyncInfo mergeInventoryReport(InventoryReport report) throws InvalidInventoryReportException { validateInventoryReport(report); @@ -407,20 +414,19 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot } }
- public boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports) { - for (ResourceUpgradeReport report : upgradeReports) { - Resource existingResource = this.entityManager.find(Resource.class, report.getResourceId()); + public Set<ResourceUpgradeResponse> upgradeResources(Set<ResourceUpgradeRequest> upgradeRequests) { + Set<ResourceUpgradeResponse> result = new HashSet<ResourceUpgradeResponse>(); + + boolean allowGenericPropertiesUpgrade = Boolean.parseBoolean(systemManager.getSystemConfiguration().getProperty(RHQConstants.AllowResourceGenericPropertiesUpgrade, "false")); + + for (ResourceUpgradeRequest request : upgradeRequests) { + Resource existingResource = this.entityManager.find(Resource.class, request.getResourceId()); if (existingResource != null) { - boolean changed = upgradeResource(existingResource, report); - if (changed) { - this.entityManager.merge(existingResource); - } - } else { - this.entityManager.getTransaction().setRollbackOnly(); - return false; + ResourceUpgradeResponse upgradedData = upgradeResource(existingResource, request, allowGenericPropertiesUpgrade); + result.add(upgradedData); } } - return true; + return result; }
/** @@ -471,40 +477,46 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot /** * @param existingResource * @param upgradeReport + * @param allowGenericPropertiesUpgrade name and description are only upgraded if this is true * @return true if the resource was changed, false otherwise */ - private boolean upgradeResource(Resource resource, ResourceUpgradeReport upgradeReport) { - if (resource != null) { - String resourceKey = upgradeReport.getNewResourceKey(); - String name = upgradeReport.getNewName(); + private ResourceUpgradeResponse upgradeResource(@NotNull Resource resource, ResourceUpgradeReport upgradeReport, boolean allowGenericPropertiesUpgrade) { + ResourceUpgradeResponse ret = new ResourceUpgradeResponse(); + ret.setResourceId(resource.getId()); + + String resourceKey = upgradeReport.getNewResourceKey(); + String name = upgradeReport.getNewName(); // String version = upgradeReport.getNewVersion(); - String description = upgradeReport.getNewDescription(); + String description = upgradeReport.getNewDescription(); // Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); // Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); + + if (resourceKey != null || name != null || description != null) { + StringBuilder logMessage = new StringBuilder("Resource [") + .append(resource.toString()).append("] upgraded its "); + + if (needsUpgrade(resource.getResourceKey(), resourceKey)) { + resource.setResourceKey(resourceKey); + logMessage.append("resourceKey, "); + } + ret.setUpgradedResourceKey(resource.getResourceKey()); + + if (allowGenericPropertiesUpgrade && needsUpgrade(resource.getName(), name)) { + resource.setName(name); + logMessage.append("name, "); + } + ret.setUpgradedResourceName(resource.getName());
- if (resourceKey != null || name != null || description != null) { - StringBuilder logMessage = new StringBuilder("Resource [") - .append(resource.toString()).append("] upgraded its "); - - if (needsUpgrade(resource.getResourceKey(), resourceKey)) { - resource.setResourceKey(resourceKey); - logMessage.append("resourceKey, "); - } - - if (needsUpgrade(resource.getName(), name)) { - resource.setName(name); - logMessage.append("name, "); - } - // if (version != null) { // changed = updateResourceVersion(resource, version) || changed; // } - - if (needsUpgrade(resource.getDescription(), description)) { - resource.setDescription(description); - logMessage.append("description, "); - } - + + if (allowGenericPropertiesUpgrade && needsUpgrade(resource.getDescription(), description)) { + resource.setDescription(description); + logMessage.append("description, "); + } + ret.setUpgradedResourceDescription(resource.getDescription()); + // if (pluginConfiguration != null) { // if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { // log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + @@ -525,16 +537,13 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot // resource.setResourceConfiguration(resourceConfiguration); // } // } - - logMessage.replace(logMessage.length() - 1, logMessage.length(), - "to become [").append(resource.toString()).append("]");
- log.info(logMessage.toString()); - - return true; - } + logMessage.replace(logMessage.length() - 1, logMessage.length(), + "to become [").append(resource.toString()).append("]"); + + log.info(logMessage.toString()); } - return false; + return ret; }
private void validateInventoryReport(InventoryReport report) throws InvalidInventoryReportException { @@ -651,9 +660,21 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot */ ResourceType resourceType = resource.getResourceType(); Resource parent = resource; + Subject overlord = subjectManager.getOverlord(); while (parent != null && existingResource == null) { parent = parent.getParentResource(); - existingResource = resourceManager.getResourceByParentAndKey(subjectManager.getOverlord(), parent, + //check if the parent itself is inventoried. This might not be the case + //during initial sync-up for resource upgrade. + Resource existingParent = null; + if (parent != null) { + existingParent = entityManager.find(Resource.class, parent.getId()); + if (existingParent == null) { + //well, this parent is not known to the server, so there's no + //point in trying to find a child of it... + continue; + } + } + existingResource = resourceManager.getResourceByParentAndKey(overlord, existingParent, resource.getResourceKey(), resourceType.getPlugin(), resourceType.getName()); }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java index af518eb..c9208fc 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java @@ -29,6 +29,8 @@ import org.jetbrains.annotations.NotNull;
import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; import org.rhq.core.domain.auth.Subject; @@ -181,9 +183,11 @@ public interface DiscoveryBossLocal extends DiscoveryBossRemote {
/** * Upgrades the data of the resources according to the provided reports. + * The server is free to ignore or modify the requests and will provide the + * true changes made to the resources on the server-side in the result of this method. * - * @param upgradeReports contains the information about the upgrade of individual resources. - * @return true if the upgrade succeeded, false otherwise. + * @param upgradeRequests contains the information about the upgrade of individual resources. + * @return details on what resources have been upgraded with what data. */ - boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports); + Set<ResourceUpgradeResponse> upgradeResources(Set<ResourceUpgradeRequest> upgradeRequest); } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java index 0f90cdc..5dbe59a 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java @@ -25,6 +25,8 @@ import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
+import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeRequest; +import org.rhq.core.clientapi.agent.upgrade.ResourceUpgradeResponse; import org.rhq.core.clientapi.server.discovery.DiscoveryServerService; import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException; import org.rhq.core.clientapi.server.discovery.InventoryReport; @@ -177,9 +179,9 @@ public class DiscoveryServerServiceImpl implements DiscoveryServerService { return discoveryBoss.updateResourceVersion(resourceId, version); }
- public boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports) { + public Set<ResourceUpgradeResponse> upgradeResources(Set<ResourceUpgradeRequest> upgradeRequests) { DiscoveryBossLocal discoveryBoss = LookupUtil.getDiscoveryBoss(); - return discoveryBoss.upgradeResources(upgradeReports); + return discoveryBoss.upgradeResources(upgradeRequests); }
private static Resource convertToPojoResource(Resource resource, boolean includeDescendants) {
commit a479fd3591a15b7422b378a000f213a21b9bf750 Merge: ab45b75... f595c48... Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jun 18 21:19:23 2010 +0200
Merge branch 'release-3.0.0' into resource-upgrade
commit ab45b7518ec6b740899c694c3229746cd0490fd6 Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jun 18 20:25:56 2010 +0200
Basic unit tests of the resource upgrade workflow along with some minor changes in the PC to handle the hardcoded test platform in a normal connected-like scenarios.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataManager.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataManager.java index 63072db..0c5e0b6 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataManager.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/agent/metadata/PluginMetadataManager.java @@ -55,7 +55,7 @@ public class PluginMetadataManager { private Object typesLock = new Object();
private Map<String, PluginMetadataParser> parsersByPlugin = new HashMap<String, PluginMetadataParser>(); - + public PluginMetadataManager() { }
@@ -177,6 +177,9 @@ public class PluginMetadataManager {
@Nullable public ResourceType getType(ResourceType resourceType) { + if (TEST_PLATFORM_TYPE.equals(resourceType)) { + return TEST_PLATFORM_TYPE; + } return getType(resourceType.getName(), resourceType.getPlugin()); }
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index dbee063..1433120 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1369,12 +1369,6 @@ public class InventoryManager extends AgentService implements ContainerService, resourceContainer.setSynchronizationState(ResourceContainer.SynchronizationState.SYNCHRONIZED); } this.resourceContainers.put(resource.getUuid(), resourceContainer); - if (resource.getParentResource() == null) { - // no parent - must be the top level platform - do some things needed for unit tests - if (this.platform.getResourceType().equals(PluginMetadataManager.TEST_PLATFORM_TYPE)) { - resourceContainer.setResourceComponent(createTestPlatformComponent()); - } - } } else { // container already exists, but make sure the classloader exists too if (resourceContainer.getResourceClassLoader() == null) { @@ -1800,6 +1794,13 @@ public class InventoryManager extends AgentService implements ContainerService, Set<DiscoveredResourceDetails> allDiscoveredPlatforms = new HashSet<DiscoveredResourceDetails>(2);
if ((platformTypes != null) && (platformTypes.size() > 0)) { + + //check for fake testing type. If the test platform type is being used, it is always going to be + //the sole platform type available. + if (platformTypes.size() == 1 && platformTypes.contains(PluginMetadataManager.TEST_PLATFORM_TYPE)) { + return getTestPlatform(); + } + // Go through all the platform types that are supported and see if they can detect our platform. for (ResourceType platformType : platformTypes) { try { @@ -1828,7 +1829,7 @@ public class InventoryManager extends AgentService implements ContainerService, .error("Missing platform plugin(s) - falling back to dummy platform impl; this should only occur in tests!"); // TODO: Set sysprop (e.g. rhq.test.mode=true) in integration tests, // and throw a runtime exception here if that sysprop is not set. - return createTestPlatform(); + return getTestPlatform(); }
if (allDiscoveredPlatforms.isEmpty()) { @@ -1870,9 +1871,13 @@ public class InventoryManager extends AgentService implements ContainerService, * resource. This is normally only used during tests. * @return A dummy platform for testing purposes only. */ - private Resource createTestPlatform() { + private Resource getTestPlatform() { ResourceType type = PluginContainer.getInstance().getPluginManager().getMetadataManager().addTestPlatformType(); + if (this.platform != null && this.platform.getResourceType() == type) { + return this.platform; + } Resource platform = new Resource("testkey" + configuration.getContainerName(), "testplatform", type); + platform.setUuid(UUID.randomUUID().toString()); platform.setAgent(this.agent); return platform; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java index 4176353..b9d9cf3 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/plugin/PluginComponentFactory.java @@ -30,6 +30,7 @@ import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.agent.metadata.PluginMetadataManager; +import org.rhq.core.domain.measurement.AvailabilityType; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.pc.ContainerService; @@ -39,6 +40,7 @@ import org.rhq.core.pc.inventory.InventoryManager; import org.rhq.core.pc.inventory.ResourceContainer; import org.rhq.core.pluginapi.inventory.ClassLoaderFacet; import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
/** @@ -129,6 +131,19 @@ public class PluginComponentFactory implements ContainerService { */ public ResourceComponent buildResourceComponent(Resource resource) throws PluginContainerException { ResourceType resourceType = resource.getResourceType(); + if (PluginMetadataManager.TEST_PLATFORM_TYPE.equals(resourceType)) { + return new ResourceComponent() { + public AvailabilityType getAvailability() { + return AvailabilityType.UP; + } + + public void start(ResourceContext context) { + } + + public void stop() { + } + }; + } String className = getPluginManager().getMetadataManager().getComponentClass(resourceType); ClassLoader resourceClassloader = getResourceClassloader(resource); ResourceComponent component = (ResourceComponent) instantiateClass(resourceClassloader, className); diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java new file mode 100644 index 0000000..4341e3a --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/FakeServerInventory.java @@ -0,0 +1,272 @@ +/* + * 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, 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.pc.upgrade; + +import static org.testng.Assert.fail; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.jmock.api.Invocation; +import org.jmock.lib.action.CustomAction; + +import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.discovery.ResourceSyncInfo; +import org.rhq.core.domain.resource.InventoryStatus; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.ResourceUpgradeReport; + +/** + * + * + * @author Lukas Krejci + */ +public class FakeServerInventory { + + private Resource platform; + private Map<String, Resource> resourceStore = new HashMap<String, Resource>(); + private int counter; + + private static final Comparator<Resource> ID_COMPARATOR = new Comparator<Resource>() { + public int compare(Resource o1, Resource o2) { + return o1.getId() - o2.getId(); + } + }; + + private static final Comparator<Resource> RESOURCE_TYPE_COMPARATOR = new Comparator<Resource>() { + public int compare(Resource o1, Resource o2) { + return o1.getResourceType().equals(o2.getResourceType()) ? 0 : o1.getId() - o2.getId(); + } + }; + + //need to synchronize, because resource upgrade is async and can overlap with + //resource discovery. + public synchronized CustomAction mergeInventoryReport(final InventoryStatus requiredInventoryStatus) { + return new CustomAction("updateServerSideInventory") { + public Object invoke(Invocation invocation) throws Throwable { + InventoryReport inventoryReport = (InventoryReport) invocation.getParameter(0); + + for(Resource res : inventoryReport.getAddedRoots()) { + if (res.getParentResource() == Resource.ROOT) { + platform = fakePersist(res, requiredInventoryStatus, new HashSet<String>()); + break; + } + } + return getSyncInfo(); + } + }; + } + + public synchronized CustomAction upgradeResources() { + return new CustomAction("upgradeServerSideInventory") { + @SuppressWarnings({"serial", "unchecked"}) + public Object invoke(Invocation invocation) throws Throwable { + Set<ResourceUpgradeReport> reports = (Set<ResourceUpgradeReport>) invocation.getParameter(0); + + for (final ResourceUpgradeReport report : reports) { + Resource resource = findResource(platform, new Resource() { + public int getId() { + return report.getResourceId(); + } + }, ID_COMPARATOR); + if (resource != null) { + if (report.getNewDescription() != null) { + resource.setDescription(report.getNewDescription()); + } + if (report.getNewName() != null) { + resource.setName(report.getNewName()); + } + + if (report.getNewResourceKey() != null) { + resource.setResourceKey(report.getNewResourceKey()); + } + } + } + return true; + } + }; + } + + public synchronized CustomAction getResources() { + return new CustomAction("getResources") { + @SuppressWarnings("unchecked") + public Object invoke(Invocation invocation) throws Throwable { + Set<Integer> resourceIds = (Set<Integer>)invocation.getParameter(0); + boolean includeDescendants = (Boolean) invocation.getParameter(1); + + return getResources(resourceIds, includeDescendants); + } + }; + } + + @SuppressWarnings("serial") + public synchronized Set<Resource> findResourcesByType(final ResourceType type) { + Set<Resource> result = new HashSet<Resource>(); + if (platform != null) { + findResources(platform, new Resource() { + public ResourceType getResourceType() { + return type; + } + }, result, RESOURCE_TYPE_COMPARATOR); + } + return result; + } + + @SuppressWarnings("serial") + private Set<Resource> getResources(Set<Integer> resourceIds, boolean includeDescendants) { + Set<Resource> result = new HashSet<Resource>(); + + for(final Integer id : resourceIds) { + Resource r = findResource(platform, new Resource() { + public int getId() { + return id; + } + }, ID_COMPARATOR); + if (r != null) { + result.add(r); + + if (includeDescendants) { + for(Resource child : r.getChildResources()) { + result.addAll(getResources(Collections.singleton(child.getId()), true)); + } + } + } + } + + return result; + } + + private Resource fakePersist(Resource agentSideResource, InventoryStatus requiredInventoryStatus, Set<String> inProgressUUIds) { + Resource persisted = resourceStore.get(agentSideResource.getUuid()); + if (!inProgressUUIds.add(agentSideResource.getUuid())) { + return persisted; + } + if (persisted == null) { + persisted = new Resource(); + persisted.setId(++counter); + persisted.setUuid(agentSideResource.getUuid()); + resourceStore.put(persisted.getUuid(), persisted); + } + persisted.setAgent(agentSideResource.getAgent()); + persisted.setCurrentAvailability(agentSideResource.getCurrentAvailability()); + persisted.setDescription(agentSideResource.getDescription()); + persisted.setName(agentSideResource.getName()); + persisted.setPluginConfiguration(agentSideResource.getPluginConfiguration().clone()); + persisted.setResourceConfiguration(agentSideResource.getResourceConfiguration().clone()); + persisted.setVersion(agentSideResource.getVersion()); + persisted.setInventoryStatus(requiredInventoryStatus); + persisted.setResourceKey(agentSideResource.getResourceKey()); + persisted.setResourceType(agentSideResource.getResourceType()); + + Resource parent = agentSideResource.getParentResource(); + if (parent != null && parent != Resource.ROOT) { + persisted.setParentResource(fakePersist(agentSideResource.getParentResource(), requiredInventoryStatus, inProgressUUIds)); + } else { + persisted.setParentResource(parent); + } + + Set<Resource> childResources = new HashSet<Resource>(); + persisted.setChildResources(childResources); + for(Resource child : agentSideResource.getChildResources()) { + childResources.add(fakePersist(child, requiredInventoryStatus, inProgressUUIds)); + } + + inProgressUUIds.remove(agentSideResource.getUuid()); + + return persisted; + } + + private ResourceSyncInfo getSyncInfo() { + return platform != null ? convert(platform) : null; + } + + private static ResourceSyncInfo convert(Resource root) { + try { + ResourceSyncInfo ret = new ResourceSyncInfo(); + + Class<ResourceSyncInfo> clazz = ResourceSyncInfo.class; + + getPrivateField(clazz, "id").set(ret, root.getId()); + getPrivateField(clazz, "uuid").set(ret, root.getUuid()); + getPrivateField(clazz, "mtime").set(ret, root.getMtime()); + getPrivateField(clazz, "inventoryStatus").set(ret, root.getInventoryStatus()); + getPrivateField(clazz, "parent").set(ret, null); + + Set<ResourceSyncInfo> children = new LinkedHashSet<ResourceSyncInfo>(); + for(Resource child : root.getChildResources()) { + ResourceSyncInfo syncChild = convert(child); + getPrivateField(clazz, "parent").set(syncChild, ret); + + children.add(convert(child)); + } + getPrivateField(clazz, "childSyncInfos").set(ret, children); + + return ret; + } catch (Exception e) { + fail("Failed to convert resource " + root + " to a ResourceSyncInfo. This should not happen.", e); + return null; + } + } + + private static Field getPrivateField(Class<?> clazz, String fieldName) throws NoSuchFieldException { + Field field = clazz.getDeclaredField(fieldName); + if (!field.isAccessible()) { + field.setAccessible(true); + } + + return field; + } + + private static Resource findResource(Resource root, Resource template, Comparator<Resource> comparator) { + if (root == null) return null; + if (comparator.compare(root, template) == 0) { + return root; + } else { + for(Resource child : root.getChildResources()) { + Resource found = findResource(child, template, comparator); + if (found != null) return found; + } + } + + return null; + } + + private static void findResources(Resource root, Resource template, Set<Resource> result, Comparator<Resource> comparator) { + if (root == null) return; + if (comparator.compare(root, template) == 0) { + result.add(root); + } else { + for(Resource child : root.getChildResources()) { + findResources(child, template, result, comparator); + } + } + } +} diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java new file mode 100644 index 0000000..46d069c --- /dev/null +++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java @@ -0,0 +1,345 @@ +/* + * 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, 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.pc.upgrade; + +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Collections; +import java.util.Set; + +import org.apache.commons.io.FileUtils; +import org.jmock.Expectations; +import org.jmock.Mockery; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import org.rhq.core.clientapi.server.bundle.BundleServerService; +import org.rhq.core.clientapi.server.configuration.ConfigurationServerService; +import org.rhq.core.clientapi.server.content.ContentServerService; +import org.rhq.core.clientapi.server.core.CoreServerService; +import org.rhq.core.clientapi.server.discovery.DiscoveryServerService; +import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.clientapi.server.event.EventServerService; +import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService; +import org.rhq.core.clientapi.server.measurement.MeasurementServerService; +import org.rhq.core.clientapi.server.operation.OperationServerService; +import org.rhq.core.domain.resource.InventoryStatus; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.PluginContainerConfiguration; +import org.rhq.core.pc.ServerServices; +import org.rhq.core.pc.inventory.InventoryManager; +import org.rhq.core.pc.inventory.ResourceContainer; +import org.rhq.core.pc.plugin.FileSystemPluginFinder; + +/** + * Test cases for resource upgrade. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeTest { + + private static final String PLUGIN_V1_FILENAME = "resource-upgrade-test-plugin-1.0.0.jar"; + private static final String PLUGIN_V2_FILENAME = "resource-upgrade-test-plugin-2.0.0.jar"; + + private static final String PLUGINS_DIR_NAME = "plugins"; + private static final String DATA_DIR_NAME = "data"; + private static final String TMP_DIR_NAME = "tmp"; + + private File tmpDir; + private File pluginDir; + private File dataDir; + + private BundleServerService currentBundleServerService; + private ConfigurationServerService currentConfigurationServerService; + private ContentServerService currentContentServerService; + private CoreServerService currentCoreServerService; + private DiscoveryServerService currentDiscoveryServerService; + private EventServerService currentEventServerService; + private MeasurementServerService currentMeasurementServerService; + private OperationServerService currentOperationServerService; + private ResourceFactoryServerService currentResourceFactoryServerService; + + private FakeServerInventory currentServerSideInventory; + + @AfterClass + public void undeployPlugins() throws IOException { + FileUtils.deleteDirectory(tmpDir); + } + + @BeforeClass + public void sanityCheck() { + verifyPluginExists(PLUGIN_V1_FILENAME); + verifyPluginExists(PLUGIN_V2_FILENAME); + } + + @BeforeClass + public void init() { + tmpDir = getTmpDirectory(); + pluginDir = new File(tmpDir, PLUGINS_DIR_NAME); + assertTrue(pluginDir.mkdir(), "Could not create plugin deploy directory."); + dataDir = new File(tmpDir, DATA_DIR_NAME); + assertTrue(dataDir.mkdir(), "Could not create plugin container data directory."); + } + + @Test + public void testInitialSyncAndDiscoveryWithoutCommit() throws Exception { + testInitialSyncAndDiscovery(InventoryStatus.NEW); + } + + @Test(dependsOnMethods = "testInitialSyncAndDiscoveryWithoutCommit") + public void testIgnoreUncommittedResources() throws Exception { + TestPayload testNoChange = new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); + assertEquals(discoveredResource.getName(), "resource-name-v1"); + assertEquals(discoveredResource.getDescription(), "resource-description-v1"); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineIgnoredExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); + will(currentServerSideInventory.getResources()); + } + }; + } + }; + + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, testNoChange); + } + + //make the tests run serially, so that they don't overwrite the currentServerSideInventory + //variable concurrently + @Test(dependsOnMethods = "testIgnoreUncommittedResources") + public void testInitialSyncAndDiscoveryWithCommit() throws Exception { + testInitialSyncAndDiscovery(InventoryStatus.COMMITTED); + } + + @Test(dependsOnMethods = "testInitialSyncAndDiscoveryWithCommit") + public void testUpgradeData() throws Exception { + //we are keeping the currentServerSideInventory from the previous test + executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), false, new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v2"); + assertEquals(discoveredResource.getName(), "resource-name-v2"); + assertEquals(discoveredResource.getDescription(), "resource-description-v2"); + + ResourceContainer container = PluginContainer.getInstance().getInventoryManager().getResourceContainer(discoveredResource); + File dataDir = container.getResourceContext().getDataDirectory(); + + File marker = new File(dataDir, "upgrade-succeeded"); + + assertTrue(marker.exists(), "The upgrade success marker file wasn't found. This means the upgrade didn't actually run."); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineIgnoredExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(InventoryStatus.COMMITTED)); + + oneOf(currentDiscoveryServerService).upgradeResources(with(any(Set.class))); + will(currentServerSideInventory.upgradeResources()); + + allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); + will(currentServerSideInventory.getResources()); + } + }; + } + }); + } + + private void testInitialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception { + currentServerSideInventory = new FakeServerInventory(); + executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), true, new TestPayload() { + public void test(Resource discoveredResource) { + assertEquals(discoveredResource.getResourceKey(), "resource-key-v1"); + assertEquals(discoveredResource.getName(), "resource-name-v1"); + assertEquals(discoveredResource.getDescription(), "resource-description-v1"); + } + + @SuppressWarnings("unchecked") + public Expectations getExpectations(Mockery context) throws Exception { + return new Expectations() { + { + defineIgnoredExpectations(this); + + between(1, 4).of(currentDiscoveryServerService).mergeInventoryReport(with(any(InventoryReport.class))); + will(currentServerSideInventory.mergeInventoryReport(requiredInventoryStatus)); + + allowing(currentDiscoveryServerService).getResources(with(any(Set.class)), with(any(boolean.class))); + will(currentServerSideInventory.getResources()); + } + }; + } + }); + + } + + private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception { + PluginContainerConfiguration conf = new PluginContainerConfiguration(); + + conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); + conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME)); + conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME)); + conf.setInsideAgent(true); //pc must think it's inside an agent so that it persists the inventory between restarts + conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory())); + conf.setCreateResourceClassloaders(false); + + currentBundleServerService = context.mock(BundleServerService.class); + currentConfigurationServerService = context.mock(ConfigurationServerService.class); + currentContentServerService = context.mock(ContentServerService.class); + currentCoreServerService = context.mock(CoreServerService.class); + currentDiscoveryServerService = context.mock(DiscoveryServerService.class); + currentEventServerService = context.mock(EventServerService.class); + currentMeasurementServerService = context.mock(MeasurementServerService.class); + currentOperationServerService = context.mock(OperationServerService.class); + currentResourceFactoryServerService = context.mock(ResourceFactoryServerService.class); + + ServerServices serverServices = new ServerServices(); + serverServices.setBundleServerService(currentBundleServerService); + serverServices.setConfigurationServerService(currentConfigurationServerService); + serverServices.setContentServerService(currentContentServerService); + serverServices.setCoreServerService(currentCoreServerService); + serverServices.setDiscoveryServerService(currentDiscoveryServerService); + serverServices.setEventServerService(currentEventServerService); + serverServices.setMeasurementServerService(currentMeasurementServerService); + serverServices.setOperationServerService(currentOperationServerService); + serverServices.setResourceFactoryServerService(currentResourceFactoryServerService); + + conf.setServerServices(serverServices); + + return conf; + } + + /** + * @param pluginResourcePath + */ + private void verifyPluginExists(String pluginResourcePath) { + URL url = getClass().getResource(pluginResourcePath); + + File pluginFile = FileUtils.toFile(url); + + assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar could not be found."); + } + + private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws IOException { + URL pluginUrl = getClass().getResource(pluginResourcePath); + + File pluginFile = new File(pluginResourcePath); + String pluginFileName = pluginFile.getName(); + + FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName)); + } + + private static File getTmpDirectory() { + File ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); + + while (ret.exists() || !ret.mkdir()) { + ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis()); + } + + return ret; + } + + private interface TestPayload { + Expectations getExpectations(Mockery context) throws Exception; + void test(Resource resourceUpgradeTestResource); + } + + private Set<Resource> getTestingResources() { + ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager().getType("Resource", "ResourceUpgradeTest"); + + return currentServerSideInventory.findResourcesByType(resType); + } + + private void executeTestWithPlugins(Set<String> pluginResourcePaths, boolean clearInventoryDat, TestPayload test) throws Exception { + FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME)); + + for(String pluginResourcePath : pluginResourcePaths) { + copyPlugin(pluginResourcePath, pluginDir); + } + + Mockery context = new Mockery(); + + PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context); + + if (clearInventoryDat) { + File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat"); + inventoryDat.delete(); + } + + context.checking(test.getExpectations(context)); + + PluginContainer.getInstance().setConfiguration(pcConfig); + PluginContainer.getInstance().initialize(); + + //give the pc the time to finish resource upgrade + Thread.sleep(1000); + + //execute full discovery + InventoryManager im = PluginContainer.getInstance().getInventoryManager(); + im.executeServerScanImmediately(); + im.executeServiceScanImmediately(); + + Set<Resource> resources = getTestingResources(); + + assertEquals(resources.size(), 1, "There should be only a single testing resource but " + resources + " were found."); + + Resource discoveredResource = resources.iterator().next(); + + test.test(discoveredResource); + + PluginContainer.getInstance().shutdown(); + + context.assertIsSatisfied(); + } + + private void defineIgnoredExpectations(Expectations expectations) { + expectations.ignoring(currentBundleServerService); + expectations.ignoring(currentConfigurationServerService); + expectations.ignoring(currentContentServerService); + expectations.ignoring(currentCoreServerService); + expectations.ignoring(currentEventServerService); + expectations.ignoring(currentMeasurementServerService); + expectations.ignoring(currentOperationServerService); + expectations.ignoring(currentResourceFactoryServerService); + } +} diff --git a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar new file mode 100644 index 0000000..33a79c0 Binary files /dev/null and b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-1.0.0.jar differ diff --git a/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar new file mode 100644 index 0000000..412ae00 Binary files /dev/null and b/modules/core/plugin-container/src/test/resources/org/rhq/core/pc/upgrade/resource-upgrade-test-plugin-2.0.0.jar differ
commit 8dae62e89bc703cf2b8e16272b8d9ebc912606dd Author: Lukas Krejci lkrejci@redhat.com Date: Fri Jun 18 20:22:33 2010 +0200
Correctly handle the upgrade sync up when the agent is connected to the server for the very first time.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 54c6bcc..dbee063 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -900,7 +900,6 @@ public class InventoryManager extends AgentService implements ContainerService, */ public boolean handleReport(InventoryReport report, boolean forceServerRoundtrip) { if (!configuration.isInsideAgent()) { - //TODO how does resource upgrade behave in the embedded scenario? return true; }
@@ -943,7 +942,14 @@ public class InventoryManager extends AgentService implements ContainerService, return false; }
- synchInventory(syncInfo); + //sync info can be null if the server hasn't received a full inventory report + //from us yet. This can happen if this method is being invoked from inside the + //resource upgrade executor to sync up with the server side inventory *JUST AFTER* + //this agent registered with the server for the very first time. In that case + //the server hasn't received any info from us yet. + if (syncInfo != null) { + synchInventory(syncInfo); + }
return true; } diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 76d6265..fd59590 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -156,7 +156,13 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot
// Prepare the ResourceSyncInfo tree which contains all the info the PC needs to sync itself up with us. Resource platform = this.resourceManager.getPlatform(knownAgent); - ResourceSyncInfo syncInfo = this.entityManager.find(ResourceSyncInfo.class, platform.getId()); + + //the platform can be null in only one scenario.. a brand new agent has connected to the server + //and that agent is currently trying to upgrade its resources. For that it asks us to send down + //the current inventory on the server side. But at this point there isn't any since that very + //agent just registered and is starting up for the very first time and therefore hasn't had + //a chance yet to send us its full inventory report. + ResourceSyncInfo syncInfo = platform != null ? this.entityManager.find(ResourceSyncInfo.class, platform.getId()) : null;
if (log.isDebugEnabled()) { log.debug("Inventory merge completed in (" + (System.currentTimeMillis() - start) + ")ms");
commit a9622206993586ce28df9e586206cbf981cc7c3b Author: Lukas Krejci lkrejci@redhat.com Date: Fri May 28 18:09:24 2010 +0200
Filter out not-commited resources from the upgrade process.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index 3397e76..bb20054 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -26,6 +26,7 @@ package org.rhq.core.pc.upgrade; 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.concurrent.ConcurrentHashMap; @@ -37,6 +38,7 @@ import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.agent.PluginContainerException; import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.domain.resource.ResourceUpgradeReport; @@ -203,6 +205,15 @@ public class ResourceUpgradeExecutor implements Runnable { Set<Resource> siblings = parentResource == null ? Collections.singleton(inventoryManager.getPlatform()) : inventoryManager.getResourcesWithType(resourceType, parentResource.getChildResources());
+ //filter out not committed resources + //XXX what about uninventoried or ignored ones? is it correct to not upgrade those? + Iterator<Resource> siblingsIterator = siblings.iterator(); + while (siblingsIterator.hasNext()) { + if (siblingsIterator.next().getInventoryStatus() != InventoryStatus.COMMITTED) { + siblingsIterator.remove(); + } + } + //get the upgrade context of the parent resource so that it can be passed to the upgrade method //of the discovery component. ResourceUpgradeContext<?> parentUpgradeContext = null;
commit df4ffc41f2554332ba870eaeb69e20017ea25240 Author: Lukas Krejci lkrejci@redhat.com Date: Fri May 28 18:08:53 2010 +0200
Improve resource upgrade logging on both agent and server side.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index ba5f316..54c6bcc 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1194,36 +1194,50 @@ public class InventoryManager extends AgentService implements ContainerService, //Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); //Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
- ResourceContainer existingResourceContainer = getResourceContainer(upgradeReport.getResourceId()); - if (existingResourceContainer != null) { - Resource existingResource = existingResourceContainer.getResource(); - if (resourceKey != null) { - existingResource.setResourceKey(resourceKey); - } - - if (name != null) { - existingResource.setName(name); - } - -// if (version != null) { -// existingResource.setVersion(version); -// } - - if (description != null) { - existingResource.setDescription(description); + //only bother if there's something to upgrade at all on this resource. + if (resourceKey != null || name != null || description != null) { + ResourceContainer existingResourceContainer = getResourceContainer(upgradeReport.getResourceId()); + if (existingResourceContainer != null) { + Resource existingResource = existingResourceContainer.getResource(); + + StringBuilder logMessage = new StringBuilder("Resource [") + .append(existingResource.toString()).append("] upgraded its "); + + if (resourceKey != null) { + existingResource.setResourceKey(resourceKey); + logMessage.append("resourceKey, "); + } + + if (name != null) { + existingResource.setName(name); + logMessage.append("name, "); + } + +// if (version != null) { +// existingResource.setVersion(version); +// } + + if (description != null) { + existingResource.setDescription(description); + logMessage.append("description, "); + } + +// if (pluginConfiguration != null) { +// existingResource.setPluginConfiguration(pluginConfiguration); +// } +// +// if (resourceConfiguration != null) { +// existingResource.setResourceConfiguration(resourceConfiguration); +// } + + logMessage.replace(logMessage.length() - 1, logMessage.length(), + "to become [").append(existingResource.toString()).append("]"); + + log.info(logMessage.toString()); + } else { + log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeReport.getResourceId()); } - -// if (pluginConfiguration != null) { -// existingResource.setPluginConfiguration(pluginConfiguration); -// } -// -// if (resourceConfiguration != null) { -// existingResource.setResourceConfiguration(resourceConfiguration); -// } - } else { - log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeReport.getResourceId()); } - } }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 1101199..76d6265 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -465,65 +465,70 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot /** * @param existingResource * @param upgradeReport - * @return + * @return true if the resource was changed, false otherwise */ private boolean upgradeResource(Resource resource, ResourceUpgradeReport upgradeReport) { - boolean changed = false; if (resource != null) { String resourceKey = upgradeReport.getNewResourceKey(); String name = upgradeReport.getNewName(); - //String version = upgradeReport.getNewVersion(); +// String version = upgradeReport.getNewVersion(); String description = upgradeReport.getNewDescription(); // Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); // Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
- if (needsUpgrade(resource.getResourceKey(), resourceKey)) { - log.info("Resource [" + resource + "] upgraded its resource key from [" + - resource.getResourceKey() + "] to [" + resourceKey + "]"); - changed = true; - resource.setResourceKey(resourceKey); - } - - if (needsUpgrade(resource.getName(), name)) { - log.info("Resource [" + resource + "] upgraded its name from [" + - resource.getName() + "] to [" + name + "]"); - changed = true; - resource.setName(name); - } - -// if (version != null) { -// changed = updateResourceVersion(resource, version) || changed; -// } - - if (needsUpgrade(resource.getDescription(), description)) { - log.info("Resource [" + resource + "] upgraded its description from [" + - resource.getDescription() + "] to [" + description + "]"); - changed = true; - resource.setDescription(description); - } - -// if (pluginConfiguration != null) { -// if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { -// log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + -// resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); -// changed = true; -// resource.setPluginConfiguration(pluginConfiguration); + if (resourceKey != null || name != null || description != null) { + StringBuilder logMessage = new StringBuilder("Resource [") + .append(resource.toString()).append("] upgraded its "); + + if (needsUpgrade(resource.getResourceKey(), resourceKey)) { + resource.setResourceKey(resourceKey); + logMessage.append("resourceKey, "); + } + + if (needsUpgrade(resource.getName(), name)) { + resource.setName(name); + logMessage.append("name, "); + } + +// if (version != null) { +// changed = updateResourceVersion(resource, version) || changed; // } -// } -// -// if (resourceConfiguration != null) { -// if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { -// //XXX Will this create a new history entry? -// -// log.info("Resource [" + resource + "] upgraded its resource configuration from [" + -// resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); -// -// changed = true; -// resource.setResourceConfiguration(resourceConfiguration); + + if (needsUpgrade(resource.getDescription(), description)) { + resource.setDescription(description); + logMessage.append("description, "); + } + +// if (pluginConfiguration != null) { +// if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { +// log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + +// resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); +// changed = true; +// resource.setPluginConfiguration(pluginConfiguration); +// } // } -// } +// +// if (resourceConfiguration != null) { +// if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { +// //XXX Will this create a new history entry? +// +// log.info("Resource [" + resource + "] upgraded its resource configuration from [" + +// resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); +// +// changed = true; +// resource.setResourceConfiguration(resourceConfiguration); +// } +// } + + logMessage.replace(logMessage.length() - 1, logMessage.length(), + "to become [").append(resource.toString()).append("]"); + + log.info(logMessage.toString()); + + return true; + } } - return changed; + return false; }
private void validateInventoryReport(InventoryReport report) throws InvalidInventoryReportException { @@ -875,18 +880,6 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot updateInventoryStatus(subject, platforms, servers, target); }
- private static <T> boolean equalOrNull(T a, T b) { - if (a == null) { - return b == null; - } else { - if (b == null) { - return false; - } else { - return a.equals(b); - } - } - } - private static <T> boolean needsUpgrade(T oldValue, T newValue) { return newValue != null && (oldValue == null || !newValue.equals(oldValue)); }
commit d896c3792ebf8b45938972eb2ff2f45bd990be83 Author: Lukas Krejci lkrejci@redhat.com Date: Fri May 28 18:08:16 2010 +0200
Run a method in a new thread only if it originates in the interface that is being proxied.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java index f8d1267..4c68970 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java @@ -81,7 +81,7 @@ public class DiscoveryComponentProxyFactory {
// This is the handler that will actually invoke the method calls. ResourceDiscoveryComponentInvocationHandler handler = new ResourceDiscoveryComponentInvocationHandler(type, - component, timeout, pluginClassLoader); + component, timeout, pluginClassLoader, componentInterface);
// This is the proxy that will look like the discovery component object that the caller will use. T proxy = (T) Proxy.newProxyInstance(pluginClassLoader, new Class<?>[] { componentInterface }, handler); @@ -167,9 +167,10 @@ public class DiscoveryComponentProxyFactory { private final long timeout; private final ResourceType resourceType; private final ClassLoader pluginClassLoader; - + private Class<?> componentInterface; + public ResourceDiscoveryComponentInvocationHandler(ResourceType type, ResourceDiscoveryComponent component, - long timeout, ClassLoader pluginClassLoader) { + long timeout, ClassLoader pluginClassLoader, Class<?> componentInterface) { if (timeout <= 0) { throw new IllegalArgumentException("timeout value is not positive."); } @@ -181,6 +182,7 @@ public class DiscoveryComponentProxyFactory { this.component = component; this.timeout = timeout; this.pluginClassLoader = pluginClassLoader; + this.componentInterface = componentInterface; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { @@ -189,7 +191,7 @@ public class DiscoveryComponentProxyFactory { + "] has been blacklisted and can no longer be invoked."); }
- if (method.getDeclaringClass().getPackage().getName().startsWith("org.rhq")) { + if (componentInterface.isAssignableFrom(method.getDeclaringClass())) { return invokeInNewThread(method, args); } else { // toString(), etc.
commit 708dee442c2519ecc9d27c723e79239b14b25455 Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 19:04:32 2010 +0200
Fixing a stupid bug that would cause no initial sync to happen during upgrade.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 83743d9..ba5f316 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -883,13 +883,22 @@ public class InventoryManager extends AgentService implements ContainerService, }
/** + * @see #handleReport(InventoryReport, boolean) + * @param report + * @return + */ + public boolean handleReport(InventoryReport report) { + return handleReport(report, false); + } + + /** * Send an inventory report to the Server. * * @param report the inventory report to be sent - * + * @param forceServerRoundtrip whether to report to the server even if there are no resources to report. * @return true if sending the report to the Server succeeded, or false otherwise */ - public boolean handleReport(InventoryReport report) { + public boolean handleReport(InventoryReport report, boolean forceServerRoundtrip) { if (!configuration.isInsideAgent()) { //TODO how does resource upgrade behave in the embedded scenario? return true; @@ -905,7 +914,7 @@ public class InventoryManager extends AgentService implements ContainerService, resourceUpgradeExecutor.sendRequests(); }
- if (report.getAddedRoots().isEmpty()) { + if (report.getAddedRoots().isEmpty() && !forceServerRoundtrip) { return true; // nothing to do }
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index f0721cb..3397e76 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -130,7 +130,7 @@ public class ResourceUpgradeExecutor implements Runnable { //pull the inventory down from the server. //this will ensure that we have an up-to-date info on the //server inventory before we try to upgrade. - boolean syncResult = inventoryManager.handleReport(new InventoryReport(inventoryManager.getAgent())); + boolean syncResult = inventoryManager.handleReport(new InventoryReport(inventoryManager.getAgent()), true); if (!syncResult) { log.warn("Resource upgrade failed to sync up the inventory with the server."); return;
commit c9b82d93170e03e564ef2db2c50a007f4d1176dc Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 18:39:32 2010 +0200
Make the ResourceUpgradeExecutor thread safe (even though it probably shouldn't have to be) and make sure it can only be run once.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java index 21da6bc..4d61e93 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java @@ -264,7 +264,7 @@ public class PluginContainer implements ContainerService {
//fire off the resource upgrade as soon as possible. It will run only once per plugin container //lifetime. - inventoryManager.executeResourceUpgradeImmediately(); + inventoryManager.fireResourceUpgrade();
return; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 7fcfd6e..83743d9 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -507,8 +507,13 @@ public class InventoryManager extends AgentService implements ContainerService, } }
- public void executeResourceUpgradeImmediately() { - resourceUpgradeExecutor.execute(); + /** + * Executes the resource upgrade asynchronously. + */ + public void fireResourceUpgrade() { + Thread resourceUpgradeThread = new Thread(resourceUpgradeExecutor, "Resource Upgrade Thread"); + resourceUpgradeThread.setDaemon(true); + resourceUpgradeThread.start(); }
public InventoryReport executeServerScanImmediately() { diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index d15a1c2..f0721cb 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -27,9 +27,10 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import java.util.Queue; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -55,21 +56,22 @@ import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; * * @author Lukas Krejci */ -public class ResourceUpgradeExecutor { +public class ResourceUpgradeExecutor implements Runnable { private static final Log log = LogFactory.getLog(ResourceUpgradeExecutor.class);
/** * The upgrade runs only once in its lifetime. */ - private boolean enabled = true; - + private AtomicBoolean enabled = new AtomicBoolean(true); + private AtomicBoolean started = new AtomicBoolean(false); + private InventoryManager inventoryManager;
- private Set<ResourceUpgradeReport> reports; + private ConcurrentLinkedQueue<ResourceUpgradeReport> reports;
public ResourceUpgradeExecutor(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; - reports = new HashSet<ResourceUpgradeReport>(); + reports = new ConcurrentLinkedQueue<ResourceUpgradeReport>(); }
/** @@ -90,14 +92,14 @@ public class ResourceUpgradeExecutor { public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> processAndQueue( ResourceUpgradeRequest<T> request, Set<Resource> discoveredResources) {
- return enabled ? executeResourceUpgradeAndStoreReport(request, discoveredResources) : null; + return enabled.get() ? executeResourceUpgradeAndStoreReport(request, discoveredResources) : null; }
/** * @return true if the executor is ready to perform the upgrade, false otherwise. */ public boolean isEnabled() { - return enabled; + return enabled.get(); }
/** @@ -105,9 +107,10 @@ public class ResourceUpgradeExecutor { * all the upgrade requests. */ public void sendRequests() { - if (enabled && reports.size() > 0) { - inventoryManager.mergeResourceFromUpgrade(reports); - reports.clear(); + if (enabled.get() && reports.size() > 0) { + HashSet<ResourceUpgradeReport> currentCopy = new HashSet<ResourceUpgradeReport>(reports); + inventoryManager.mergeResourceFromUpgrade(currentCopy); + reports.removeAll(currentCopy); } }
@@ -117,8 +120,8 @@ public class ResourceUpgradeExecutor { * After that a full discovery is performed and both the upgrade report and discovery report * are sent to the server. */ - public void execute() { - if (enabled) { + public void run() { + if (!started.getAndSet(true)) { if (log.isDebugEnabled()) { log.debug("Starting resource upgrade."); } @@ -140,7 +143,7 @@ public class ResourceUpgradeExecutor { log.warn("Resource upgrade failed.", t); } finally { //make sure to switch off the upgrade... - this.enabled = false; + this.enabled.set(false);
//clear up so that we don't hold unnecessary instances. reports.clear();
commit 760871c264eca5adf2cf322a48614b3cd68a3640 Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 18:11:49 2010 +0200
Avoid deadlock by invoking the resource upgrade only after all services are initialized, removing the ability to perform plugin/resource configuration upgrades, generally made stuff work.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java index bfeba0d..979c456 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java @@ -44,9 +44,18 @@ public class ResourceUpgradeReport implements Serializable { private int resourceId; private String newResourceKey; private String newName; - private String newVersion; - private Configuration newPluginConfiguration; - private Configuration newResourceConfiguration; + +// version changes are handled differently. +// private String newVersion; + +// upgrading configurations would have large consequences. +// it would be difficult to synchronize the upgrade process +// with the agent or server initiated configuration updates. +// It could also be difficult for the UI to reflect more complicated +// structural changes as currently, it is assumed that +// the configurations are kept backwards compatible. +// private Configuration newPluginConfiguration; +// private Configuration newResourceConfiguration; private String newDescription;
public ResourceUpgradeReport() { @@ -85,29 +94,29 @@ public class ResourceUpgradeReport implements Serializable { this.newName = newName; }
- public String getNewVersion() { - return newVersion; - } - - public void setNewVersion(String newVersion) { - this.newVersion = newVersion; - } - - public Configuration getNewPluginConfiguration() { - return newPluginConfiguration; - } - - public void setNewPluginConfiguration(Configuration newPluginConfiguration) { - this.newPluginConfiguration = newPluginConfiguration; - } - - public Configuration getNewResourceConfiguration() { - return newResourceConfiguration; - } - - public void setNewResourceConfiguration(Configuration newResourceConfiguration) { - this.newResourceConfiguration = newResourceConfiguration; - } +// public String getNewVersion() { +// return newVersion; +// } +// +// public void setNewVersion(String newVersion) { +// this.newVersion = newVersion; +// } +// +// public Configuration getNewPluginConfiguration() { +// return newPluginConfiguration; +// } +// +// public void setNewPluginConfiguration(Configuration newPluginConfiguration) { +// this.newPluginConfiguration = newPluginConfiguration; +// } +// +// public Configuration getNewResourceConfiguration() { +// return newResourceConfiguration; +// } +// +// public void setNewResourceConfiguration(Configuration newResourceConfiguration) { +// this.newResourceConfiguration = newResourceConfiguration; +// }
public String getNewDescription() { return newDescription; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java index 8970404..21da6bc 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/PluginContainer.java @@ -262,6 +262,10 @@ public class PluginContainer implements ContainerService { releaseLock(lock); }
+ //fire off the resource upgrade as soon as possible. It will run only once per plugin container + //lifetime. + inventoryManager.executeResourceUpgradeImmediately(); + return; }
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 044aa25..7fcfd6e 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -250,16 +250,7 @@ public class InventoryManager extends AgentService implements ContainerService, .getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS); }
- //try to perform the full resource upgrade now. - //The initialization time is ideal for this because inventory manager - //is the first plugin container service to start and hence we can - //be sure that no under concurrent updates to the resources are happening. - //Because PC doesn't support online updates of plugins and needs to be restarted - //in order to pick up the changed plugins, we can be sure that running the - //upgrade only once at the PC start up is enough for the lifetime of - //plugin container (and hence this instance of InventoryManager). resourceUpgradeExecutor = new ResourceUpgradeExecutor(this); - resourceUpgradeExecutor.execute(); } finally { inventoryLock.writeLock().unlock(); } @@ -516,6 +507,10 @@ public class InventoryManager extends AgentService implements ContainerService, } }
+ public void executeResourceUpgradeImmediately() { + resourceUpgradeExecutor.execute(); + } + public InventoryReport executeServerScanImmediately() { try { return inventoryThreadPoolExecutor.submit((Callable<InventoryReport>) this.serverScanExecutor).get(); @@ -1180,10 +1175,10 @@ public class InventoryManager extends AgentService implements ContainerService, for (ResourceUpgradeReport upgradeReport : upgradeReports) { String resourceKey = upgradeReport.getNewResourceKey(); String name = upgradeReport.getNewName(); - String version = upgradeReport.getNewVersion(); + //String version = upgradeReport.getNewVersion(); String description = upgradeReport.getNewDescription(); - Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); - Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); + //Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); + //Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
ResourceContainer existingResourceContainer = getResourceContainer(upgradeReport.getResourceId()); if (existingResourceContainer != null) { @@ -1196,21 +1191,21 @@ public class InventoryManager extends AgentService implements ContainerService, existingResource.setName(name); }
- if (version != null) { - existingResource.setVersion(version); - } +// if (version != null) { +// existingResource.setVersion(version); +// }
if (description != null) { existingResource.setDescription(description); }
- if (pluginConfiguration != null) { - existingResource.setPluginConfiguration(pluginConfiguration); - } - - if (resourceConfiguration != null) { - existingResource.setResourceConfiguration(resourceConfiguration); - } +// if (pluginConfiguration != null) { +// existingResource.setPluginConfiguration(pluginConfiguration); +// } +// +// if (resourceConfiguration != null) { +// existingResource.setResourceConfiguration(resourceConfiguration); +// } } else { log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeReport.getResourceId()); } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index b00dfd4..d15a1c2 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -69,6 +69,7 @@ public class ResourceUpgradeExecutor {
public ResourceUpgradeExecutor(InventoryManager inventoryManager) { this.inventoryManager = inventoryManager; + reports = new HashSet<ResourceUpgradeReport>(); }
/** @@ -104,8 +105,9 @@ public class ResourceUpgradeExecutor { * all the upgrade requests. */ public void sendRequests() { - if (enabled) { + if (enabled && reports.size() > 0) { inventoryManager.mergeResourceFromUpgrade(reports); + reports.clear(); } }
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 44f79a2..1101199 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -472,67 +472,56 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot if (resource != null) { String resourceKey = upgradeReport.getNewResourceKey(); String name = upgradeReport.getNewName(); - String version = upgradeReport.getNewVersion(); + //String version = upgradeReport.getNewVersion(); String description = upgradeReport.getNewDescription(); - Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); - Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); +// Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); +// Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration();
- if (resourceKey != null) { - if (!equalOrNull(resourceKey, resource.getResourceKey())) { - log.info("Resource [" + resource + "] upgraded its resource key from [" + - resource.getResourceKey() + "] to [" + resourceKey + "]"); - changed = true; - resource.setResourceKey(resourceKey); - } - } - - if (name != null) { - if (!equalOrNull(name, resource.getName())) { - log.info("Resource [" + resource + "] upgraded its name from [" + - resource.getName() + "] to [" + name + "]"); - changed = true; - resource.setName(name); - } - } - - if (version != null) { - changed = updateResourceVersion(resource, version) || changed; + if (needsUpgrade(resource.getResourceKey(), resourceKey)) { + log.info("Resource [" + resource + "] upgraded its resource key from [" + + resource.getResourceKey() + "] to [" + resourceKey + "]"); + changed = true; + resource.setResourceKey(resourceKey); }
- if (description != null) { - if (!equalOrNull(description, resource.getDescription())) { - log.info("Resource [" + resource + "] upgraded its description from [" + - resource.getDescription() + "] to [" + description + "]"); - changed = true; - resource.setDescription(description); - } + if (needsUpgrade(resource.getName(), name)) { + log.info("Resource [" + resource + "] upgraded its name from [" + + resource.getName() + "] to [" + name + "]"); + changed = true; + resource.setName(name); }
- if (pluginConfiguration != null) { - if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { - log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + - resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); - changed = true; - resource.setPluginConfiguration(pluginConfiguration); - } - } +// if (version != null) { +// changed = updateResourceVersion(resource, version) || changed; +// }
- if (resourceConfiguration != null) { - if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { - //XXX Will this create a new history entry? - - log.info("Resource [" + resource + "] upgraded its resource configuration from [" + - resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); - - changed = true; - resource.setResourceConfiguration(resourceConfiguration); - } + if (needsUpgrade(resource.getDescription(), description)) { + log.info("Resource [" + resource + "] upgraded its description from [" + + resource.getDescription() + "] to [" + description + "]"); + changed = true; + resource.setDescription(description); }
- // If the resource was marked as deleted, reactivate it again. - if (resource.getInventoryStatus() == InventoryStatus.DELETED) { - resource.setInventoryStatus(InventoryStatus.COMMITTED); - } +// if (pluginConfiguration != null) { +// if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { +// log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + +// resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); +// changed = true; +// resource.setPluginConfiguration(pluginConfiguration); +// } +// } +// +// if (resourceConfiguration != null) { +// if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { +// //XXX Will this create a new history entry? +// +// log.info("Resource [" + resource + "] upgraded its resource configuration from [" + +// resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); +// +// changed = true; +// resource.setResourceConfiguration(resourceConfiguration); +// } +// } } return changed; } @@ -897,4 +886,8 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot } } } + + private static <T> boolean needsUpgrade(T oldValue, T newValue) { + return newValue != null && (oldValue == null || !newValue.equals(oldValue)); + } } \ No newline at end of file
commit 1fe97fb0bb997c5e6c023adca8bb94da0fca7c79 Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 16:18:21 2010 +0200
Actually call out back to inv manager to perform the upgrade.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java index f0f2b43..b00dfd4 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -105,7 +105,7 @@ public class ResourceUpgradeExecutor { */ public void sendRequests() { if (enabled) { - //TODO implement + inventoryManager.mergeResourceFromUpgrade(reports); } }
commit d0d2e582e00344b1720ee9d01a730fa1d1c3cb46 Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 15:58:35 2010 +0200
reimplemented the upgrade process on the agent to happen only at init time. the server receives a full batch of upgrades, not one upgrade after another.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java index cfa2459..61e5084 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java @@ -138,13 +138,12 @@ public interface DiscoveryServerService { boolean updateResourceVersion(int resourceId, String version);
/** - * Upgrades the data of the resource according to the provided report. + * Upgrades the data of the resources according to the provided reports. * - * @param resourceId the id of the resource to be upgraded - * @param upgradeReport contains the information about the upgrade + * @param upgradeReports contains the information about the upgrade of individual resources. * @return true if the upgrade succeeded, false otherwise. */ - boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport); + boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports);
/** * Gives the server a chance to apply any necessary post-processing that's needed for newly committed resources diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java index 52acf09..bfeba0d 100644 --- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java @@ -41,6 +41,7 @@ public class ResourceUpgradeReport implements Serializable {
private static final long serialVersionUID = 1L;
+ private int resourceId; private String newResourceKey; private String newName; private String newVersion; @@ -52,6 +53,22 @@ public class ResourceUpgradeReport implements Serializable {
}
+ /** + * The server-side id of the resource being upgraded. + * The discovery components don't need to assign this value. + */ + public int getResourceId() { + return resourceId; + } + + /** + * The server-side id of the resource being upgraded. + * The discovery components don't need to assign this value. + */ + public void setResourceId(int resourceId) { + this.resourceId = resourceId; + } + public String getNewResourceKey() { return newResourceKey; } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 032256b..044aa25 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -33,9 +33,11 @@ import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -89,6 +91,8 @@ import org.rhq.core.pc.plugin.BlacklistedException; import org.rhq.core.pc.plugin.CanonicalResourceKey; import org.rhq.core.pc.plugin.PluginComponentFactory; import org.rhq.core.pc.plugin.PluginManager; +import org.rhq.core.pc.upgrade.ResourceUpgradeExecutor; +import org.rhq.core.pc.upgrade.ResourceUpgradeRequest; import org.rhq.core.pc.util.DiscoveryComponentProxyFactory; import org.rhq.core.pc.util.FacetLockType; import org.rhq.core.pc.util.LoggingThreadFactory; @@ -186,6 +190,11 @@ public class InventoryManager extends AgentService implements ContainerService, */ private AvailabilityCollectorThreadPool availabilityCollectors;
+ /** + * Handles the resource upgrade during the initialization of the inventory manager. + */ + private ResourceUpgradeExecutor resourceUpgradeExecutor; + public InventoryManager() { super(DiscoveryAgentService.class); } @@ -240,6 +249,17 @@ public class InventoryManager extends AgentService implements ContainerService, inventoryThreadPoolExecutor.scheduleWithFixedDelay(serviceScanExecutor, configuration .getServiceDiscoveryInitialDelay(), configuration.getServiceDiscoveryPeriod(), TimeUnit.SECONDS); } + + //try to perform the full resource upgrade now. + //The initialization time is ideal for this because inventory manager + //is the first plugin container service to start and hence we can + //be sure that no under concurrent updates to the resources are happening. + //Because PC doesn't support online updates of plugins and needs to be restarted + //in order to pick up the changed plugins, we can be sure that running the + //upgrade only once at the PC start up is enough for the lifetime of + //plugin container (and hence this instance of InventoryManager). + resourceUpgradeExecutor = new ResourceUpgradeExecutor(this); + resourceUpgradeExecutor.execute(); } finally { inventoryLock.writeLock().unlock(); } @@ -356,6 +376,23 @@ public class InventoryManager extends AgentService implements ContainerService, return results; }
+ public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> invokeDiscoveryComponentResourceUpgradeFacet( + ResourceType resourceType, ResourceDiscoveryComponent<T> component, + Set<ResourceUpgradeContext<T>> inventoriedSiblings, ResourceUpgradeContext<?> parent, + Set<ResourceUpgradeContext<T>> discoveredResources) throws Throwable { + + long timeout = getDiscoveryComponentTimeout(resourceType); + try { + @SuppressWarnings("unchecked") + ResourceUpgradeFacet<T> proxy = this.discoveryComponentProxyFactory.getDiscoveryComponentProxy(resourceType, component, timeout, ResourceUpgradeFacet.class); + + return proxy.upgrade(inventoriedSiblings, parent, discoveredResources); + } catch (BlacklistedException e) { + log.debug(e); + return Collections.emptyMap(); + } + } + public DiscoveryComponentProxyFactory getDiscoveryComponentProxyFactory() { return this.discoveryComponentProxyFactory; } @@ -854,8 +891,20 @@ public class InventoryManager extends AgentService implements ContainerService, */ public boolean handleReport(InventoryReport report) { if (!configuration.isInsideAgent()) { + //TODO how does resource upgrade behave in the embedded scenario? return true; } + + //finish the resource upgrade. + //by now all the resource upgrade requests have been processed + //by the executor, which means that the inventory report + //we got already only contains the "correct" new resources and + //that the executor has all the upgrade requests queued up + //to be sent to the server in a batch. + if (resourceUpgradeExecutor.isEnabled()) { + resourceUpgradeExecutor.sendRequests(); + } + if (report.getAddedRoots().isEmpty()) { return true; // nothing to do } @@ -925,6 +974,7 @@ public class InventoryManager extends AgentService implements ContainerService, log.debug(String.format("DONE syncing local inventory [%d] ms.", (System.currentTimeMillis() - startTime))); } + // If we synced any Resources, one or more Resource components were probably started, // so run an avail check to report on their availabilities immediately. Also kick off // a service scan to scan those Resources for new child Resources. Kick both tasks off @@ -941,7 +991,7 @@ public class InventoryManager extends AgentService implements ContainerService, throw new RuntimeException(t); } } - + private void getAllUuids(ResourceSyncInfo syncInfo, Set<String> allServerSideUuids) { allServerSideUuids.add(syncInfo.getUuid()); for (ResourceSyncInfo child : syncInfo.getChildSyncInfos()) { @@ -1113,49 +1163,58 @@ public class InventoryManager extends AgentService implements ContainerService, return resourceContainer.updateAvailability(availabilityType); }
- private boolean mergeResourceFromUpgrade(Resource existingResource, ResourceUpgradeReport upgradeReport) { - String resourceKey = upgradeReport.getNewResourceKey(); - String name = upgradeReport.getNewName(); - String version = upgradeReport.getNewVersion(); - String description = upgradeReport.getNewDescription(); - Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); - Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); - + public boolean mergeResourceFromUpgrade(Set<ResourceUpgradeReport> upgradeReports) { boolean serverUpdated = false; try { ServerServices serverServices = this.configuration.getServerServices(); if (serverServices != null) { DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService();
- serverUpdated = discoveryServerService.upgradeResource(existingResource.getId(), upgradeReport); + serverUpdated = discoveryServerService.upgradeResources(upgradeReports); } } catch (Exception e) { - log.error("Failed to upgrade the resource [" + existingResource + "] on the server.", e); + log.error("Failed to process resource upgrades on the server.", e); }
if (serverUpdated) { - if (resourceKey != null) { - existingResource.setResourceKey(resourceKey); - } - - if (name != null) { - existingResource.setName(name); - } - - if (version != null) { - existingResource.setVersion(version); - } - - if (description != null) { - existingResource.setDescription(description); - } - - if (pluginConfiguration != null) { - existingResource.setPluginConfiguration(pluginConfiguration); - } - - if (resourceConfiguration != null) { - existingResource.setResourceConfiguration(resourceConfiguration); + for (ResourceUpgradeReport upgradeReport : upgradeReports) { + String resourceKey = upgradeReport.getNewResourceKey(); + String name = upgradeReport.getNewName(); + String version = upgradeReport.getNewVersion(); + String description = upgradeReport.getNewDescription(); + Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); + Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); + + ResourceContainer existingResourceContainer = getResourceContainer(upgradeReport.getResourceId()); + if (existingResourceContainer != null) { + Resource existingResource = existingResourceContainer.getResource(); + if (resourceKey != null) { + existingResource.setResourceKey(resourceKey); + } + + if (name != null) { + existingResource.setName(name); + } + + if (version != null) { + existingResource.setVersion(version); + } + + if (description != null) { + existingResource.setDescription(description); + } + + if (pluginConfiguration != null) { + existingResource.setPluginConfiguration(pluginConfiguration); + } + + if (resourceConfiguration != null) { + existingResource.setResourceConfiguration(resourceConfiguration); + } + } else { + log.error("Upgraded a resource that is not present on the agent. This should not happen. The id of the missing resource is " + upgradeReport.getResourceId()); + } + } }
@@ -1453,6 +1512,23 @@ public class InventoryManager extends AgentService implements ContainerService, this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do }
+ public <T extends ResourceComponent> ResourceUpgradeContext<T> createResourceUpgradeContext(Resource resource, T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { + File pluginDataDir = new File(this.configuration.getDataDirectory(), resource.getResourceType().getPlugin()); + + return new ResourceUpgradeContext<T>(resource, // the resource itself + parentComponent, // its parent component + discoveryComponent, // the discovery component (this is actually the proxy to it) + SystemInfoFactory.createSystemInfo(), // for native access + this.configuration.getTemporaryDirectory(), // location for plugin to write temp files + pluginDataDir, // location for plugin to write data files + this.configuration.getContainerName(), // the name of the agent/PC + getEventContext(resource), // for event access + getOperationContext(resource), // for operation manager access + getContentContext(resource), // for content manager access + this.availabilityCollectors, // for components that want to perform async avail checking + this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do + } + /** * This will send a resource error to the server (if applicable) to indicate that the given resource could not be * connected to due to an invalid plugin configuration. @@ -1536,7 +1612,7 @@ public class InventoryManager extends AgentService implements ContainerService, return getResourcesWithType(serverType, this.platform.getChildResources()); }
- private Set<Resource> getResourcesWithType(ResourceType serverType, Set<Resource> resources) { + public Set<Resource> getResourcesWithType(ResourceType serverType, Set<Resource> resources) { Set<Resource> servers = new HashSet<Resource>();
if (resources == null) { @@ -2061,76 +2137,10 @@ public class InventoryManager extends AgentService implements ContainerService, newResources.add(newResource); } } - - //check if the discovery component supports resource upgrade - //if it does, perform the resource upgrade straight away here during the discovery process. - if (discoveryComponent instanceof ResourceUpgradeFacet) { - ResourceUpgradeFacet resourceUpgrade = (ResourceUpgradeFacet) discoveryComponent; - - //the siblings are the resources of the type that is currently being discovered that are already - //present in the inventory. These are the candidate resources for the upgrade. - Set<Resource> siblings = getResourcesWithType(resourceType, parentResource.getChildResources()); - - ResourceUpgradeContext<?> parentUpgradeContext = null; - - //get the upgrade context of the parent resource so that it can be passed to the upgrade method - //of the discovery component. - if (parentResource != null) { - Resource grandParent = parentResource.getParentResource(); - ResourceContainer grandParentContainer = grandParent == null ? null : getResourceContainer(grandParent); - ResourceDiscoveryComponent parentDiscoveryComponent = PluginContainer.getInstance().getPluginComponentFactory() - .getDiscoveryComponent(parentResource.getResourceType(), grandParentContainer); - - parentUpgradeContext = new ResourceUpgradeContext(parentResource, parentDiscoveryComponent, parentResourceContext, availabilityCollectors); - } - - //convert the sibling resources into upgrade context objects so that the plugin methods don't access the - //domain objects directly. - Set<ResourceUpgradeContext> siblingContexts = new HashSet<ResourceUpgradeContext>(siblings.size()); - - //but we are going to need to update the resources in the end, so map the contexts with the resources. - Map<ResourceUpgradeContext, Resource> siblingContextToResource = new HashMap<ResourceUpgradeContext, Resource>(); - - for (Resource sibling : siblings) { - ResourceUpgradeContext siblingContext = new ResourceUpgradeContext(sibling, discoveryComponent, getResourceContainer(sibling).getResourceContext(), availabilityCollectors); - siblingContexts.add(siblingContext); - siblingContextToResource.put(siblingContext, sibling); - } - - //covert the new resources into contexts. - //map the resources by resource key so that we can later check for uniqueness of the reported results. - Set<ResourceUpgradeContext> newResourceContexts = new HashSet<ResourceUpgradeContext>(); - Map<String, Resource> newResourceKeyToResource = new HashMap<String, Resource>(); - - for (Resource newResource : newResources) { - ResourceUpgradeContext newUpgradeContext = new ResourceUpgradeContext(newResource, discoveryComponent, createResourceContext(newResource, parentComponent, discoveryComponent), availabilityCollectors); - newResourceContexts.add(newUpgradeContext); - newResourceKeyToResource.put(newResource.getResourceKey(), newResource); - } - - //ask the discovery component to upgrade the siblings. - Map<ResourceUpgradeContext, ResourceUpgradeReport> results = resourceUpgrade.upgrade(siblingContexts, parentUpgradeContext, newResourceContexts); - - //now go through the results and upgrade the resources as needed. - for(Map.Entry<ResourceUpgradeContext, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { - Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); - ResourceUpgradeReport newData = upgradeEntry.getValue(); - - //upgrade the data on the server first - mergeResourceFromUpgrade(siblingToUpgrade, newData); - - //if there was a resource key upgrade, remove a resource with the same resource key - //from the discovery results. Otherwise we'd end up with 2 sibling resources with - //the same resource key, which is illegal. - if (newData.getNewResourceKey() != null) { - Resource newResourceToRemove = newResourceKeyToResource.get(newData.getNewResourceKey()); - if (newResourceToRemove != null) { - newResources.remove(newResourceToRemove); - } - } - } - }
+ if (resourceUpgradeExecutor.isEnabled()) { + resourceUpgradeExecutor.processAndQueue(new ResourceUpgradeRequest(newResources, context, parentResource.getId()), newResources); + } } catch (Throwable e) { // TODO GH: Add server/parent - up/down semantics so this won't happen just because a server is not up long elapsedTime = System.currentTimeMillis() - startTime; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java new file mode 100644 index 0000000..f0f2b43 --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeExecutor.java @@ -0,0 +1,285 @@ +/* + * 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, 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.pc.upgrade; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.rhq.core.clientapi.agent.PluginContainerException; +import org.rhq.core.clientapi.server.discovery.InventoryReport; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pc.PluginContainer; +import org.rhq.core.pc.inventory.InventoryManager; +import org.rhq.core.pc.inventory.ResourceContainer; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; + +/** + * This class is responsible for performing the resource upgrade on behalf on of {@link InventoryManager}. + * Despite its name, it is not an {@link java.util.concurrent.Executor} implementation. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeExecutor { + private static final Log log = LogFactory.getLog(ResourceUpgradeExecutor.class); + + /** + * The upgrade runs only once in its lifetime. + */ + private boolean enabled = true; + + private InventoryManager inventoryManager; + + private Set<ResourceUpgradeReport> reports; + + public ResourceUpgradeExecutor(InventoryManager inventoryManager) { + this.inventoryManager = inventoryManager; + } + + /** + * This method is called from within the {@link InventoryManager} during the + * discovery process as individual upgrade requests are generated. + * <p> + * This method calls the appropriate discovery component to perform the upgrade and + * at the same time stores off the results so that they can be sent to the server + * at the end of the discovery in one big batch. + * <p> + * The provided set of discovery results is updated if this method detects that an existing + * resource upgrade would result in a resource key collision with some of the newly discovered + * resources. + * + * @param request the upgrade request + * @param discoveredResources the set of discovered resources that this method can optionally remove some elements from. + */ + public <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> processAndQueue( + ResourceUpgradeRequest<T> request, Set<Resource> discoveredResources) { + + return enabled ? executeResourceUpgradeAndStoreReport(request, discoveredResources) : null; + } + + /** + * @return true if the executor is ready to perform the upgrade, false otherwise. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * This method is called from within the {@link InventoryManager} once it's collected + * all the upgrade requests. + */ + public void sendRequests() { + if (enabled) { + //TODO implement + } + } + + /** + * Performs the resource upgrade. First, a full inventory report is pulled down from the + * server to ensure we have an up-to-date picture of the inventory. + * After that a full discovery is performed and both the upgrade report and discovery report + * are sent to the server. + */ + public void execute() { + if (enabled) { + if (log.isDebugEnabled()) { + log.debug("Starting resource upgrade."); + } + + try { + //pull the inventory down from the server. + //this will ensure that we have an up-to-date info on the + //server inventory before we try to upgrade. + boolean syncResult = inventoryManager.handleReport(new InventoryReport(inventoryManager.getAgent())); + if (!syncResult) { + log.warn("Resource upgrade failed to sync up the inventory with the server."); + return; + } + + //fire off the full discovery + inventoryManager.executeServerScanImmediately(); + inventoryManager.executeServiceScanImmediately(); + } catch (Throwable t) { + log.warn("Resource upgrade failed.", t); + } finally { + //make sure to switch off the upgrade... + this.enabled = false; + + //clear up so that we don't hold unnecessary instances. + reports.clear(); + + if (log.isDebugEnabled()) { + log.debug("Resource upgrade finished."); + } + } + + } else { + if (log.isDebugEnabled()) { + log.debug("ResourceUpgradeExecutor already ran before. Skipping the execution."); + } + } + } + + /** + * Executes the resource upgrade request on the agent (if the appropriate discovery component support {@link ResourceUpgradeFacet}). + * + * @param request the upgrade request to execute on the agent. + * @param discoveredResources the set of the discovered resources that this method can remove some elements from + * @return the resulting upgrade map as reported by the plugin from {@link ResourceUpgradeFacet#upgrade(Set, ResourceUpgradeContext, Set)} method. + * + * @throws PluginContainerException + */ + private <T extends ResourceComponent> Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> executeResourceUpgradeAndStoreReport( + ResourceUpgradeRequest<T> request, Set<Resource> discoveredResources) { + + ResourceDiscoveryContext<T> discoveryContext = request.getDiscoveryContext(); + Set<Resource> newResources = request.getDiscoveredResources(); + Integer parentResourceId = request.getParentResourceId(); + + try { + ResourceType resourceType = discoveryContext.getResourceType(); + ResourceContainer parentResourceContainer = null; + Resource parentResource = null; + if (parentResourceId != null) { + parentResourceContainer = inventoryManager.getResourceContainer(parentResourceId); + if (parentResourceContainer != null) { + parentResource = parentResourceContainer.getResource(); + } + } + + @SuppressWarnings("unchecked") + ResourceDiscoveryComponent<T> discoveryComponent = PluginContainer.getInstance() + .getPluginComponentFactory().getDiscoveryComponent(resourceType, parentResourceContainer); + + ResourceContext<?> parentResourceContext = discoveryContext.getParentResourceContext(); + + T parentComponent = discoveryContext.getParentResourceComponent(); + + //check if the discovery component supports resource upgrade + //if it does, perform the resource upgrade straight away here during the discovery process. + if (discoveryComponent instanceof ResourceUpgradeFacet) { + //the siblings are the resources of the type that is currently being discovered that are already + //present in the inventory. These are the candidate resources for the upgrade. + Set<Resource> siblings = parentResource == null ? Collections.singleton(inventoryManager.getPlatform()) + : inventoryManager.getResourcesWithType(resourceType, parentResource.getChildResources()); + + //get the upgrade context of the parent resource so that it can be passed to the upgrade method + //of the discovery component. + ResourceUpgradeContext<?> parentUpgradeContext = null; + + if (parentResource != null) { + Resource grandParent = parentResource.getParentResource(); + ResourceContainer grandParentContainer = grandParent == null ? null : inventoryManager + .getResourceContainer(grandParent); + + @SuppressWarnings("unchecked") + ResourceDiscoveryComponent<ResourceComponent> parentDiscoveryComponent = PluginContainer + .getInstance().getPluginComponentFactory().getDiscoveryComponent( + parentResource.getResourceType(), grandParentContainer); + + ResourceComponent<?> grandParentResourceComponent = grandParentContainer == null ? null + : grandParentContainer.getResourceComponent(); + + parentUpgradeContext = inventoryManager.createResourceUpgradeContext(parentResource, + grandParentResourceComponent, parentDiscoveryComponent); + } + + //convert the sibling resources into upgrade context objects so that the plugin methods don't access the + //domain objects directly. + Set<ResourceUpgradeContext<T>> siblingContexts = new HashSet<ResourceUpgradeContext<T>>(siblings.size()); + + //but we are going to need to update the resources in the end, so map the contexts with the resources. + Map<ResourceUpgradeContext<T>, Resource> siblingContextToResource = new HashMap<ResourceUpgradeContext<T>, Resource>(); + + for (Resource sibling : siblings) { + ResourceUpgradeContext<T> siblingContext = inventoryManager.createResourceUpgradeContext(sibling, + parentComponent, discoveryComponent); + siblingContexts.add(siblingContext); + siblingContextToResource.put(siblingContext, sibling); + } + + //convert the new resources into contexts. + //map the resources by resource key so that we can later check for uniqueness of the reported results. + Set<ResourceUpgradeContext<T>> newResourceContexts = new HashSet<ResourceUpgradeContext<T>>(); + Map<String, Resource> newResourceKeyToResource = new HashMap<String, Resource>(); + + for (Resource newResource : newResources) { + ResourceUpgradeContext<T> newUpgradeContext = inventoryManager.createResourceUpgradeContext( + newResource, parentComponent, discoveryComponent); + newResourceContexts.add(newUpgradeContext); + newResourceKeyToResource.put(newResource.getResourceKey(), newResource); + } + + //ask the discovery component to upgrade the siblings. + Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> results; + try { + results = inventoryManager.invokeDiscoveryComponentResourceUpgradeFacet(resourceType, + discoveryComponent, siblingContexts, parentUpgradeContext, newResourceContexts); + + //now go through the results and upgrade the resources as needed. + for (Map.Entry<ResourceUpgradeContext<T>, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { + Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); + ResourceUpgradeReport newData = upgradeEntry.getValue(); + + //upgrade the data on the server first + newData.setResourceId(siblingToUpgrade.getId()); + reports.add(newData); + + //if there was a resource key upgrade, remove a resource with the same resource key + //from the discovery results. Otherwise we'd end up with 2 sibling resources with + //the same resource key, which is illegal. + if (newData.getNewResourceKey() != null) { + Resource newResourceToRemove = newResourceKeyToResource.get(newData.getNewResourceKey()); + if (newResourceToRemove != null) { + discoveredResources.remove(newResourceToRemove); + } + } + } + + return results; + } catch (Throwable t) { + log.warn("Exception in discovery component " + discoveryComponent.getClass() + " upgrade method.", + t); + } + } + } catch (PluginContainerException e) { + log.warn("Failed resource upgrade of children of resource id " + parentResourceId, e); + } + return null; + } +} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java new file mode 100644 index 0000000..25178ee --- /dev/null +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/upgrade/ResourceUpgradeRequest.java @@ -0,0 +1,35 @@ +package org.rhq.core.pc.upgrade; + +import java.util.Set; + +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; + +/** + * This class is used to store the requests for resource upgrade that originate in + * the discovery workflow, but can only be executed after an inventory sync. + */ +public class ResourceUpgradeRequest<T extends ResourceComponent> { + private Set<Resource> discoveredResources; + private ResourceDiscoveryContext<T> discoveryContext; + private Integer parentResourceId; + + public ResourceUpgradeRequest(Set<Resource> discoveredResources, ResourceDiscoveryContext<T> discoveryContext, Integer parentResourceId) { + this.discoveredResources = discoveredResources; + this.discoveryContext = discoveryContext; + this.parentResourceId = parentResourceId; + } + + public Set<Resource> getDiscoveredResources() { + return discoveredResources; + } + + public ResourceDiscoveryContext<T> getDiscoveryContext() { + return discoveryContext; + } + + public Integer getParentResourceId() { + return parentResourceId; + } +} \ No newline at end of file diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java index 57b9874..f8d1267 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/util/DiscoveryComponentProxyFactory.java @@ -189,7 +189,7 @@ public class DiscoveryComponentProxyFactory { + "] has been blacklisted and can no longer be invoked."); }
- if (method.getDeclaringClass().equals(ResourceDiscoveryComponent.class)) { + if (method.getDeclaringClass().getPackage().getName().startsWith("org.rhq")) { return invokeInNewThread(method, args); } else { // toString(), etc. diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index 2d3e9e6..44f79a2 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -401,17 +401,20 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot } }
- public boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport) { - Resource existingResource = this.entityManager.find(Resource.class, resourceId); - if (existingResource != null) { - boolean changed = upgradeResource(existingResource, upgradeReport); - if (changed) { - this.entityManager.merge(existingResource); + public boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports) { + for (ResourceUpgradeReport report : upgradeReports) { + Resource existingResource = this.entityManager.find(Resource.class, report.getResourceId()); + if (existingResource != null) { + boolean changed = upgradeResource(existingResource, report); + if (changed) { + this.entityManager.merge(existingResource); + } + } else { + this.entityManager.getTransaction().setRollbackOnly(); + return false; } - return true; - } else { - return false; } + return true; }
/** diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java index 4e60ffb..af518eb 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java @@ -21,6 +21,7 @@ package org.rhq.enterprise.server.discovery; import java.util.EnumSet; import java.util.List; import java.util.Map; +import java.util.Set;
import javax.ejb.Local;
@@ -179,11 +180,10 @@ public interface DiscoveryBossLocal extends DiscoveryBossRemote { boolean updateResourceVersion(int resourceId, String version);
/** - * Upgrades the data of the resource according to the provided report. + * Upgrades the data of the resources according to the provided reports. * - * @param resourceId the id of the resource to be upgraded - * @param upgradeReport contains the information about the upgrade + * @param upgradeReports contains the information about the upgrade of individual resources. * @return true if the upgrade succeeded, false otherwise. */ - boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport); + boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports); } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java index 720465e..0f90cdc 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java @@ -177,9 +177,9 @@ public class DiscoveryServerServiceImpl implements DiscoveryServerService { return discoveryBoss.updateResourceVersion(resourceId, version); }
- public boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport) { + public boolean upgradeResources(Set<ResourceUpgradeReport> upgradeReports) { DiscoveryBossLocal discoveryBoss = LookupUtil.getDiscoveryBoss(); - return discoveryBoss.upgradeResource(resourceId, upgradeReport); + return discoveryBoss.upgradeResources(upgradeReports); }
private static Resource convertToPojoResource(Resource resource, boolean includeDescendants) { diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index fc001f9..2f3431b 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -170,10 +170,10 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return discoveredResources; }
- public Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSiblings, - ResourceUpgradeContext<PlatformComponent> parentContext, Set<ResourceUpgradeContext> discoveryResults) { + public Map<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext<PlatformComponent>> inventoriedSiblings, + ResourceUpgradeContext<?> parentContext, Set<ResourceUpgradeContext<PlatformComponent>> discoveryResults) {
- Map<ResourceUpgradeContext, ResourceUpgradeReport> ret = new HashMap<ResourceUpgradeContext, ResourceUpgradeReport>(); + Map<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport> ret = new HashMap<ResourceUpgradeContext<PlatformComponent>, ResourceUpgradeReport>();
for (ResourceUpgradeContext context : inventoriedSiblings) { String inventoriedResourceKey = context.getResourceKey();
commit 15ee2d7c543480cb636eb0b2c68a773d0728fe78 Author: Lukas Krejci lkrejci@redhat.com Date: Thu May 27 12:11:54 2010 +0200
Small interface correction.
diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java index cea777a..914641c 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java @@ -37,7 +37,6 @@ import org.rhq.core.pluginapi.inventory.ResourceComponent; * * @author Lukas Krejci */ -@SuppressWarnings("unchecked") public interface ResourceUpgradeFacet<T extends ResourceComponent> {
/** @@ -54,5 +53,5 @@ public interface ResourceUpgradeFacet<T extends ResourceComponent> { * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the * corresponding siblings should be upgraded to. */ - Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSiblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); + Map<ResourceUpgradeContext<T>, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext<T>> inventoriedSiblings, ResourceUpgradeContext<? extends ResourceComponent> parentContext, Set<ResourceUpgradeContext<T>> discoveryResults); }
commit df9228b55e6fdd293be1b1b030a00fb109fd649c Author: Lukas Krejci lkrejci@redhat.com Date: Wed May 26 15:06:37 2010 +0200
added some comments, fixed typos and one possible NPE.
diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java index b68b5df..cea777a 100644 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java @@ -45,7 +45,7 @@ public interface ResourceUpgradeFacet<T extends ResourceComponent> { * The exact same discovery results are passed to this method along with the set of resources * that already exist in the inventory. * - * @param inventoriedSimblings the existing resources + * @param inventoriedSiblings the existing resources * @param parentContext the parent of both the newly discovered and existing resources * @param discoveryResults the discovered resources. The resources from this set that have * the same resource key as one of the inventoried siblings (after upgrade using the results of this method) won't @@ -54,5 +54,5 @@ public interface ResourceUpgradeFacet<T extends ResourceComponent> { * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the * corresponding siblings should be upgraded to. */ - Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); + Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSiblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); } diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 866fd79..032256b 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -2062,21 +2062,33 @@ public class InventoryManager extends AgentService implements ContainerService, } }
- //check for upgrade support + //check if the discovery component supports resource upgrade + //if it does, perform the resource upgrade straight away here during the discovery process. if (discoveryComponent instanceof ResourceUpgradeFacet) { ResourceUpgradeFacet resourceUpgrade = (ResourceUpgradeFacet) discoveryComponent;
+ //the siblings are the resources of the type that is currently being discovered that are already + //present in the inventory. These are the candidate resources for the upgrade. Set<Resource> siblings = getResourcesWithType(resourceType, parentResource.getChildResources());
- Resource grandParent = parentResource.getParentResource(); - ResourceContainer grandParentContainer = grandParent == null ? null : getResourceContainer(grandParent); - ResourceDiscoveryComponent parentDiscoveryComponent = PluginContainer.getInstance().getPluginComponentFactory() - .getDiscoveryComponent(parentResource.getResourceType(), grandParentContainer); - - ResourceUpgradeContext<?> parentUpgradeContext = new ResourceUpgradeContext(parentResource, parentDiscoveryComponent, parentResourceContext, availabilityCollectors); + ResourceUpgradeContext<?> parentUpgradeContext = null; + + //get the upgrade context of the parent resource so that it can be passed to the upgrade method + //of the discovery component. + if (parentResource != null) { + Resource grandParent = parentResource.getParentResource(); + ResourceContainer grandParentContainer = grandParent == null ? null : getResourceContainer(grandParent); + ResourceDiscoveryComponent parentDiscoveryComponent = PluginContainer.getInstance().getPluginComponentFactory() + .getDiscoveryComponent(parentResource.getResourceType(), grandParentContainer); + + parentUpgradeContext = new ResourceUpgradeContext(parentResource, parentDiscoveryComponent, parentResourceContext, availabilityCollectors); + }
+ //convert the sibling resources into upgrade context objects so that the plugin methods don't access the + //domain objects directly. Set<ResourceUpgradeContext> siblingContexts = new HashSet<ResourceUpgradeContext>(siblings.size());
+ //but we are going to need to update the resources in the end, so map the contexts with the resources. Map<ResourceUpgradeContext, Resource> siblingContextToResource = new HashMap<ResourceUpgradeContext, Resource>();
for (Resource sibling : siblings) { @@ -2085,6 +2097,8 @@ public class InventoryManager extends AgentService implements ContainerService, siblingContextToResource.put(siblingContext, sibling); }
+ //covert the new resources into contexts. + //map the resources by resource key so that we can later check for uniqueness of the reported results. Set<ResourceUpgradeContext> newResourceContexts = new HashSet<ResourceUpgradeContext>(); Map<String, Resource> newResourceKeyToResource = new HashMap<String, Resource>();
@@ -2094,12 +2108,15 @@ public class InventoryManager extends AgentService implements ContainerService, newResourceKeyToResource.put(newResource.getResourceKey(), newResource); }
+ //ask the discovery component to upgrade the siblings. Map<ResourceUpgradeContext, ResourceUpgradeReport> results = resourceUpgrade.upgrade(siblingContexts, parentUpgradeContext, newResourceContexts);
+ //now go through the results and upgrade the resources as needed. for(Map.Entry<ResourceUpgradeContext, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); ResourceUpgradeReport newData = upgradeEntry.getValue();
+ //upgrade the data on the server first mergeResourceFromUpgrade(siblingToUpgrade, newData);
//if there was a resource key upgrade, remove a resource with the same resource key diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index 45887f6..fc001f9 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -170,12 +170,12 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return discoveredResources; }
- public Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, + public Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSiblings, ResourceUpgradeContext<PlatformComponent> parentContext, Set<ResourceUpgradeContext> discoveryResults) {
Map<ResourceUpgradeContext, ResourceUpgradeReport> ret = new HashMap<ResourceUpgradeContext, ResourceUpgradeReport>();
- for (ResourceUpgradeContext context : inventoriedSimblings) { + for (ResourceUpgradeContext context : inventoriedSiblings) { String inventoriedResourceKey = context.getResourceKey(); File inventoriedResourceKeyAsPath = new File(inventoriedResourceKey);
commit 3c7d8241ea85fdceb317049664886b204f4d9cba Author: Lukas Krejci lkrejci@redhat.com Date: Wed May 26 14:49:03 2010 +0200
renamed the org.rhq.core.pluginapi.migration package to org.rhq.core.pluginapi.upgrade to make it use the "upgrade" notion used by the classes in it.
diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java deleted file mode 100644 index e8c5f03..0000000 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java +++ /dev/null @@ -1,89 +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, 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.pluginapi.migration; - -import java.io.File; -import java.util.concurrent.Executor; - -import org.rhq.core.domain.configuration.Configuration; -import org.rhq.core.domain.resource.Resource; -import org.rhq.core.pluginapi.content.ContentContext; -import org.rhq.core.pluginapi.event.EventContext; -import org.rhq.core.pluginapi.inventory.PluginContainerDeployment; -import org.rhq.core.pluginapi.inventory.ResourceComponent; -import org.rhq.core.pluginapi.inventory.ResourceContext; -import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; -import org.rhq.core.pluginapi.operation.OperationContext; -import org.rhq.core.system.SystemInfo; - -/** - * Represents a resource during the resource upgrade phase of discovery. - * - * @see ResourceUpgradeFacet - * - * @author Lukas Krejci - */ -@SuppressWarnings("unchecked") -public class ResourceUpgradeContext<T extends ResourceComponent> extends ResourceContext<T> { - - private final Configuration resourceConfiguration; - private final String name; - private final String description; - - /** - * @see ResourceContext#ResourceContext(Resource, ResourceComponent, ResourceDiscoveryComponent, SystemInfo, File, File, String, EventContext, OperationContext, ContentContext, Executor, PluginContainerDeployment) - */ - public ResourceUpgradeContext(Resource resource, T parentResourceComponent, - ResourceDiscoveryComponent resourceDiscoveryComponent, SystemInfo systemInfo, File temporaryDirectory, - File dataDirectory, String pluginContainerName, EventContext eventContext, OperationContext operationContext, - ContentContext contentContext, Executor availCollectorThreadPool, - PluginContainerDeployment pluginContainerDeployment) { - - super(resource, parentResourceComponent, resourceDiscoveryComponent, systemInfo, temporaryDirectory, dataDirectory, - pluginContainerName, eventContext, operationContext, contentContext, availCollectorThreadPool, - pluginContainerDeployment); - - this.resourceConfiguration = resource.getResourceConfiguration(); - this.name = resource.getName(); - this.description = resource.getDescription(); - } - - public ResourceUpgradeContext(Resource resource, ResourceDiscoveryComponent discoveryComponent, ResourceContext<T> context, Executor availCollectorThreadPool) { - this(resource, context.getParentResourceComponent(), discoveryComponent, context.getSystemInformation(), context.getTemporaryDirectory(), - context.getDataDirectory(), context.getPluginContainerName(), context.getEventContext(), context.getOperationContext(), - context.getContentContext(), availCollectorThreadPool, context.getPluginContainerDeployment()); - } - - public Configuration getResourceConfiguration() { - return resourceConfiguration; - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } -} diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.java deleted file mode 100644 index df372bf..0000000 --- a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.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, 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.pluginapi.migration; - -import java.util.Map; -import java.util.Set; - -import org.rhq.core.domain.resource.ResourceUpgradeReport; -import org.rhq.core.pluginapi.inventory.ResourceComponent; - -/** - * This interface is to be implemented by discovery classes if they want to support - * upgrading the existing resources to a new format needed by an updated resource component. - * This is useful for example in the case when a new version of plugin redefined a resource - * key generation algorithm and wants to upgrade the legacy resources to use the new format. - * - * @author Lukas Krejci - */ -@SuppressWarnings("unchecked") -public interface ResourceUpgradeFacet<T extends ResourceComponent> { - - /** - * This method is called on the discovery component straight after it has finished the discovery. - * The exact same discovery results are passed to this method along with the set of resources - * that already exist in the inventory. - * - * @param inventoriedSimblings the existing resources - * @param parentContext the parent of both the newly discovered and existing resources - * @param discoveryResults the discovered resources. The resources from this set that have - * the same resource key as one of the inventoried siblings (after upgrade using the results of this method) won't - * be reported. - * @return the mapping of old resources to the newly desired data. The keys are instances from the - * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the - * corresponding siblings should be upgraded to. - */ - Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); -} diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeContext.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeContext.java new file mode 100644 index 0000000..35f5029 --- /dev/null +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeContext.java @@ -0,0 +1,89 @@ +/* + * 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, 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.pluginapi.upgrade; + +import java.io.File; +import java.util.concurrent.Executor; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pluginapi.content.ContentContext; +import org.rhq.core.pluginapi.event.EventContext; +import org.rhq.core.pluginapi.inventory.PluginContainerDeployment; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.operation.OperationContext; +import org.rhq.core.system.SystemInfo; + +/** + * Represents a resource during the resource upgrade phase of discovery. + * + * @see ResourceUpgradeFacet + * + * @author Lukas Krejci + */ +@SuppressWarnings("unchecked") +public class ResourceUpgradeContext<T extends ResourceComponent> extends ResourceContext<T> { + + private final Configuration resourceConfiguration; + private final String name; + private final String description; + + /** + * @see ResourceContext#ResourceContext(Resource, ResourceComponent, ResourceDiscoveryComponent, SystemInfo, File, File, String, EventContext, OperationContext, ContentContext, Executor, PluginContainerDeployment) + */ + public ResourceUpgradeContext(Resource resource, T parentResourceComponent, + ResourceDiscoveryComponent resourceDiscoveryComponent, SystemInfo systemInfo, File temporaryDirectory, + File dataDirectory, String pluginContainerName, EventContext eventContext, OperationContext operationContext, + ContentContext contentContext, Executor availCollectorThreadPool, + PluginContainerDeployment pluginContainerDeployment) { + + super(resource, parentResourceComponent, resourceDiscoveryComponent, systemInfo, temporaryDirectory, dataDirectory, + pluginContainerName, eventContext, operationContext, contentContext, availCollectorThreadPool, + pluginContainerDeployment); + + this.resourceConfiguration = resource.getResourceConfiguration(); + this.name = resource.getName(); + this.description = resource.getDescription(); + } + + public ResourceUpgradeContext(Resource resource, ResourceDiscoveryComponent discoveryComponent, ResourceContext<T> context, Executor availCollectorThreadPool) { + this(resource, context.getParentResourceComponent(), discoveryComponent, context.getSystemInformation(), context.getTemporaryDirectory(), + context.getDataDirectory(), context.getPluginContainerName(), context.getEventContext(), context.getOperationContext(), + context.getContentContext(), availCollectorThreadPool, context.getPluginContainerDeployment()); + } + + public Configuration getResourceConfiguration() { + return resourceConfiguration; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } +} diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java new file mode 100644 index 0000000..b68b5df --- /dev/null +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/upgrade/ResourceUpgradeFacet.java @@ -0,0 +1,58 @@ +/* + * 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, 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.pluginapi.upgrade; + +import java.util.Map; +import java.util.Set; + +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pluginapi.inventory.ResourceComponent; + +/** + * This interface is to be implemented by discovery classes if they want to support + * upgrading the existing resources to a new format needed by an updated resource component. + * This is useful for example in the case when a new version of plugin redefined a resource + * key generation algorithm and wants to upgrade the legacy resources to use the new format. + * + * @author Lukas Krejci + */ +@SuppressWarnings("unchecked") +public interface ResourceUpgradeFacet<T extends ResourceComponent> { + + /** + * This method is called on the discovery component straight after it has finished the discovery. + * The exact same discovery results are passed to this method along with the set of resources + * that already exist in the inventory. + * + * @param inventoriedSimblings the existing resources + * @param parentContext the parent of both the newly discovered and existing resources + * @param discoveryResults the discovered resources. The resources from this set that have + * the same resource key as one of the inventoried siblings (after upgrade using the results of this method) won't + * be reported. + * @return the mapping of old resources to the newly desired data. The keys are instances from the + * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the + * corresponding siblings should be upgraded to. + */ + Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); +} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index feb2d81..866fd79 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -105,10 +105,10 @@ import org.rhq.core.pluginapi.inventory.ResourceComponent; import org.rhq.core.pluginapi.inventory.ResourceContext; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; -import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; -import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; import org.rhq.core.pluginapi.operation.OperationContext; import org.rhq.core.pluginapi.operation.OperationServices; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; import org.rhq.core.system.SystemInfo; import org.rhq.core.system.SystemInfoFactory; import org.rhq.core.util.exception.ThrowableUtil; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java index c60d4a8..e31ffda 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java @@ -46,8 +46,8 @@ import org.rhq.core.pc.plugin.PluginComponentFactory; import org.rhq.core.pluginapi.inventory.ProcessScanResult; import org.rhq.core.pluginapi.inventory.ResourceComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; -import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; -import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; import org.rhq.core.util.exception.ExceptionPackage; import org.rhq.core.util.exception.Severity;
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index 4d80ac1..45887f6 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -46,8 +46,8 @@ import org.rhq.core.pluginapi.inventory.ProcessScanResult; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; import org.rhq.core.pluginapi.inventory.ManualAddFacet; -import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; -import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeContext; +import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet; import org.rhq.core.pluginapi.util.FileUtils; import org.rhq.core.system.ProcessInfo; import org.rhq.plugins.apache.parser.ApacheConfigReader;
commit 15bea470c93d5a59c69cd8bea3dc0f0c2a728a37 Author: Lukas Krejci lkrejci@redhat.com Date: Tue May 25 18:17:02 2010 +0200
Update the resource with upgrade data only if the upgrade data is not null.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 8cc5280..feb2d81 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -1134,12 +1134,29 @@ public class InventoryManager extends AgentService implements ContainerService, }
if (serverUpdated) { - existingResource.setResourceKey(resourceKey); - existingResource.setName(name); - existingResource.setVersion(version); - existingResource.setDescription(description); - existingResource.setPluginConfiguration(pluginConfiguration); - existingResource.setResourceConfiguration(resourceConfiguration); + if (resourceKey != null) { + existingResource.setResourceKey(resourceKey); + } + + if (name != null) { + existingResource.setName(name); + } + + if (version != null) { + existingResource.setVersion(version); + } + + if (description != null) { + existingResource.setDescription(description); + } + + if (pluginConfiguration != null) { + existingResource.setPluginConfiguration(pluginConfiguration); + } + + if (resourceConfiguration != null) { + existingResource.setResourceConfiguration(resourceConfiguration); + } }
return serverUpdated;
commit 5c77f642a72f50fcb0c89613def447c39fcd1308 Author: Lukas Krejci lkrejci@redhat.com Date: Tue May 25 14:10:02 2010 +0200
First version of plugin-driven resource upgrade.
diff --git a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java index f542f57..cfa2459 100644 --- a/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java +++ b/modules/core/client-api/src/main/java/org/rhq/core/clientapi/server/discovery/DiscoveryServerService.java @@ -37,6 +37,7 @@ import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.ResourceErrorType; +import org.rhq.core.domain.resource.ResourceUpgradeReport;
/** * The interface to a JON server's resource discovery subsystem. @@ -137,6 +138,15 @@ public interface DiscoveryServerService { boolean updateResourceVersion(int resourceId, String version);
/** + * Upgrades the data of the resource according to the provided report. + * + * @param resourceId the id of the resource to be upgraded + * @param upgradeReport contains the information about the upgrade + * @return true if the upgrade succeeded, false otherwise. + */ + boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport); + + /** * Gives the server a chance to apply any necessary post-processing that's needed for newly committed resources * that have been successfully synchronized on the agent. * diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java new file mode 100644 index 0000000..52acf09 --- /dev/null +++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/ResourceUpgradeReport.java @@ -0,0 +1,102 @@ +/* + * 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, 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.resource; + +import java.io.Serializable; + +import org.rhq.core.domain.configuration.Configuration; + +/** + * Represents the changes that should be applied to the existing resource + * in order to upgrade it to conform to the new requirements set by the + * changed resource component. + * <p> + * Null values of the properties mean no change, non-null values represent + * the desired new values. + * + * @author Lukas Krejci + */ +public class ResourceUpgradeReport implements Serializable { + + private static final long serialVersionUID = 1L; + + private String newResourceKey; + private String newName; + private String newVersion; + private Configuration newPluginConfiguration; + private Configuration newResourceConfiguration; + private String newDescription; + + public ResourceUpgradeReport() { + + } + + public String getNewResourceKey() { + return newResourceKey; + } + + public void setNewResourceKey(String newResourceKey) { + this.newResourceKey = newResourceKey; + } + + public String getNewName() { + return newName; + } + + public void setNewName(String newName) { + this.newName = newName; + } + + public String getNewVersion() { + return newVersion; + } + + public void setNewVersion(String newVersion) { + this.newVersion = newVersion; + } + + public Configuration getNewPluginConfiguration() { + return newPluginConfiguration; + } + + public void setNewPluginConfiguration(Configuration newPluginConfiguration) { + this.newPluginConfiguration = newPluginConfiguration; + } + + public Configuration getNewResourceConfiguration() { + return newResourceConfiguration; + } + + public void setNewResourceConfiguration(Configuration newResourceConfiguration) { + this.newResourceConfiguration = newResourceConfiguration; + } + + public String getNewDescription() { + return newDescription; + } + + public void setNewDescription(String newDescription) { + this.newDescription = newDescription; + } +} diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java new file mode 100644 index 0000000..e8c5f03 --- /dev/null +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeContext.java @@ -0,0 +1,89 @@ +/* + * 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, 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.pluginapi.migration; + +import java.io.File; +import java.util.concurrent.Executor; + +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.resource.Resource; +import org.rhq.core.pluginapi.content.ContentContext; +import org.rhq.core.pluginapi.event.EventContext; +import org.rhq.core.pluginapi.inventory.PluginContainerDeployment; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.operation.OperationContext; +import org.rhq.core.system.SystemInfo; + +/** + * Represents a resource during the resource upgrade phase of discovery. + * + * @see ResourceUpgradeFacet + * + * @author Lukas Krejci + */ +@SuppressWarnings("unchecked") +public class ResourceUpgradeContext<T extends ResourceComponent> extends ResourceContext<T> { + + private final Configuration resourceConfiguration; + private final String name; + private final String description; + + /** + * @see ResourceContext#ResourceContext(Resource, ResourceComponent, ResourceDiscoveryComponent, SystemInfo, File, File, String, EventContext, OperationContext, ContentContext, Executor, PluginContainerDeployment) + */ + public ResourceUpgradeContext(Resource resource, T parentResourceComponent, + ResourceDiscoveryComponent resourceDiscoveryComponent, SystemInfo systemInfo, File temporaryDirectory, + File dataDirectory, String pluginContainerName, EventContext eventContext, OperationContext operationContext, + ContentContext contentContext, Executor availCollectorThreadPool, + PluginContainerDeployment pluginContainerDeployment) { + + super(resource, parentResourceComponent, resourceDiscoveryComponent, systemInfo, temporaryDirectory, dataDirectory, + pluginContainerName, eventContext, operationContext, contentContext, availCollectorThreadPool, + pluginContainerDeployment); + + this.resourceConfiguration = resource.getResourceConfiguration(); + this.name = resource.getName(); + this.description = resource.getDescription(); + } + + public ResourceUpgradeContext(Resource resource, ResourceDiscoveryComponent discoveryComponent, ResourceContext<T> context, Executor availCollectorThreadPool) { + this(resource, context.getParentResourceComponent(), discoveryComponent, context.getSystemInformation(), context.getTemporaryDirectory(), + context.getDataDirectory(), context.getPluginContainerName(), context.getEventContext(), context.getOperationContext(), + context.getContentContext(), availCollectorThreadPool, context.getPluginContainerDeployment()); + } + + public Configuration getResourceConfiguration() { + return resourceConfiguration; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } +} diff --git a/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.java b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.java new file mode 100644 index 0000000..df372bf --- /dev/null +++ b/modules/core/plugin-api/src/main/java/org/rhq/core/pluginapi/migration/ResourceUpgradeFacet.java @@ -0,0 +1,58 @@ +/* + * 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, 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.pluginapi.migration; + +import java.util.Map; +import java.util.Set; + +import org.rhq.core.domain.resource.ResourceUpgradeReport; +import org.rhq.core.pluginapi.inventory.ResourceComponent; + +/** + * This interface is to be implemented by discovery classes if they want to support + * upgrading the existing resources to a new format needed by an updated resource component. + * This is useful for example in the case when a new version of plugin redefined a resource + * key generation algorithm and wants to upgrade the legacy resources to use the new format. + * + * @author Lukas Krejci + */ +@SuppressWarnings("unchecked") +public interface ResourceUpgradeFacet<T extends ResourceComponent> { + + /** + * This method is called on the discovery component straight after it has finished the discovery. + * The exact same discovery results are passed to this method along with the set of resources + * that already exist in the inventory. + * + * @param inventoriedSimblings the existing resources + * @param parentContext the parent of both the newly discovered and existing resources + * @param discoveryResults the discovered resources. The resources from this set that have + * the same resource key as one of the inventoried siblings (after upgrade using the results of this method) won't + * be reported. + * @return the mapping of old resources to the newly desired data. The keys are instances from the + * inventoriedSiblings set, the values are the upgrade reports detailing what the data of the + * corresponding siblings should be upgraded to. + */ + Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, ResourceUpgradeContext<T> parentContext, Set<ResourceUpgradeContext> discoveryResults); +} diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java index b84cdbc..e8abbbf 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java @@ -183,7 +183,7 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport List<ProcessScanResult> scanResults = performProcessScans(processInfos, serverType);
Set<Resource> discoveredServers = this.inventoryManager.executeComponentDiscovery(serverType, - component, platformComponent, platformContainer.getResourceContext(), scanResults); + component, platformContainer, scanResults);
for (Resource discoveredServer : discoveredServers) { log.debug("Detected server " + discoveredServer); diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java index 8944b99..8cc5280 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java @@ -70,6 +70,7 @@ import org.rhq.core.domain.resource.ResourceCategory; import org.rhq.core.domain.resource.ResourceCreationDataType; import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.ResourceErrorType; +import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.pc.ContainerService; import org.rhq.core.pc.PluginContainer; @@ -104,6 +105,8 @@ import org.rhq.core.pluginapi.inventory.ResourceComponent; import org.rhq.core.pluginapi.inventory.ResourceContext; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; +import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; import org.rhq.core.pluginapi.operation.OperationContext; import org.rhq.core.pluginapi.operation.OperationServices; import org.rhq.core.system.SystemInfo; @@ -1110,6 +1113,38 @@ public class InventoryManager extends AgentService implements ContainerService, return resourceContainer.updateAvailability(availabilityType); }
+ private boolean mergeResourceFromUpgrade(Resource existingResource, ResourceUpgradeReport upgradeReport) { + String resourceKey = upgradeReport.getNewResourceKey(); + String name = upgradeReport.getNewName(); + String version = upgradeReport.getNewVersion(); + String description = upgradeReport.getNewDescription(); + Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); + Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); + + boolean serverUpdated = false; + try { + ServerServices serverServices = this.configuration.getServerServices(); + if (serverServices != null) { + DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService(); + + serverUpdated = discoveryServerService.upgradeResource(existingResource.getId(), upgradeReport); + } + } catch (Exception e) { + log.error("Failed to upgrade the resource [" + existingResource + "] on the server.", e); + } + + if (serverUpdated) { + existingResource.setResourceKey(resourceKey); + existingResource.setName(name); + existingResource.setVersion(version); + existingResource.setDescription(description); + existingResource.setPluginConfiguration(pluginConfiguration); + existingResource.setResourceConfiguration(resourceConfiguration); + } + + return serverUpdated; + } + public Resource mergeResourceFromDiscovery(Resource resource, Resource parent) throws PluginContainerException { // If the Resource is already in inventory, make sure its version is up-to-date, then simply return the // existing Resource. @@ -1336,20 +1371,8 @@ public class InventoryManager extends AgentService implements ContainerService, parentComponent = getResourceComponent(resource.getParentResource()); }
- File pluginDataDir = new File(this.configuration.getDataDirectory(), resource.getResourceType().getPlugin()); - - ResourceContext context = new ResourceContext(resource, // the resource itself - parentComponent, // its parent component - discoveryComponent, // the discovery component (this is actually the proxy to it) - SystemInfoFactory.createSystemInfo(), // for native access - this.configuration.getTemporaryDirectory(), // location for plugin to write temp files - pluginDataDir, // location for plugin to write data files - this.configuration.getContainerName(), // the name of the agent/PC - getEventContext(resource), // for event access - getOperationContext(resource), // for operation manager access - getContentContext(resource), // for content manager access - this.availabilityCollectors, // for components that want to perform async avail checking - this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do + ResourceContext context = createResourceContext(resource, parentComponent, discoveryComponent); + container.setResourceContext(context);
// Wrap the component in a proxy that will provide locking and a timeout for the call to start(). @@ -1396,6 +1419,23 @@ public class InventoryManager extends AgentService implements ContainerService, } }
+ private <T extends ResourceComponent> ResourceContext<T> createResourceContext(Resource resource, T parentComponent, ResourceDiscoveryComponent<T> discoveryComponent) { + File pluginDataDir = new File(this.configuration.getDataDirectory(), resource.getResourceType().getPlugin()); + + return new ResourceContext<T>(resource, // the resource itself + parentComponent, // its parent component + discoveryComponent, // the discovery component (this is actually the proxy to it) + SystemInfoFactory.createSystemInfo(), // for native access + this.configuration.getTemporaryDirectory(), // location for plugin to write temp files + pluginDataDir, // location for plugin to write data files + this.configuration.getContainerName(), // the name of the agent/PC + getEventContext(resource), // for event access + getOperationContext(resource), // for operation manager access + getContentContext(resource), // for content manager access + this.availabilityCollectors, // for components that want to perform async avail checking + this.configuration.getPluginContainerDeployment()); // helps components make determinations of what to do + } + /** * This will send a resource error to the server (if applicable) to indicate that the given resource could not be * connected to due to an invalid plugin configuration. @@ -1960,8 +2000,12 @@ public class InventoryManager extends AgentService implements ContainerService,
@NotNull Set<Resource> executeComponentDiscovery(ResourceType resourceType, ResourceDiscoveryComponent discoveryComponent, - ResourceComponent parentComponent, ResourceContext parentResourceContext, - List<ProcessScanResult> processScanResults) { + ResourceContainer parentContainer, List<ProcessScanResult> processScanResults) { + + ResourceContext parentResourceContext = parentContainer.getResourceContext(); + ResourceComponent parentComponent = parentContainer.getResourceComponent(); + Resource parentResource = parentContainer.getResource(); + long startTime = System.currentTimeMillis(); log.debug("Executing discovery for [" + resourceType.getName() + "] Resources..."); Set<Resource> newResources; @@ -2000,6 +2044,59 @@ public class InventoryManager extends AgentService implements ContainerService, newResources.add(newResource); } } + + //check for upgrade support + if (discoveryComponent instanceof ResourceUpgradeFacet) { + ResourceUpgradeFacet resourceUpgrade = (ResourceUpgradeFacet) discoveryComponent; + + Set<Resource> siblings = getResourcesWithType(resourceType, parentResource.getChildResources()); + + Resource grandParent = parentResource.getParentResource(); + ResourceContainer grandParentContainer = grandParent == null ? null : getResourceContainer(grandParent); + ResourceDiscoveryComponent parentDiscoveryComponent = PluginContainer.getInstance().getPluginComponentFactory() + .getDiscoveryComponent(parentResource.getResourceType(), grandParentContainer); + + ResourceUpgradeContext<?> parentUpgradeContext = new ResourceUpgradeContext(parentResource, parentDiscoveryComponent, parentResourceContext, availabilityCollectors); + + Set<ResourceUpgradeContext> siblingContexts = new HashSet<ResourceUpgradeContext>(siblings.size()); + + Map<ResourceUpgradeContext, Resource> siblingContextToResource = new HashMap<ResourceUpgradeContext, Resource>(); + + for (Resource sibling : siblings) { + ResourceUpgradeContext siblingContext = new ResourceUpgradeContext(sibling, discoveryComponent, getResourceContainer(sibling).getResourceContext(), availabilityCollectors); + siblingContexts.add(siblingContext); + siblingContextToResource.put(siblingContext, sibling); + } + + Set<ResourceUpgradeContext> newResourceContexts = new HashSet<ResourceUpgradeContext>(); + Map<String, Resource> newResourceKeyToResource = new HashMap<String, Resource>(); + + for (Resource newResource : newResources) { + ResourceUpgradeContext newUpgradeContext = new ResourceUpgradeContext(newResource, discoveryComponent, createResourceContext(newResource, parentComponent, discoveryComponent), availabilityCollectors); + newResourceContexts.add(newUpgradeContext); + newResourceKeyToResource.put(newResource.getResourceKey(), newResource); + } + + Map<ResourceUpgradeContext, ResourceUpgradeReport> results = resourceUpgrade.upgrade(siblingContexts, parentUpgradeContext, newResourceContexts); + + for(Map.Entry<ResourceUpgradeContext, ResourceUpgradeReport> upgradeEntry : results.entrySet()) { + Resource siblingToUpgrade = siblingContextToResource.get(upgradeEntry.getKey()); + ResourceUpgradeReport newData = upgradeEntry.getValue(); + + mergeResourceFromUpgrade(siblingToUpgrade, newData); + + //if there was a resource key upgrade, remove a resource with the same resource key + //from the discovery results. Otherwise we'd end up with 2 sibling resources with + //the same resource key, which is illegal. + if (newData.getNewResourceKey() != null) { + Resource newResourceToRemove = newResourceKeyToResource.get(newData.getNewResourceKey()); + if (newResourceToRemove != null) { + newResources.remove(newResourceToRemove); + } + } + } + } + } catch (Throwable e) { // TODO GH: Add server/parent - up/down semantics so this won't happen just because a server is not up long elapsedTime = System.currentTimeMillis() - startTime; diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java index c16ba56..c60d4a8 100644 --- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java +++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/RuntimeDiscoveryExecutor.java @@ -43,8 +43,11 @@ import org.rhq.core.domain.resource.ResourceType; import org.rhq.core.pc.PluginContainer; import org.rhq.core.pc.PluginContainerConfiguration; import org.rhq.core.pc.plugin.PluginComponentFactory; +import org.rhq.core.pluginapi.inventory.ProcessScanResult; import org.rhq.core.pluginapi.inventory.ResourceComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; +import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; import org.rhq.core.util.exception.ExceptionPackage; import org.rhq.core.util.exception.Severity;
@@ -237,8 +240,8 @@ public class RuntimeDiscoveryExecutor implements Runnable, Callable<InventoryRep + childResourceType + "]"); } Set<Resource> childResources = this.inventoryManager.executeComponentDiscovery(childResourceType, - discoveryComponent, parentComponent, parentContainer.getResourceContext(), Collections.EMPTY_LIST); - + discoveryComponent, parentContainer, Collections.<ProcessScanResult>emptyList()); + // For each discovered resource, update it in the inventory manager and recursively discover its child resources Map<String, Resource> mergedResources = new HashMap<String, Resource>();
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java index cded63b..2d3e9e6 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossBean.java @@ -56,6 +56,7 @@ import org.rhq.core.domain.resource.ProductVersion; 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.resource.ResourceUpgradeReport; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList; import org.rhq.core.domain.util.PageOrdering; @@ -400,6 +401,19 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot } }
+ public boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport) { + Resource existingResource = this.entityManager.find(Resource.class, resourceId); + if (existingResource != null) { + boolean changed = upgradeResource(existingResource, upgradeReport); + if (changed) { + this.entityManager.merge(existingResource); + } + return true; + } else { + return false; + } + } + /** * Convienence method that looks at <code>resource</code> and if its version is not * the same as <code>newVersion</code>, its version string will be set to it. If @@ -445,6 +459,81 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot return versionChanged; }
+ /** + * @param existingResource + * @param upgradeReport + * @return + */ + private boolean upgradeResource(Resource resource, ResourceUpgradeReport upgradeReport) { + boolean changed = false; + if (resource != null) { + String resourceKey = upgradeReport.getNewResourceKey(); + String name = upgradeReport.getNewName(); + String version = upgradeReport.getNewVersion(); + String description = upgradeReport.getNewDescription(); + Configuration pluginConfiguration = upgradeReport.getNewPluginConfiguration(); + Configuration resourceConfiguration = upgradeReport.getNewResourceConfiguration(); + + if (resourceKey != null) { + if (!equalOrNull(resourceKey, resource.getResourceKey())) { + log.info("Resource [" + resource + "] upgraded its resource key from [" + + resource.getResourceKey() + "] to [" + resourceKey + "]"); + changed = true; + resource.setResourceKey(resourceKey); + } + } + + if (name != null) { + if (!equalOrNull(name, resource.getName())) { + log.info("Resource [" + resource + "] upgraded its name from [" + + resource.getName() + "] to [" + name + "]"); + changed = true; + resource.setName(name); + } + } + + if (version != null) { + changed = updateResourceVersion(resource, version) || changed; + } + + if (description != null) { + if (!equalOrNull(description, resource.getDescription())) { + log.info("Resource [" + resource + "] upgraded its description from [" + + resource.getDescription() + "] to [" + description + "]"); + changed = true; + resource.setDescription(description); + } + } + + if (pluginConfiguration != null) { + if (!equalOrNull(pluginConfiguration, resource.getPluginConfiguration())) { + log.info("Resource [" + resource + "] upgraded its plugin configuration from [" + + resource.getPluginConfiguration() + "] to [" + pluginConfiguration + "]"); + changed = true; + resource.setPluginConfiguration(pluginConfiguration); + } + } + + if (resourceConfiguration != null) { + if (!equalOrNull(resourceConfiguration, resource.getResourceConfiguration())) { + //XXX Will this create a new history entry? + + log.info("Resource [" + resource + "] upgraded its resource configuration from [" + + resource.getResourceConfiguration() + "] to [" + resourceConfiguration + "]"); + + changed = true; + resource.setResourceConfiguration(resourceConfiguration); + } + } + + // If the resource was marked as deleted, reactivate it again. + if (resource.getInventoryStatus() == InventoryStatus.DELETED) { + resource.setInventoryStatus(InventoryStatus.COMMITTED); + } + } + return changed; + } + private void validateInventoryReport(InventoryReport report) throws InvalidInventoryReportException { for (Resource root : report.getAddedRoots()) { validateResource(root); @@ -793,4 +882,16 @@ public class DiscoveryBossBean implements DiscoveryBossLocal, DiscoveryBossRemot
updateInventoryStatus(subject, platforms, servers, target); } + + private static <T> boolean equalOrNull(T a, T b) { + if (a == null) { + return b == null; + } else { + if (b == null) { + return false; + } else { + return a.equals(b); + } + } + } } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java index 01394b9..4e60ffb 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryBossLocal.java @@ -38,6 +38,7 @@ import org.rhq.core.domain.resource.InventoryStatus; import org.rhq.core.domain.resource.Resource; import org.rhq.core.domain.resource.ResourceError; import org.rhq.core.domain.resource.ResourceType; +import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.domain.util.PageControl; import org.rhq.core.domain.util.PageList;
@@ -176,4 +177,13 @@ public interface DiscoveryBossLocal extends DiscoveryBossRemote { * <code>false</code> if the Resource was not in inventory */ boolean updateResourceVersion(int resourceId, String version); + + /** + * Upgrades the data of the resource according to the provided report. + * + * @param resourceId the id of the resource to be upgraded + * @param upgradeReport contains the information about the upgrade + * @return true if the upgrade succeeded, false otherwise. + */ + boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport); } \ No newline at end of file diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java index d692ad8..720465e 100644 --- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java +++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/discovery/DiscoveryServerServiceImpl.java @@ -37,6 +37,7 @@ 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.ResourceError; +import org.rhq.core.domain.resource.ResourceUpgradeReport; import org.rhq.core.util.collection.ArrayUtils; import org.rhq.core.util.exception.ThrowableUtil; import org.rhq.enterprise.server.alert.AlertDefinitionCreationException; @@ -176,6 +177,11 @@ public class DiscoveryServerServiceImpl implements DiscoveryServerService { return discoveryBoss.updateResourceVersion(resourceId, version); }
+ public boolean upgradeResource(int resourceId, ResourceUpgradeReport upgradeReport) { + DiscoveryBossLocal discoveryBoss = LookupUtil.getDiscoveryBoss(); + return discoveryBoss.upgradeResource(resourceId, upgradeReport); + } + private static Resource convertToPojoResource(Resource resource, boolean includeDescendants) { Resource pojoResource = new Resource(resource.getId()); pojoResource.setUuid(resource.getUuid()); diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java index 8f6deb7..4d80ac1 100644 --- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java +++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java @@ -21,8 +21,10 @@ package org.rhq.plugins.apache; import java.io.File; import java.io.IOException; import java.net.URI; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set;
import org.apache.commons.logging.Log; @@ -36,12 +38,16 @@ import org.rhq.augeas.util.GlobFilter; 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.resource.ResourceUpgradeReport; import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; import org.rhq.core.pluginapi.inventory.ManualAddFacet; import org.rhq.core.pluginapi.inventory.ProcessScanResult; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.core.pluginapi.inventory.ManualAddFacet; +import org.rhq.core.pluginapi.migration.ResourceUpgradeContext; +import org.rhq.core.pluginapi.migration.ResourceUpgradeFacet; import org.rhq.core.pluginapi.util.FileUtils; import org.rhq.core.system.ProcessInfo; import org.rhq.plugins.apache.parser.ApacheConfigReader; @@ -63,7 +69,8 @@ import org.rhq.rhqtransform.impl.PluginDescriptorBasedAugeasConfiguration; * @author Ian Springer * @author Lukas Krejci */ -public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponent<PlatformComponent>, ManualAddFacet<PlatformComponent> { +public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponent<PlatformComponent>, ManualAddFacet<PlatformComponent>, + ResourceUpgradeFacet<PlatformComponent> { private static final String PRODUCT_DESCRIPTION = "Apache Web Server";
private static final Log log = LogFactory.getLog(ApacheServerDiscoveryComponent.class); @@ -163,7 +170,46 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen return discoveredResources; }
- + public Map<ResourceUpgradeContext, ResourceUpgradeReport> upgrade(Set<ResourceUpgradeContext> inventoriedSimblings, + ResourceUpgradeContext<PlatformComponent> parentContext, Set<ResourceUpgradeContext> discoveryResults) { + + Map<ResourceUpgradeContext, ResourceUpgradeReport> ret = new HashMap<ResourceUpgradeContext, ResourceUpgradeReport>(); + + for (ResourceUpgradeContext context : inventoriedSimblings) { + String inventoriedResourceKey = context.getResourceKey(); + File inventoriedResourceKeyAsPath = new File(inventoriedResourceKey); + + //the resource key we use now is a full path to the httpdconf. + //in the old version, it was the server root. + //so if the inventoried resource key is a path to a file, + //we know it's a new style resource key. + if (inventoriedResourceKeyAsPath.isFile()) { + continue; + } + + Configuration pluginConfiguration = context.getPluginConfiguration(); + + String serverRoot = pluginConfiguration.getSimpleValue("serverRoot", null); + String httpdConf = pluginConfiguration.getSimpleValue("configFile", null); + + String resourceKey = null; + + if (httpdConf != null) { + File httpdConfFile = new File(httpdConf); + if (!httpdConfFile.isAbsolute()) { + httpdConfFile = new File(serverRoot, httpdConf); + } + + resourceKey = httpdConfFile.getPath(); + + ResourceUpgradeReport rep = new ResourceUpgradeReport(); + rep.setNewResourceKey(resourceKey); + + ret.put(context, rep); + } + } + return ret; + }
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig, ResourceDiscoveryContext<PlatformComponent> discoveryContext)
rhq-commits@lists.fedorahosted.org